Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RSJ-76] aggiunto import degli scheduling esterni in json #22

Merged
merged 1 commit into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import lombok.AllArgsConstructor;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import unical.demacs.rdm.config.ModelMapperExtended;
import unical.demacs.rdm.persistence.dto.*;
import unical.demacs.rdm.persistence.entities.Job;
Expand Down Expand Up @@ -140,4 +141,20 @@ public ResponseEntity<List<ScheduleDTO>> downloadSchedules() {
return ResponseEntity.ok(modelMapperExtended.mapList(schedules, ScheduleDTO.class));
}

@Operation(summary = "Import Schedules from JSON", description = "Upload and import Schedules from a JSON file.",
tags = {"json-controller"})
@PostMapping(value = "/upload-schedules", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Map<String, String>> importSchedules(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("message", "File is empty."));
}
jsonService.importSchedules(file);
return ResponseEntity.ok(Map.of("message", "Schedules imported successfully."));
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("message", "Error importing schedules: " + e.getMessage()));
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import unical.demacs.rdm.persistence.dto.*;
import unical.demacs.rdm.persistence.entities.Schedule;
import unical.demacs.rdm.persistence.repository.JobRepository;
import unical.demacs.rdm.persistence.repository.MachineRepository;
import unical.demacs.rdm.persistence.repository.MachineTypeRepository;
import unical.demacs.rdm.persistence.repository.ScheduleRepository;
import unical.demacs.rdm.persistence.service.interfaces.IJsonService;

Expand All @@ -17,6 +22,9 @@ public class JsonServiceImpl implements IJsonService {

private final ObjectMapper objectMapper;
private final ScheduleRepository scheduleRepository;
private final JobRepository jobRepository;
private final MachineRepository machineRepository;
private final MachineTypeRepository machineTypeRepository;

public List<ScheduleWithMachineDTO> readScheduleFile(String fileName) {
File file = new File(fileName);
Expand All @@ -28,4 +36,38 @@ public List<ScheduleWithMachineDTO> readScheduleFile(String fileName) {
}
}

@Override
public void importSchedules(MultipartFile file) {
try {
String jsonContent = new String(file.getBytes());
List<ScheduleWithMachineDTO> schedules = objectMapper.readValue(
jsonContent,
objectMapper.getTypeFactory().constructCollectionType(List.class, ScheduleWithMachineDTO.class)
);
for (ScheduleWithMachineDTO dto : schedules) {
Schedule schedule = mapDtoToEntity(dto);
scheduleRepository.save(schedule);
}
} catch (IOException e) {
throw new RuntimeException("Errore durante la lettura del file JSON: " + e.getMessage(), e);
}
}

private Schedule mapDtoToEntity(ScheduleWithMachineDTO dto) {
return Schedule.scheduleBuilder()
.job(jobRepository.findById(dto.getJobId())
.orElseThrow(() -> new RuntimeException("Job non trovato")))
.machineType(machineTypeRepository.findById(dto.getMachineTypeId())
.orElseThrow(() -> new RuntimeException("MachineType non trovato")))
.machine(dto.getMachineId() != null ?
machineRepository.findById(dto.getMachineId())
.orElseThrow(() -> new RuntimeException("Machine non trovata"))
: null)
.dueDate(dto.getDueDate())
.startTime(dto.getStartTime())
.duration(dto.getDuration())
.status(dto.getStatus())
.build();
}

}
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package unical.demacs.rdm.persistence.service.interfaces;


import org.springframework.web.multipart.MultipartFile;
import unical.demacs.rdm.persistence.dto.ScheduleWithMachineDTO;

import java.util.List;

public interface IJsonService {
public List<ScheduleWithMachineDTO> readScheduleFile(String fileName);
void importSchedules(MultipartFile file);

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
import unical.demacs.rdm.persistence.dto.ScheduleDTO;
import unical.demacs.rdm.persistence.dto.ScheduleWithMachineDTO;
import unical.demacs.rdm.persistence.enums.ScheduleStatus;
import unical.demacs.rdm.persistence.repository.JobRepository;
import unical.demacs.rdm.persistence.repository.MachineRepository;
import unical.demacs.rdm.persistence.repository.MachineTypeRepository;
import unical.demacs.rdm.persistence.repository.ScheduleRepository;
import unical.demacs.rdm.persistence.service.implementation.JsonServiceImpl;
import unical.demacs.rdm.persistence.service.interfaces.IJsonService;
Expand All @@ -29,13 +32,22 @@ public class JsonServiceImplTest {
@Mock
private IJsonService jsonService;

@Mock
private MachineRepository machineRepository;

@Mock
private MachineTypeRepository machineTypeRepository;

@Mock
private JobRepository jobRepository;

@Mock
private ScheduleRepository scheduleRepository;

@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
jsonService = new JsonServiceImpl(objectMapper, scheduleRepository);
jsonService = new JsonServiceImpl(objectMapper, scheduleRepository, jobRepository, machineRepository, machineTypeRepository);
}

@Test
Expand Down
2 changes: 2 additions & 0 deletions Frontend/src/app/components/schedule/schedule.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ <h2>Job partecipanti alla schedulazione</h2>
<div class="schedule-actions">
<button class="button" (click)="openSchedulingDialog()">Avvia Scheduling</button>
<button class="button" (click)="downloadSchedules()">Download Scheduling</button>
<button class="button" (click)="triggerFileInput()">Import Scheduling</button>
<input type="file" style="display: none;" (change)="importSchedules($event)" accept=".json" id="hiddenFileInput"/>
</div>
</div>
<div class="table-responsive">
Expand Down
34 changes: 34 additions & 0 deletions Frontend/src/app/components/schedule/schedule.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,5 +448,39 @@ export class ScheduleComponent implements OnInit {
machineLink.click();
});
}

triggerFileInput(): void {
const fileInput = document.getElementById('hiddenFileInput') as HTMLInputElement;
if (fileInput) {
fileInput.value = '';
fileInput.click();
} else {
console.error('Elemento file input non trovato.');
}
}

importSchedules(event: Event): void {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (file) {
console.log('File selezionato:', file);
if (file.type === 'application/json' || file.name.endsWith('.json')) {
console.log('Il file è un JSON valido.');
const formData = new FormData();
formData.append('file', file);
this.jsonService.importSchedulesForm(file).subscribe({
next:() => {
Swal.fire('Importato', 'Il file selezionato è stato importato con successo.', 'success');
},
error:() => {
Swal.fire('Errore', 'Errore durante l\'importazione. Riprova.', 'error');
}
});
} else {
Swal.fire('Errore', 'Il file selezionato non è un file JSON valido. Riprova.', 'error');
console.error('Formato file non valido:', file.type);
}
}
}

}
Loading