Skip to content

Commit

Permalink
merge
Browse files Browse the repository at this point in the history
  • Loading branch information
PierpaoloSpadafora committed Dec 11, 2024
2 parents 553d67a + a2d5e08 commit 651ae95
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 1 deletion.
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 @@ -144,4 +145,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 @@ -449,4 +449,38 @@ export class ScheduleComponent implements OnInit {
});
}

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);
}
}
}

}

0 comments on commit 651ae95

Please sign in to comment.