feat: Implement add employee to project route (SCRUM-2) (!32)
All checks were successful
Quality Check / Tests (push) Successful in 1m8s
Build / Build and analyze (push) Successful in 1m48s
Quality Check / Checkstyle Main (push) Successful in 38s
Release / Release (push) Successful in 45s

Co-authored-by: Phan Huy Tran <p.tran@neusta.de>
Reviewed-on: #32
Reviewed-by: Jan Gleytenhoover <krisellp9@gmail.com>
Co-authored-by: Phan Huy Tran <ptran@noreply.localhost>
Co-committed-by: Phan Huy Tran <ptran@noreply.localhost>
This commit is contained in:
Phan Huy Tran 2024-10-23 08:39:25 +00:00 committed by Jan Gleytenhoover
parent 1e38efaa63
commit 1008278fde
24 changed files with 246 additions and 34 deletions

@ -0,0 +1,12 @@
POST https://employee.szut.dev/employees
Authorization: Bearer {{auth_token}}
Content-Type: application/json
{
"firstName": "Jan",
"lastName": "Klattenhoff",
"street": "Pirolweg 17",
"postcode": "27777",
"city": "Gandakersee",
"phone": "017684984816"
}

@ -0,0 +1,2 @@
DELETE https://employee.szut.dev/employees/310
Authorization: Bearer {{auth_token}}

@ -0,0 +1,2 @@
GET https://employee.szut.dev/employees
Authorization: Bearer {{auth_token}}

@ -0,0 +1,2 @@
GET https://employee.szut.dev/employees/312
Authorization: Bearer {{auth_token}}

@ -0,0 +1,2 @@
POST http://localhost:8080/projects/1/employees/312
Authorization: Bearer {{auth_token}}

@ -0,0 +1,34 @@
package de.szut.lf8_starter.employee;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
@Service
public class EmployeeService {
private final RestTemplate restTemplate;
public EmployeeService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public boolean employeeExists(String accessToken, Long employeeId) {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken.replace("Bearer ", ""));
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = "https://employee.szut.dev/employees/" + employeeId;
try {
restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
} catch (HttpClientErrorException.NotFound e) {
return false;
}
return true;
}
}

