package com.softech.education.api; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.validation.Valid; import com.softech.education.constant.RoleName; import com.softech.education.entity.Employee; import com.softech.education.entity.Role; import com.softech.education.repository.EmployeeRepository; import com.softech.education.repository.RoleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/api") @RequiredArgsConstructor public class EmployeeController { @Autowired EmployeeRepository eRepository; @Autowired RoleRepository roleRepository; @GetMapping("/employee") public ResponseEntity> findAll() { return ResponseEntity.ok(eRepository.findAll()); } @PostMapping("/employee") public ResponseEntity create(@Valid @RequestBody Employee employee) { Role userRole = roleRepository.findRoleByName(RoleName.ROLE_EMPLOYEE); Set roles = Stream.of(userRole).collect(Collectors.toCollection(HashSet::new)); employee.setRoles(roles); return ResponseEntity.ok(eRepository.save(employee)); } @GetMapping("/employee/{id}") public ResponseEntity findById(@PathVariable(value = "id") Long employeeId) { return eRepository.findById(employeeId).map(record -> ResponseEntity.ok().body(record)) .orElse(ResponseEntity.notFound().build()); } @PutMapping("/{id}") public ResponseEntity update(@PathVariable(value = "id") Long employeeId, @Valid @RequestBody Employee employee) { return eRepository.findById(employeeId).map(record -> { record.setUsername(employee.getUsername()); record.setPassword(employee.getPassword()); record.setEmail(employee.getEmail()); record.setPhone(employee.getPhone()); record.setAvatarUrl(employee.getAvatarUrl()); record.setRoles(new HashSet<>(Arrays.asList(new Role(RoleName.ROLE_EMPLOYEE)))); record.setName(employee.getName()); record.setAdmin(employee.isAdmin()); Employee updated = eRepository.save(record); return ResponseEntity.ok().body(updated); }).orElse(ResponseEntity.notFound().build()); } // @DeleteMapping("/{id}") // public ResponseEntity delete(@PathVariable(value = "id") Long employeeId) { // return eRepository.findById(employeeId).map(record -> { // eRepository.deleteById(employeeId); // return ResponseEntity.ok().build(); // }).orElse(ResponseEntity.notFound().build()); // } }