94 lines
3.1 KiB
Java
94 lines
3.1 KiB
Java
package de.iwomm.propify_api.controller;
|
|
|
|
import de.iwomm.propify_api.dto.NewProjectDTO;
|
|
import de.iwomm.propify_api.dto.ProjectDTO;
|
|
import de.iwomm.propify_api.dto.ProjectDetailsDTO;
|
|
import de.iwomm.propify_api.dto.ProjectStatsDTO;
|
|
import de.iwomm.propify_api.entity.Project;
|
|
import de.iwomm.propify_api.mapper.ProjectMapper;
|
|
import de.iwomm.propify_api.service.ProjectService;
|
|
import jakarta.persistence.EntityNotFoundException;
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.security.access.prepost.PreAuthorize;
|
|
import org.springframework.web.bind.annotation.*;
|
|
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
|
|
|
import java.net.URI;
|
|
import java.util.List;
|
|
import java.util.UUID;
|
|
|
|
@RestController
|
|
@RequestMapping("/api/v1/projects")
|
|
public class ProjectController {
|
|
private final ProjectService projectService;
|
|
private final ProjectMapper projectMapper;
|
|
|
|
public ProjectController(ProjectService projectService, ProjectMapper projectMapper) {
|
|
this.projectService = projectService;
|
|
this.projectMapper = projectMapper;
|
|
}
|
|
|
|
@GetMapping
|
|
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
|
|
public ResponseEntity<?> getAll() {
|
|
List<ProjectDTO> projectDTOs = projectService.toDTOs(projectService.findAll());
|
|
|
|
return ResponseEntity
|
|
.ok(projectDTOs);
|
|
}
|
|
|
|
@GetMapping("/{id}")
|
|
@PreAuthorize("hasAnyRole('ADMIN', 'USER')")
|
|
public ResponseEntity<?> getById(@PathVariable UUID id) {
|
|
try {
|
|
Project project = projectService.findById(id).orElseThrow(EntityNotFoundException::new);
|
|
ProjectDetailsDTO projectDTO = this.projectMapper.projectToProjectDetailsDTO(project);
|
|
|
|
return ResponseEntity
|
|
.ok(projectDTO);
|
|
} catch (EntityNotFoundException e) {
|
|
return ResponseEntity
|
|
.notFound()
|
|
.build();
|
|
} catch (Exception e) {
|
|
return ResponseEntity
|
|
.internalServerError()
|
|
.build();
|
|
}
|
|
}
|
|
|
|
@GetMapping("/stats")
|
|
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
|
|
public ResponseEntity<?> getProjectStats() {
|
|
|
|
ProjectStatsDTO projectStatsDTO = this.projectService.getStatsDTO();
|
|
|
|
List<ProjectDTO> projectDTOs = projectService.toDTOs(projectService.findAll());
|
|
|
|
return ResponseEntity
|
|
.ok(projectStatsDTO);
|
|
}
|
|
|
|
|
|
@PostMapping
|
|
@PreAuthorize("hasRole('ADMIN')")
|
|
public ResponseEntity<?> create(@RequestBody NewProjectDTO newProjectDTO) {
|
|
try {
|
|
Project newItem = projectService.save(newProjectDTO);
|
|
|
|
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
|
|
.path("/{id}")
|
|
.buildAndExpand(newItem.getId())
|
|
.toUri();
|
|
|
|
return ResponseEntity
|
|
.created(location)
|
|
.body(newItem);
|
|
} catch (Exception e) {
|
|
return ResponseEntity
|
|
.internalServerError()
|
|
.build();
|
|
}
|
|
}
|
|
}
|