@ -25,7 +25,7 @@ public class ProjectEntity {
private long leadingEmployee;
@ElementCollection
@ElementCollection(fetch = FetchType.EAGER)
private List<Long> employees;
private long contractor;

@ -25,10 +25,8 @@ public class ProjectService {
return projectRepository.findById(id);
}
public ProjectEntity update(ProjectEntity project) {
public void update(ProjectEntity project) {
this.projectRepository.save(project);
return project;
}
public void delete(Long id) {

@ -1,4 +1,4 @@
package de.szut.lf8_starter.project.action;
package de.szut.lf8_starter.project.action.crud;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectMapper;

@ -1,4 +1,4 @@
package de.szut.lf8_starter.project.action;
package de.szut.lf8_starter.project.action.crud;
import de.szut.lf8_starter.project.ProjectMapper;
import de.szut.lf8_starter.project.ProjectService;

@ -1,4 +1,4 @@
package de.szut.lf8_starter.project.action;
package de.szut.lf8_starter.project.action.crud;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectMapper;
@ -11,7 +11,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;

@ -1,4 +1,4 @@
package de.szut.lf8_starter.project.action;
package de.szut.lf8_starter.project.action.crud;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectMapper;

@ -0,0 +1,55 @@
package de.szut.lf8_starter.project.action.employee;
import de.szut.lf8_starter.employee.EmployeeService;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
public class AddEmployeeToProjectAction {
private final ProjectService projectService;
private final EmployeeService employeeService;
public AddEmployeeToProjectAction(ProjectService projectService, EmployeeService employeeService) {
this.projectService = projectService;
this.employeeService = employeeService;
}
@Operation(summary = "Add an employee to a project")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Employee added to project"),
@ApiResponse(responseCode = "404", description = "Project or employee not found", content = @Content)
})
@PostMapping("/projects/{projectId}/employees/{employeeId}")
public ResponseEntity<Object> create(
@PathVariable Long projectId,
@PathVariable Long employeeId,
@RequestHeader("Authorization") String accessToken
) {
Optional<ProjectEntity> project = this.projectService.findById(projectId);
if (project.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if (!this.employeeService.employeeExists(accessToken, employeeId)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
project.get().getEmployees().add(employeeId);
this.projectService.update(project.get());
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}

@ -0,0 +1,22 @@
package de.szut.lf8_starter.project.dto;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class EmployeeDto {
private long id;
private String firstName;
private String lastName;
private String street;
private String postcode;
private String city;
private String phone;
private List<String> skillSet;
}

@ -0,0 +1,77 @@
package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
class AddEmployeeToProjectActionIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private RestTemplate restTemplate;
@Autowired
private ProjectRepository projectRepository;
@Test
void addEmployeeToProjectTest() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setComment("comment");
project.setContractor(1);
project.setContractorName("contractorName");
project.setEndDate(LocalDate.of(2024, 1, 1));
project.setLeadingEmployee(1);
project.setName("name");
project.setStartDate(LocalDate.of(2021, 1, 1));
project.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project);
mockMvc.perform(post("/projects/{projectId}/employees/{employeeId}", 1, 312)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
ProjectEntity updatedProject = projectRepository.findById(1L).get();
assert updatedProject.getEmployees().contains(312L);
}
private String getBearerToken() {
String url = "https://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", "password");
map.add("client_id", "employee-management-service");
map.add("username", "user");
map.add("password", "test");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<Map> response = this.restTemplate.exchange(url, HttpMethod.POST, request, Map.class);
return Objects.requireNonNull(response.getBody()).get("access_token").toString();
}
}

@ -1,5 +1,6 @@
package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
@ -11,11 +12,12 @@ import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@ -41,7 +43,7 @@ class CreateProjectActionTest {
}
""";
final var contentAsString = this.mockMvc.perform(
final String contentAsString = this.mockMvc.perform(
post("/projects").content(content).contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isCreated())
@ -57,9 +59,9 @@ class CreateProjectActionTest {
.getResponse()
.getContentAsString();
final var id = Long.parseLong(new JSONObject(contentAsString).get("id").toString());
final long id = Long.parseLong(new JSONObject(contentAsString).get("id").toString());
final var project = this.projectRepository.findById(id);
final Optional<ProjectEntity> project = this.projectRepository.findById(id);
assertThat(project.get().getName()).isEqualTo("name");
assertThat(project.get().getLeadingEmployee()).isEqualTo(1);
assertThat(project.get().getContractor()).isEqualTo(4);

@ -26,7 +26,7 @@ class GetProjectActionTest {
@Test
void getProjectTest() throws Exception {
var project = new ProjectEntity();
ProjectEntity project = new ProjectEntity();
project.setId(1);
project.setComment("comment");
project.setContractor(1);
@ -54,6 +54,6 @@ class GetProjectActionTest {
@Test
void getProjectShouldReturnNotFoundResponseWhenProjectIsNotFound() throws Exception {
this.mockMvc.perform(get("/projects/2")).andExpect(status().isNotFound());
this.mockMvc.perform(get("/projects/1111")).andExpect(status().isNotFound());
}
}

@ -27,7 +27,7 @@ class ProjectFindAllSuccessTest {
@Test
void findAllProjectsTest() throws Exception {
var project = new ProjectEntity();
ProjectEntity project = new ProjectEntity();
project.setId(1);
project.setComment("comment");
project.setContractor(1);
@ -36,7 +36,7 @@ class ProjectFindAllSuccessTest {
project.setLeadingEmployee(1);
project.setName("name");
project.setStartDate(LocalDate.of(2021, 1, 1));
project.setEmployees(List.of(1L,2L,3L));
project.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project);
this.mockMvc.perform(get("/projects"))

@ -25,7 +25,7 @@ class RemoveProjectActionTest {
@Test
void deleteProjectTest() throws Exception {
var project = new ProjectEntity();
ProjectEntity project = new ProjectEntity();
project.setComment("comment");
project.setContractor(1);
project.setContractorName("contractorName");

@ -13,6 +13,7 @@ import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@ -55,7 +56,7 @@ class UpdateProjectActionTest {
}
""";
final var contentAsString = this.mockMvc.perform(
final String contentAsString = this.mockMvc.perform(
put("/projects/1").content(content).contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
@ -71,9 +72,9 @@ class UpdateProjectActionTest {
.getResponse()
.getContentAsString();
final var id = Long.parseLong(new JSONObject(contentAsString).get("id").toString());
final long id = Long.parseLong(new JSONObject(contentAsString).get("id").toString());
final var existingProject = this.projectRepository.findById(id);
final Optional<ProjectEntity> existingProject = this.projectRepository.findById(id);
assertThat(existingProject.get().getName()).isEqualTo("updatedName");
assertThat(existingProject.get().getLeadingEmployee()).isEqualTo(2);
assertThat(existingProject.get().getContractor()).isEqualTo(6);
@ -103,13 +104,13 @@ class UpdateProjectActionTest {
{}
""";
final var contentAsString = this.mockMvc.perform(
final String contentAsString = this.mockMvc.perform(
put("/projects/1").content(content).contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andExpect(jsonPath("name", is("name")))
.andExpect(jsonPath("leading_employee", is(1)))
.andExpect(jsonPath("employees", is(List.of(1,2,3))))
.andExpect(jsonPath("employees", is(List.of(1, 2, 3))))
.andExpect(jsonPath("contractor", is(1)))
.andExpect(jsonPath("contractor_name", is("contractorName")))
.andExpect(jsonPath("comment", is("comment")))
@ -120,9 +121,9 @@ class UpdateProjectActionTest {
.getResponse()
.getContentAsString();
final var id = Long.parseLong(new JSONObject(contentAsString).get("id").toString());
final long id = Long.parseLong(new JSONObject(contentAsString).get("id").toString());
final var existingProject = this.projectRepository.findById(id);
final Optional<ProjectEntity> existingProject = this.projectRepository.findById(id);
assertThat(existingProject.get().getName()).isEqualTo("name");
assertThat(existingProject.get().getLeadingEmployee()).isEqualTo(1);
assertThat(existingProject.get().getContractor()).isEqualTo(1);