├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── LICENSE ├── Procfile ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── herokuapp │ │ └── erpmesbackend │ │ └── erpmesbackend │ │ ├── ErpMesBackendApplication.java │ │ ├── RestErrorHandler.java │ │ ├── SetupController.java │ │ ├── communication │ │ ├── config │ │ │ ├── EmailConfig.java │ │ │ └── WebSocketConfiguration.java │ │ ├── controller │ │ │ ├── EmailController.java │ │ │ ├── NotificationController.java │ │ │ ├── SuggestionController.java │ │ │ └── WebSocketController.java │ │ ├── dto │ │ │ ├── NotificationDTO.java │ │ │ └── SuggestionDTO.java │ │ ├── factory │ │ │ ├── NotificationFactory.java │ │ │ └── SuggestionFactory.java │ │ ├── model │ │ │ ├── EmailEntity.java │ │ │ ├── EmailType.java │ │ │ ├── Notification.java │ │ │ ├── Phase.java │ │ │ ├── State.java │ │ │ └── Suggestion.java │ │ ├── repository │ │ │ ├── EmailEntityRepository.java │ │ │ ├── NotificationRepository.java │ │ │ └── SuggestionRepository.java │ │ ├── request │ │ │ ├── EmailEntityRequest.java │ │ │ ├── NotificationRequest.java │ │ │ └── SuggestionRequest.java │ │ └── service │ │ │ ├── EmailService.java │ │ │ ├── InboxService.java │ │ │ ├── NotificationService.java │ │ │ └── SuggestionService.java │ │ ├── exceptions │ │ ├── EntitiesConflictException.java │ │ ├── ForbiddenException.java │ │ ├── InvalidRequestException.java │ │ ├── NotAManagerException.java │ │ └── NotFoundException.java │ │ ├── production │ │ ├── controller │ │ │ ├── AssignmentController.java │ │ │ ├── IndicatorsController.java │ │ │ ├── PlanningController.java │ │ │ ├── ReportsController.java │ │ │ └── TaskController.java │ │ ├── dto │ │ │ └── TaskDTO.java │ │ ├── factory │ │ │ └── TaskFactory.java │ │ ├── model │ │ │ ├── Category.java │ │ │ ├── CurrentReport.java │ │ │ ├── DailyPlan.java │ │ │ ├── EstimatedCosts.java │ │ │ ├── Expense.java │ │ │ ├── ExpenseType.java │ │ │ ├── Indicators.java │ │ │ ├── MonthlyReport.java │ │ │ ├── SpecialPlan.java │ │ │ ├── Task.java │ │ │ └── Type.java │ │ ├── repository │ │ │ ├── CurrentReportRepository.java │ │ │ ├── DailyPlanRepository.java │ │ │ ├── EstimatedCostsRepository.java │ │ │ ├── ExpenseRepository.java │ │ │ ├── MonthlyReportRepository.java │ │ │ ├── SpecialPlanRepository.java │ │ │ └── TaskRepository.java │ │ ├── request │ │ │ ├── AssignmentRequest.java │ │ │ ├── DailyPlanRequest.java │ │ │ ├── EstimatedCostsRequest.java │ │ │ ├── ExpenseRequest.java │ │ │ ├── SpecialPlanRequest.java │ │ │ └── TaskRequest.java │ │ └── service │ │ │ ├── AssignmentService.java │ │ │ ├── IndicatorsService.java │ │ │ ├── PlanningService.java │ │ │ ├── ReportService.java │ │ │ └── TaskService.java │ │ ├── security │ │ ├── AuthController.java │ │ ├── Credentials.java │ │ ├── JwtAuthEntryPoint.java │ │ ├── JwtAuthFilter.java │ │ ├── JwtToken.java │ │ ├── JwtTokenUtil.java │ │ ├── SecurityConfig.java │ │ └── UserService.java │ │ ├── shop │ │ ├── controller │ │ │ ├── ComplaintController.java │ │ │ ├── DeliveryController.java │ │ │ ├── ItemController.java │ │ │ ├── OrderController.java │ │ │ └── ReturnController.java │ │ ├── factory │ │ │ └── ShopServiceFactory.java │ │ ├── model │ │ │ ├── Complaint.java │ │ │ ├── ComplaintStatus.java │ │ │ ├── Delivery.java │ │ │ ├── DeliveryItem.java │ │ │ ├── Item.java │ │ │ ├── Order.java │ │ │ ├── Resolution.java │ │ │ ├── Return.java │ │ │ ├── ReturnStatus.java │ │ │ └── Status.java │ │ ├── repository │ │ │ ├── ComplaintRepository.java │ │ │ ├── DeliveryItemRepository.java │ │ │ ├── DeliveryRepository.java │ │ │ ├── ItemRepository.java │ │ │ ├── OrderRepository.java │ │ │ └── ReturnRepository.java │ │ ├── request │ │ │ ├── DeliveryItemRequest.java │ │ │ ├── DeliveryRequest.java │ │ │ ├── ItemRequest.java │ │ │ └── ShopServiceRequest.java │ │ └── service │ │ │ ├── DeliveryService.java │ │ │ ├── ItemService.java │ │ │ └── ShopService.java │ │ └── staff │ │ ├── controller │ │ ├── EmployeeController.java │ │ ├── HolidayController.java │ │ └── TeamController.java │ │ ├── dto │ │ ├── EmployeeDTO.java │ │ ├── TeamDTO.java │ │ └── UserDTO.java │ │ ├── factory │ │ ├── EmployeeFactory.java │ │ └── HolidayFactory.java │ │ ├── model │ │ ├── ApprovalState.java │ │ ├── Contract.java │ │ ├── Employee.java │ │ ├── Holiday.java │ │ ├── HolidayType.java │ │ ├── Role.java │ │ └── Team.java │ │ ├── repository │ │ ├── ContractRepository.java │ │ ├── EmployeeRepository.java │ │ ├── HolidayRepository.java │ │ └── TeamRepository.java │ │ ├── request │ │ ├── AdminRequest.java │ │ ├── ContractRequest.java │ │ ├── EmployeeRequest.java │ │ └── HolidayRequest.java │ │ └── service │ │ ├── EmployeeService.java │ │ └── HolidayService.java └── resources │ ├── application.properties │ └── db │ └── changelog │ └── db.changelog-master.yaml └── test └── java └── com └── herokuapp └── erpmesbackend └── erpmesbackend └── erpmesbackend ├── ErpMesBackendApplicationTests.java ├── TestConfig.java └── controllers ├── ComplaintControllerTest.java ├── DeliveryControllerTest.java ├── EmailControllerTest.java ├── EmployeeControllerTest.java ├── HolidayControllerTest.java ├── ItemControllerTest.java ├── NotificationControllerTest.java ├── OrderControllerTest.java ├── PlanningControllerTest.java ├── ReportsControllerTest.java ├── ReturnControllerTest.java ├── SuggestionControllerTest.java └── TaskControllerTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plkpiotr/erp-mes-backend/ae8e15bab527fd41f9bfc5f85618f81861f007a0/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Piotr Pałka 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, channel to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: java -Dserver.port=$PORT $JAVA_OPTS -jar target/*.jar -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.herokuapp.erp-mes-backend 7 | erp-mes-backend 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | erp-mes-backend 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-actuator 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-data-jpa 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-security 39 | 40 | 41 | io.jsonwebtoken 42 | jjwt 43 | 0.6.0 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-web 48 | 49 | 50 | org.postgresql 51 | postgresql 52 | runtime 53 | 54 | 55 | org.projectlombok 56 | lombok 57 | 1.16.22 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-starter-test 62 | test 63 | 64 | 65 | org.springframework.security 66 | spring-security-test 67 | test 68 | 69 | 70 | javax.xml.bind 71 | jaxb-api 72 | 2.3.0 73 | 74 | 75 | org.liquibase 76 | liquibase-core 77 | 3.6.1 78 | 79 | 80 | org.springframework.boot 81 | spring-boot-starter-mail 82 | 2.0.4.RELEASE 83 | 84 | 85 | javax.mail 86 | javax.mail-api 87 | 1.6.2 88 | 89 | 90 | org.springframework.boot 91 | spring-boot-starter-websocket 92 | 1.5.2.RELEASE 93 | 94 | 95 | 96 | 97 | 98 | 99 | org.springframework.boot 100 | spring-boot-maven-plugin 101 | 102 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/ErpMesBackendApplication.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ErpMesBackendApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ErpMesBackendApplication.class, args); 11 | } 12 | } -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/RestErrorHandler.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.*; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.web.bind.annotation.ControllerAdvice; 7 | import org.springframework.web.bind.annotation.ExceptionHandler; 8 | import org.springframework.web.context.request.WebRequest; 9 | 10 | @ControllerAdvice 11 | public class RestErrorHandler { 12 | 13 | @ExceptionHandler(value = NotFoundException.class) 14 | public ResponseEntity handleNotFoundException(NotFoundException ex, WebRequest request) { 15 | return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); 16 | } 17 | 18 | @ExceptionHandler(value = NotAManagerException.class) 19 | public ResponseEntity handleNotAManagerException(NotAManagerException ex, WebRequest request) { 20 | return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); 21 | } 22 | 23 | @ExceptionHandler(value = InvalidRequestException.class) 24 | public ResponseEntity handleInvalidRequestException(InvalidRequestException ex, WebRequest request) { 25 | return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); 26 | } 27 | 28 | @ExceptionHandler(value = EntitiesConflictException.class) 29 | public ResponseEntity handleTeamConflictException(EntitiesConflictException ex, WebRequest request) { 30 | return new ResponseEntity<>(ex.getMessage(), HttpStatus.CONFLICT); 31 | } 32 | 33 | @ExceptionHandler(value = ForbiddenException.class) 34 | public ResponseEntity handleForbiddenException(ForbiddenException ex, WebRequest request) { 35 | return new ResponseEntity<>(ex.getMessage(), HttpStatus.FORBIDDEN); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/config/EmailConfig.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.mail.javamail.JavaMailSender; 6 | import org.springframework.mail.javamail.JavaMailSenderImpl; 7 | 8 | import java.util.Properties; 9 | 10 | @Configuration 11 | public class EmailConfig { 12 | 13 | @Bean 14 | public JavaMailSender getJavaMailSender() { 15 | JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); 16 | mailSender.setHost("smtp.gmail.com"); 17 | mailSender.setPort(587); 18 | 19 | mailSender.setUsername("erp.mes123@gmail.com"); 20 | mailSender.setPassword("erpmeserpmes"); 21 | 22 | Properties props = mailSender.getJavaMailProperties(); 23 | props.put("mail.transport.protocol", "smtp"); 24 | props.put("mail.smtp.ssl.trust", "*"); 25 | props.put("mail.smtp.auth", "true"); 26 | props.put("mail.smtp.starttls.enable", "true"); 27 | props.put("mail.debug", "true"); 28 | 29 | return mailSender; 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/config/WebSocketConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.messaging.simp.config.MessageBrokerRegistry; 5 | import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; 6 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; 7 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry; 8 | 9 | @Configuration 10 | @EnableWebSocketMessageBroker 11 | public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer { 12 | @Override 13 | public void registerStompEndpoints(StompEndpointRegistry registry) { 14 | registry.addEndpoint("/socket") 15 | .setAllowedOrigins("*") 16 | .withSockJS(); 17 | } 18 | 19 | @Override 20 | public void configureMessageBroker(MessageBrokerRegistry registry) { 21 | registry.setApplicationDestinationPrefixes("/app") 22 | .enableSimpleBroker("/chat"); 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/controller/EmailController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.repository.EmailEntityRepository; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.request.EmailEntityRequest; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.service.EmailService; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.EmailEntity; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.EmailType; 8 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.data.domain.Sort; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | import java.util.List; 15 | import java.util.stream.Collectors; 16 | 17 | @RestController 18 | @CrossOrigin("*") 19 | public class EmailController { 20 | 21 | private final String EMAIL_NOT_FOUND = "Such email doesn't exist!"; 22 | 23 | private final EmailEntityRepository emailEntityRepository; 24 | private final EmailService emailService; 25 | 26 | @Autowired 27 | public EmailController(EmailEntityRepository emailEntityRepository, EmailService emailService) { 28 | this.emailEntityRepository = emailEntityRepository; 29 | this.emailService = emailService; 30 | } 31 | 32 | @GetMapping("/emails/inbox") 33 | @ResponseStatus(HttpStatus.OK) 34 | public List readMail() { 35 | return emailService.readMail(); 36 | } 37 | 38 | @GetMapping("/emails/outbox") 39 | @ResponseStatus(HttpStatus.OK) 40 | public List readSentMail() { 41 | return emailEntityRepository.findAll(new Sort(Sort.Direction.DESC, "timestamp")) 42 | .stream() 43 | .filter(emailEntity -> emailEntity.getEmailType().equals(EmailType.SENT)) 44 | .collect(Collectors.toList()); 45 | } 46 | 47 | @PostMapping("/emails") 48 | @ResponseStatus(HttpStatus.CREATED) 49 | public EmailEntity sendMailWithAddress(@RequestBody EmailEntityRequest request) { 50 | return emailService.sendMessage(request.getEmail(), request.getSubject(), request.getContent()); 51 | } 52 | 53 | @GetMapping("/emails/{id}") 54 | @ResponseStatus(HttpStatus.OK) 55 | public List readConversation(@PathVariable("id") long id) { 56 | EmailEntity emailEntity = emailEntityRepository.findById(id) 57 | .orElseThrow(() -> new NotFoundException(EMAIL_NOT_FOUND)); 58 | return emailEntityRepository.findByEmailOrderByTimestampDesc(emailEntity.getEmail()) 59 | .orElseThrow(() -> new NotFoundException(EMAIL_NOT_FOUND)); 60 | } 61 | 62 | @PostMapping("/emails/{id}") 63 | @ResponseStatus(HttpStatus.CREATED) 64 | public EmailEntity sendMailWithAddrss(@RequestBody EmailEntityRequest request, 65 | @PathVariable("id") long id) { 66 | EmailEntity emailEntity = emailEntityRepository.findById(id) 67 | .orElseThrow(() -> new NotFoundException(EMAIL_NOT_FOUND)); 68 | emailService.checkIfEmailReceived(emailEntity); 69 | return emailService.sendMessage(emailEntity.getEmail(), request.getSubject(), 70 | request.getContent()); 71 | } 72 | 73 | @DeleteMapping("/emails/{id}") 74 | public HttpStatus removeEmail(@PathVariable("id") long id) { 75 | emailEntityRepository.delete(emailEntityRepository.findById(id) 76 | .orElseThrow(() -> new NotFoundException(EMAIL_NOT_FOUND))); 77 | return HttpStatus.NO_CONTENT; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/controller/NotificationController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.dto.NotificationDTO; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.request.NotificationRequest; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.service.NotificationService; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | import java.util.List; 10 | 11 | @RestController 12 | @CrossOrigin(origins = "*") 13 | public class NotificationController { 14 | 15 | private final NotificationService notificationService; 16 | 17 | public NotificationController(NotificationService notificationService) { 18 | this.notificationService = notificationService; 19 | } 20 | 21 | @GetMapping("/notifications") 22 | @ResponseStatus(HttpStatus.OK) 23 | public List getAllNotifications() { 24 | return notificationService.getAllNotifications(); 25 | } 26 | 27 | @GetMapping("/notifications/{id}") 28 | @ResponseStatus(HttpStatus.OK) 29 | public NotificationDTO getOneNotification(@PathVariable("id") Long id) { 30 | return notificationService.getOneNotification(id); 31 | } 32 | 33 | @GetMapping("/employees/{id}/notifications") 34 | @ResponseStatus(HttpStatus.OK) 35 | public List getNotificationsByConsignee(@PathVariable("id") Long id) { 36 | return notificationService.getNotificationsByConsignee(id); 37 | } 38 | 39 | @PostMapping("/notifications") 40 | @ResponseStatus(HttpStatus.CREATED) 41 | public NotificationDTO addOneNotification(@RequestBody NotificationRequest notificationRequest) { 42 | return notificationService.addOneNotification(notificationRequest); 43 | } 44 | 45 | @PutMapping("notifications/{id}") 46 | public NotificationDTO setNextState(@PathVariable("id") Long id) { 47 | return notificationService.setNextState(id); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/controller/SuggestionController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.dto.SuggestionDTO; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.request.SuggestionRequest; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.service.SuggestionService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import java.util.List; 11 | 12 | @RestController 13 | @CrossOrigin(origins = "*") 14 | public class SuggestionController { 15 | 16 | private final SuggestionService suggestionService; 17 | 18 | @Autowired 19 | public SuggestionController(SuggestionService suggestionService) { 20 | this.suggestionService = suggestionService; 21 | } 22 | 23 | @GetMapping("/suggestions") 24 | @ResponseStatus(HttpStatus.OK) 25 | public List getAllSuggestions() { 26 | return suggestionService.getAllSuggestions(); 27 | } 28 | 29 | @GetMapping("/suggestions/{id}") 30 | @ResponseStatus(HttpStatus.OK) 31 | public SuggestionDTO getOneSuggestion(@PathVariable("id") Long id) { 32 | return suggestionService.getOneSuggestion(id); 33 | } 34 | 35 | @PostMapping("/suggestions") 36 | @ResponseStatus(HttpStatus.CREATED) 37 | public SuggestionDTO addOneSuggestion(@RequestBody SuggestionRequest suggestionRequest) { 38 | return suggestionService.addOneSuggestion(suggestionRequest); 39 | } 40 | 41 | @PutMapping("suggestions/{id}") 42 | @ResponseStatus(HttpStatus.OK) 43 | public SuggestionDTO setNextPhase(@PathVariable("id") Long id) { 44 | return suggestionService.setNextPhase(id); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/controller/WebSocketController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.messaging.handler.annotation.MessageMapping; 5 | import org.springframework.messaging.simp.SimpMessagingTemplate; 6 | import org.springframework.stereotype.Controller; 7 | 8 | import java.text.SimpleDateFormat; 9 | import java.util.Date; 10 | 11 | @Controller 12 | public class WebSocketController { 13 | 14 | private final SimpMessagingTemplate template; 15 | 16 | @Autowired 17 | WebSocketController(SimpMessagingTemplate template) { 18 | this.template = template; 19 | } 20 | 21 | @MessageMapping("/send/message") 22 | public void onReceivedMessage(String message) { 23 | this.template.convertAndSend("/chat", 24 | new SimpleDateFormat("HH:mm:ss").format(new Date()) + " | " + message); 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/dto/NotificationDTO.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.dto; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.Notification; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.State; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.dto.EmployeeDTO; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Type; 7 | import lombok.AllArgsConstructor; 8 | import lombok.Data; 9 | 10 | import java.time.LocalDateTime; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | @Data 15 | @AllArgsConstructor 16 | public class NotificationDTO { 17 | 18 | private long id; 19 | private State state; 20 | private String instruction; 21 | private String description; 22 | private EmployeeDTO notifier; 23 | private EmployeeDTO transferee; 24 | private List consignees; 25 | private LocalDateTime creationTime; 26 | private Type type; 27 | private LocalDateTime startTime; 28 | private LocalDateTime endTime; 29 | private EmployeeDTO endEmployee; 30 | 31 | public NotificationDTO(Notification notification) { 32 | this.id = notification.getId(); 33 | this.state = notification.getState(); 34 | this.instruction = notification.getInstruction(); 35 | this.description = notification.getDescription(); 36 | this.notifier = new EmployeeDTO(notification.getNotifier()); 37 | this.consignees = new ArrayList<>(); 38 | notification.getConsignees().forEach(consignee -> this.consignees.add(new EmployeeDTO(consignee))); 39 | this.creationTime = notification.getCreationTime(); 40 | this.type = notification.getType(); 41 | 42 | if (notification.getStartTime() != null) { 43 | this.startTime = notification.getStartTime(); 44 | this.transferee = new EmployeeDTO(notification.getTransferee()); 45 | } 46 | 47 | if (notification.getEndTime() != null) { 48 | this.endTime = notification.getEndTime(); 49 | this.endEmployee = new EmployeeDTO(notification.getEndEmployee()); 50 | } 51 | } 52 | 53 | public NotificationDTO(String instruction, String description, EmployeeDTO notifier, List consignees, 54 | Type type) { 55 | this.instruction = instruction; 56 | this.description = description; 57 | this.notifier = notifier; 58 | this.consignees = consignees; 59 | this.type = type; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/dto/SuggestionDTO.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.dto; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.Phase; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.Suggestion; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.dto.EmployeeDTO; 6 | import lombok.AllArgsConstructor; 7 | import lombok.Data; 8 | 9 | import java.time.LocalDateTime; 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | @Data 14 | @AllArgsConstructor 15 | public class SuggestionDTO { 16 | 17 | private long id; 18 | private Phase phase; 19 | private String name; 20 | private String description; 21 | private EmployeeDTO author; 22 | private List recipients; 23 | private LocalDateTime creationTime; 24 | 25 | private LocalDateTime startTime; 26 | private LocalDateTime endTime; 27 | private EmployeeDTO startEmployee; 28 | private EmployeeDTO endEmployee; 29 | 30 | public SuggestionDTO(Suggestion suggestion) { 31 | this.id = suggestion.getId(); 32 | this.phase = suggestion.getPhase(); 33 | this.name = suggestion.getName(); 34 | this.description = suggestion.getDescription(); 35 | this.author = new EmployeeDTO(suggestion.getAuthor()); 36 | this.recipients = new ArrayList<>(); 37 | suggestion.getRecipients().forEach(recipient -> this.recipients.add(new EmployeeDTO(recipient))); 38 | this.creationTime = suggestion.getCreationTime(); 39 | 40 | if (suggestion.getStartTime() != null) { 41 | this.startTime = suggestion.getStartTime(); 42 | this.startEmployee = new EmployeeDTO(suggestion.getStartEmployee()); 43 | } 44 | 45 | if (suggestion.getEndTime() != null) { 46 | this.endTime = suggestion.getEndTime(); 47 | this.endEmployee = new EmployeeDTO(suggestion.getEndEmployee()); 48 | } 49 | } 50 | 51 | public SuggestionDTO(String name, String description, EmployeeDTO author, List recipientDTOs) { 52 | this.name = name; 53 | this.description = description; 54 | this.author = author; 55 | this.recipients = recipientDTOs; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/factory/NotificationFactory.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.factory; 2 | 3 | import java.util.Random; 4 | 5 | public class NotificationFactory { 6 | 7 | private String[] INSTRUCTIONS = {"Uszkodzona przesyłka", "Nieopłacone zamówienie", 8 | "Brak jednego przedmiotu"}; 9 | 10 | private String[] DESCRIPTIONS = {"Zadzwonić do odbiorcy", "Wykonać w pierwszej kolejności", 11 | "Przesłać uwagi przełożonemu"}; 12 | 13 | private final Random random; 14 | 15 | private String generate(String[] array) { 16 | return array[random.nextInt(array.length)]; 17 | } 18 | 19 | public NotificationFactory() { 20 | random = new Random(); 21 | } 22 | 23 | public String generateInstruction() { 24 | return generate(INSTRUCTIONS); 25 | } 26 | 27 | public String generateDescription() { 28 | return generate(DESCRIPTIONS); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/factory/SuggestionFactory.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.factory; 2 | 3 | import java.util.Random; 4 | 5 | public class SuggestionFactory { 6 | 7 | private final String[] NAMES = {"Przeprowadzić szkolenie", 8 | "Zorganizować spotkanie", 9 | "Zmienić liczbę osób"}; 10 | 11 | private final String[] DESCRIPTIONS = {"Propozycja przedstawiana przez wielu współpracowników", 12 | "Zgłoszone po konsultacjach z przełożonym", 13 | "Zaproponowane podczas konferencji"}; 14 | 15 | private final Random random; 16 | 17 | public SuggestionFactory() { 18 | random = new Random(); 19 | } 20 | 21 | private String generate(String[] array) { 22 | return array[random.nextInt(array.length)]; 23 | } 24 | 25 | public String generateName() { 26 | return generate(NAMES); 27 | } 28 | 29 | public String generateDescription() { 30 | return generate(DESCRIPTIONS); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/model/EmailEntity.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | import javax.validation.constraints.Email; 8 | import java.time.LocalDateTime; 9 | import java.util.List; 10 | 11 | @Entity 12 | @Getter 13 | @NoArgsConstructor 14 | public class EmailEntity { 15 | 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | 20 | @Email 21 | private String email; 22 | private String subject; 23 | 24 | @ElementCollection 25 | private List content; 26 | 27 | @Enumerated(EnumType.STRING) 28 | private EmailType emailType; 29 | 30 | LocalDateTime timestamp; 31 | 32 | public EmailEntity(@Email String email, String subject, List content, EmailType emailType, 33 | LocalDateTime timestamp) { 34 | this.email = email; 35 | this.subject = subject; 36 | this.content = content; 37 | this.emailType = emailType; 38 | this.timestamp = timestamp; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/model/EmailType.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.model; 2 | 3 | public enum EmailType { 4 | SENT, RECEIVED 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/model/Notification.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.model; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Type; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | 9 | import javax.persistence.*; 10 | import javax.validation.constraints.Size; 11 | import java.time.LocalDateTime; 12 | import java.util.List; 13 | 14 | @Entity 15 | @Getter 16 | @Setter 17 | @NoArgsConstructor 18 | public class Notification { 19 | 20 | @Id 21 | @GeneratedValue(strategy = GenerationType.IDENTITY) 22 | private long id; 23 | 24 | @Column(nullable = false) 25 | @Enumerated(EnumType.STRING) 26 | private State state; 27 | 28 | @Column(nullable = false) 29 | @Size(max = 25) 30 | private String instruction; 31 | 32 | @Size(max = 250) 33 | private String description; 34 | 35 | @OneToOne 36 | private Employee notifier; 37 | 38 | @OneToOne 39 | private Employee transferee; 40 | 41 | @Column(nullable = false) 42 | @ManyToMany 43 | private List consignees; 44 | 45 | @Column(nullable = false) 46 | private LocalDateTime creationTime; 47 | 48 | @Column(nullable = false) 49 | @Enumerated(EnumType.STRING) 50 | private Type type; 51 | 52 | private LocalDateTime startTime; 53 | private LocalDateTime endTime; 54 | 55 | @OneToOne 56 | private Employee endEmployee; 57 | 58 | public Notification(String instruction, String description, Employee notifier, List consignees, 59 | Type type) { 60 | this.state = State.REPORTED; 61 | this.instruction = instruction; 62 | this.description = description; 63 | this.notifier = notifier; 64 | this.transferee = null; 65 | this.consignees = consignees; 66 | this.creationTime = LocalDateTime.now(); 67 | this.type = type; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/model/Phase.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.model; 2 | 3 | public enum Phase { 4 | REPORTED, IN_IMPLEMENTATION, IMPLEMENTED; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/model/State.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.model; 2 | 3 | public enum State { 4 | REPORTED, IN_PROGRESS, RESOLVED; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/model/Suggestion.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.model; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | 8 | import javax.persistence.*; 9 | import javax.validation.constraints.Size; 10 | import java.time.LocalDateTime; 11 | import java.util.List; 12 | 13 | @Entity 14 | @Getter 15 | @Setter 16 | @NoArgsConstructor 17 | public class Suggestion { 18 | 19 | @Id 20 | @GeneratedValue(strategy = GenerationType.IDENTITY) 21 | private long id; 22 | 23 | @Column(nullable = false) 24 | @Enumerated(EnumType.STRING) 25 | private Phase phase; 26 | 27 | @Column(nullable = false) 28 | @Size(max = 25) 29 | private String name; 30 | 31 | @Column(nullable = false) 32 | @Size(max = 250) 33 | private String description; 34 | 35 | @OneToOne 36 | private Employee author; 37 | 38 | @Column(nullable = false) 39 | @ManyToMany 40 | private List recipients; 41 | 42 | @Column(nullable = false) 43 | private LocalDateTime creationTime; 44 | 45 | private LocalDateTime startTime; 46 | private LocalDateTime endTime; 47 | 48 | @OneToOne 49 | private Employee startEmployee; 50 | 51 | @OneToOne 52 | private Employee endEmployee; 53 | 54 | public Suggestion(String name, String description, Employee author, List recipients) { 55 | this.phase = Phase.REPORTED; 56 | this.name = name; 57 | this.description = description; 58 | this.author = author; 59 | this.recipients = recipients; 60 | this.creationTime = LocalDateTime.now(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/repository/EmailEntityRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.EmailEntity; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.List; 8 | import java.util.Optional; 9 | 10 | @Repository 11 | public interface EmailEntityRepository extends JpaRepository { 12 | 13 | Optional> findByEmailOrderByTimestampDesc(String email); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/repository/NotificationRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.Notification; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Query; 6 | import org.springframework.data.repository.query.Param; 7 | 8 | import java.time.LocalDateTime; 9 | import java.util.List; 10 | import java.util.Optional; 11 | 12 | public interface NotificationRepository extends JpaRepository { 13 | 14 | long countNotificationsByTransfereeIdAndCreationTimeAfter(Long id, LocalDateTime timeRange); 15 | 16 | long countNotificationsByConsigneesIdAndCreationTimeAfter(Long id, LocalDateTime timeRange); 17 | 18 | @Query(value = "SELECT EXTRACT(EPOCH FROM (SELECT avg(n.start_time - n.creation_time) FROM notification n WHERE transferee_id = :transferee_id))", 19 | nativeQuery = true) 20 | Long countAverageDifferenceBetweenStartTimeAndCreationTime(@Param("transferee_id") Long transferee_id); 21 | 22 | @Query(value = "SELECT EXTRACT(EPOCH FROM (SELECT avg(n.start_time - n.creation_time) FROM notification n))", 23 | nativeQuery = true) 24 | Long countAverageDifferenceBetweenStartTimeAndCreationTime(); 25 | 26 | @Query(value = "SELECT EXTRACT(EPOCH FROM (SELECT avg(n.end_time - n.start_time) FROM notification n WHERE transferee_id = :transferee_id))", 27 | nativeQuery = true) 28 | Long countAverageDifferenceBetweenEndTimeAndStartTime(@Param("transferee_id") Long transferee_id); 29 | 30 | @Query(value = "SELECT EXTRACT(EPOCH FROM (SELECT avg(n.end_time - n.start_time) FROM notification n))", 31 | nativeQuery = true) 32 | Long countAverageDifferenceBetweenEndTimeAndStartTime(); 33 | 34 | Optional> findByConsigneesId(Long id); 35 | 36 | Optional> findByNotifierId(Long id); 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/repository/SuggestionRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.Phase; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.Suggestion; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.time.LocalDateTime; 9 | import java.util.List; 10 | import java.util.Optional; 11 | 12 | @Repository 13 | public interface SuggestionRepository extends JpaRepository { 14 | 15 | long countSuggestionsByAuthorIdAndCreationTimeAfter(Long id, LocalDateTime timeRange); 16 | 17 | long countSuggestionsByCreationTimeAfter(LocalDateTime timeRange); 18 | 19 | long countSuggestionsByAuthorIdAndPhaseAndCreationTimeAfter(Long id, Phase phase, LocalDateTime timeRange); 20 | 21 | long countSuggestionsByPhaseAndCreationTimeAfter(Phase phase, LocalDateTime timeRange); 22 | 23 | Optional> findByRecipientsId(Long id); 24 | 25 | Optional> findByAuthorId(Long id); 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/request/EmailEntityRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | import javax.validation.constraints.NotNull; 7 | import java.util.List; 8 | 9 | @Data 10 | @AllArgsConstructor 11 | public class EmailEntityRequest { 12 | 13 | private String email; 14 | 15 | @NotNull 16 | private String subject; 17 | 18 | @NotNull 19 | private List content; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/request/NotificationRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.request; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Type; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | import lombok.NonNull; 8 | 9 | import java.util.List; 10 | 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | public class NotificationRequest { 15 | 16 | @NonNull 17 | private String instruction; 18 | 19 | private String description; 20 | 21 | @NonNull 22 | private List consigneeIds; 23 | 24 | @NonNull 25 | private Type type; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/request/SuggestionRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | import lombok.NonNull; 7 | 8 | import java.util.List; 9 | 10 | @Data 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | public class SuggestionRequest { 14 | 15 | @NonNull 16 | private String name; 17 | 18 | @NonNull 19 | private String description; 20 | 21 | @NonNull 22 | private List recipientIds; 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/service/InboxService.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.service; 2 | 3 | 4 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.EmailEntity; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.EmailType; 6 | 7 | import javax.mail.*; 8 | import javax.mail.Message; 9 | import java.time.Instant; 10 | import java.time.LocalDateTime; 11 | import java.time.ZoneId; 12 | import java.util.*; 13 | 14 | public class InboxService { 15 | 16 | public List readMail() { 17 | Properties props = new Properties(); 18 | props.put("mail.smtp.host", "gmail"); 19 | props.put("mail.smtp.socketFactory.port", "465"); 20 | props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 21 | props.put("mail.smtp.auth", "true"); 22 | props.put("mail.smtp.port", "465"); 23 | props.put("mail.smtp.ssl.trust", "*"); 24 | 25 | Session session = Session.getDefaultInstance(props, null); 26 | List emailEntityList = new ArrayList<>(); 27 | 28 | try { 29 | Store store = session.getStore("imaps"); 30 | store.connect("smtp.gmail.com", "erp.mes123@gmail.com", "erpmeserpmes"); 31 | 32 | Folder folder = store.getFolder("inbox"); 33 | folder.open(Folder.READ_ONLY); 34 | javax.mail.Message[] messages = folder.getMessages(); 35 | 36 | for (Message message : messages) { 37 | String address = message.getFrom()[0].toString(); 38 | String emailAddress = address.substring(address.indexOf("<") + 1, 39 | address.lastIndexOf(">")); 40 | Date receivedDate = message.getReceivedDate(); 41 | Instant instant = receivedDate.toInstant(); 42 | ZoneId zoneId = ZoneId.systemDefault(); 43 | LocalDateTime receivedDateTime = instant.atZone(zoneId).toLocalDateTime(); 44 | 45 | List content = new ArrayList<>(); 46 | Multipart multipart = (Multipart) message.getContent(); 47 | int j = 0; 48 | boolean reachedHtml = false; 49 | while (j < multipart.getCount() && !reachedHtml) { 50 | BodyPart bodyPart = multipart.getBodyPart(j); 51 | String contentPart = (String) bodyPart.getContent(); 52 | if (contentPart.contains("html")) { 53 | reachedHtml = true; 54 | } else { 55 | if (contentPart.length() >= 255) { 56 | for (int i = 0; i < contentPart.length()/255; i++) { 57 | content.add(contentPart.substring(i*255, (i+1)*255)); 58 | } 59 | } else { 60 | content.add(contentPart); 61 | } 62 | } 63 | j++; 64 | } 65 | emailEntityList.add(new EmailEntity(emailAddress, message.getSubject(), content, 66 | EmailType.RECEIVED, receivedDateTime)); 67 | } 68 | folder.close(true); 69 | store.close(); 70 | } catch (Exception e) { 71 | e.printStackTrace(); 72 | } 73 | return emailEntityList; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/communication/service/SuggestionService.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.communication.service; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.dto.SuggestionDTO; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.Phase; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.Suggestion; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.repository.SuggestionRepository; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.request.SuggestionRequest; 8 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 9 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 10 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.repository.EmployeeRepository; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.security.core.context.SecurityContextHolder; 13 | import org.springframework.security.core.userdetails.UserDetails; 14 | import org.springframework.stereotype.Service; 15 | 16 | import java.time.LocalDateTime; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.stream.Collectors; 20 | 21 | @Service 22 | public class SuggestionService { 23 | 24 | private final SuggestionRepository suggestionRepository; 25 | private final EmployeeRepository employeeRepository; 26 | 27 | @Autowired 28 | public SuggestionService(SuggestionRepository suggestionRepository, EmployeeRepository employeeRepository) { 29 | this.suggestionRepository = suggestionRepository; 30 | this.employeeRepository = employeeRepository; 31 | } 32 | 33 | public List getAllSuggestions() { 34 | Employee author = employeeRepository.findByEmail(getEmailLoggedInUser()).get(); 35 | List suggestions = new ArrayList<>(); 36 | List ownSuggestions; 37 | 38 | if (author.isManager()) { 39 | suggestions = suggestionRepository.findAll(); 40 | } else { 41 | if (suggestionRepository.findByRecipientsId(author.getId()).isPresent()) { 42 | suggestions = suggestionRepository.findByRecipientsId(author.getId()).get(); 43 | } 44 | if (suggestionRepository.findByAuthorId(author.getId()).isPresent()) { 45 | ownSuggestions = suggestionRepository.findByAuthorId(author.getId()).get(); 46 | suggestions.addAll(ownSuggestions); 47 | suggestions = suggestions.stream().distinct().collect(Collectors.toList()); 48 | } 49 | } 50 | 51 | List suggestionDTOs = new ArrayList<>(); 52 | suggestions.forEach(suggestion -> suggestionDTOs.add(new SuggestionDTO(suggestion))); 53 | return suggestionDTOs; 54 | } 55 | 56 | public SuggestionDTO getOneSuggestion(Long id) { 57 | checkIfSuggestionExists(id); 58 | return new SuggestionDTO(suggestionRepository.findById(id).get()); 59 | } 60 | 61 | public SuggestionDTO addOneSuggestion(SuggestionRequest suggestionRequest) { 62 | String name = suggestionRequest.getName(); 63 | String details = suggestionRequest.getDescription(); 64 | 65 | Employee author = employeeRepository.findByEmail(getEmailLoggedInUser()).get(); 66 | 67 | List recipients = new ArrayList<>(); 68 | suggestionRequest.getRecipientIds().forEach(this::checkIfRecipientExists); 69 | suggestionRequest.getRecipientIds().forEach(id -> recipients.add(employeeRepository.findById(id).get())); 70 | 71 | Suggestion suggestion = new Suggestion(name, details, author, recipients); 72 | suggestionRepository.save(suggestion); 73 | return new SuggestionDTO(suggestion); 74 | } 75 | 76 | public SuggestionDTO setNextPhase(Long id) { 77 | checkIfSuggestionExists(id); 78 | Suggestion suggestion = suggestionRepository.findById(id).get(); 79 | 80 | Employee employee = employeeRepository.findByEmail(getEmailLoggedInUser()).get(); 81 | 82 | if (suggestion.getPhase() == Phase.REPORTED) { 83 | suggestion.setPhase(Phase.IN_IMPLEMENTATION); 84 | suggestion.setStartTime(LocalDateTime.now()); 85 | suggestion.setStartEmployee(employee); 86 | } else if (suggestion.getPhase() == Phase.IN_IMPLEMENTATION) { 87 | suggestion.setPhase(Phase.IMPLEMENTED); 88 | suggestion.setEndTime(LocalDateTime.now()); 89 | suggestion.setEndEmployee(employee); 90 | } 91 | 92 | suggestionRepository.save(suggestion); 93 | return new SuggestionDTO(suggestion); 94 | } 95 | 96 | private String getEmailLoggedInUser() { 97 | Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 98 | return ((UserDetails) principal).getUsername(); 99 | } 100 | 101 | private void checkIfSuggestionExists(Long id) { 102 | if (!suggestionRepository.findById(id).isPresent()) { 103 | throw new NotFoundException("Such suggestion doesn't exist!"); 104 | } 105 | } 106 | 107 | private void checkIfRecipientExists(Long id) { 108 | if (!employeeRepository.findById(id).isPresent()) { 109 | throw new NotFoundException("At least one of the recipients doesn't exist!"); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/exceptions/EntitiesConflictException.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.exceptions; 2 | 3 | public class EntitiesConflictException extends RuntimeException { 4 | 5 | public EntitiesConflictException() { 6 | super(); 7 | } 8 | 9 | public EntitiesConflictException(String msg) { 10 | super(msg); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/exceptions/ForbiddenException.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.exceptions; 2 | 3 | public class ForbiddenException extends RuntimeException { 4 | 5 | public ForbiddenException() { 6 | super(); 7 | } 8 | 9 | public ForbiddenException(String msg) { 10 | super(msg); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/exceptions/InvalidRequestException.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.exceptions; 2 | 3 | public class InvalidRequestException extends RuntimeException { 4 | 5 | public InvalidRequestException() { 6 | super(); 7 | } 8 | 9 | public InvalidRequestException(String message) { 10 | super(message); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/exceptions/NotAManagerException.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.exceptions; 2 | 3 | public class NotAManagerException extends RuntimeException { 4 | 5 | public NotAManagerException() { 6 | super(); 7 | } 8 | 9 | public NotAManagerException(String message) { 10 | super(message); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/exceptions/NotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.exceptions; 2 | 3 | public class NotFoundException extends RuntimeException { 4 | 5 | public NotFoundException() { 6 | super(); 7 | } 8 | 9 | public NotFoundException(String message) { 10 | super(message); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/controller/AssignmentController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.dto.TaskDTO; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.AssignmentRequest; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.production.service.AssignmentService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import java.util.List; 11 | 12 | @RestController 13 | @CrossOrigin(origins = "*") 14 | public class AssignmentController { 15 | 16 | private final AssignmentService assignmentService; 17 | 18 | @Autowired 19 | public AssignmentController(AssignmentService assignmentService) { 20 | this.assignmentService = assignmentService; 21 | } 22 | 23 | @GetMapping("/assignment") 24 | @ResponseStatus(HttpStatus.OK) 25 | public List getTasksByAssigneeIsNull() { 26 | return assignmentService.getTasksByAssigneeIsNull(); 27 | } 28 | 29 | @PutMapping("/assignment") 30 | @ResponseStatus(HttpStatus.OK) 31 | public HttpStatus assignToEmployees(@RequestBody AssignmentRequest assignmentRequest) { 32 | assignmentService.assignToEmployees(assignmentRequest); 33 | return HttpStatus.OK; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/controller/IndicatorsController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Indicators; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.service.IndicatorsService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | @RestController 10 | @CrossOrigin(origins = "*") 11 | public class IndicatorsController { 12 | 13 | private final IndicatorsService indicatorsService; 14 | 15 | @Autowired 16 | public IndicatorsController(IndicatorsService indicatorsService) { 17 | this.indicatorsService = indicatorsService; 18 | } 19 | 20 | @GetMapping("/indicators/{id}") 21 | @ResponseStatus(HttpStatus.OK) 22 | public Indicators getIndicators(@PathVariable("id") Long id) { 23 | return indicatorsService.getIndicators(id); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/controller/PlanningController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.DailyPlan; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.SpecialPlan; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.production.repository.DailyPlanRepository; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.production.repository.SpecialPlanRepository; 8 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.DailyPlanRequest; 9 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.SpecialPlanRequest; 10 | import com.herokuapp.erpmesbackend.erpmesbackend.production.service.PlanningService; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.format.annotation.DateTimeFormat; 13 | import org.springframework.http.HttpStatus; 14 | import org.springframework.web.bind.annotation.*; 15 | 16 | import java.time.LocalDate; 17 | import java.util.List; 18 | import java.util.Optional; 19 | 20 | @RestController 21 | @CrossOrigin("*") 22 | public class PlanningController { 23 | 24 | private final DailyPlanRepository dailyPlanRepository; 25 | private final SpecialPlanRepository specialPlanRepository; 26 | private final PlanningService planningService; 27 | 28 | @Autowired 29 | public PlanningController(DailyPlanRepository dailyPlanRepository, SpecialPlanRepository specialPlanRepository, 30 | PlanningService planningService) { 31 | this.dailyPlanRepository = dailyPlanRepository; 32 | this.specialPlanRepository = specialPlanRepository; 33 | this.planningService = planningService; 34 | } 35 | 36 | @GetMapping("/daily-plan") 37 | @ResponseStatus(HttpStatus.OK) 38 | public DailyPlan getDailyPlan() { 39 | return dailyPlanRepository.findById(1L) 40 | .orElseThrow(NotFoundException::new); 41 | } 42 | 43 | @PutMapping("/daily-plan") 44 | @ResponseStatus(HttpStatus.OK) 45 | public DailyPlan updateDailyPlan(@RequestBody DailyPlanRequest request) { 46 | return planningService.updateDailyPlan(request); 47 | } 48 | 49 | @GetMapping("/scheduled-orders") 50 | @ResponseStatus(HttpStatus.OK) 51 | public int getOrdersScheduledForDay(@RequestParam("when") String when) { 52 | return planningService.getOrdersForDay(when).size(); 53 | } 54 | 55 | @GetMapping("/scheduled-returns") 56 | @ResponseStatus(HttpStatus.OK) 57 | public int getReturnsScheduledForDay(@RequestParam("when") String when) { 58 | return planningService.getReturnsForDay(when).size(); 59 | } 60 | 61 | @GetMapping("/scheduled-complaints") 62 | @ResponseStatus(HttpStatus.OK) 63 | public int getComplaintsScheduledForDay(@RequestParam("when") String when) { 64 | return planningService.getComplaintsForDay(when).size(); 65 | } 66 | 67 | @GetMapping("/special-plans") 68 | @ResponseStatus(HttpStatus.OK) 69 | public List getSpecialPlans() { 70 | return specialPlanRepository.findAll(); 71 | } 72 | 73 | @GetMapping("/special-plan") 74 | @ResponseStatus(HttpStatus.OK) 75 | public SpecialPlan findSpecialPlan(@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) 76 | @RequestParam("day") LocalDate day) { 77 | Optional> byDay = specialPlanRepository.findByDay(day); 78 | return byDay.isPresent() ? byDay.get().get(byDay.get().size()-1) : new SpecialPlan(); 79 | } 80 | 81 | @PostMapping("/special-plan") 82 | @ResponseStatus(HttpStatus.CREATED) 83 | public SpecialPlan addSpecialPlan(@RequestBody SpecialPlanRequest request) { 84 | SpecialPlan specialPlan = request.extractSpecialPlan(); 85 | specialPlanRepository.save(specialPlan); 86 | return specialPlan; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/controller/ReportsController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.CurrentReport; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.MonthlyReport; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.production.repository.CurrentReportRepository; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.production.repository.EstimatedCostsRepository; 8 | import com.herokuapp.erpmesbackend.erpmesbackend.production.repository.ExpenseRepository; 9 | import com.herokuapp.erpmesbackend.erpmesbackend.production.repository.MonthlyReportRepository; 10 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.EstimatedCostsRequest; 11 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.ExpenseRequest; 12 | import com.herokuapp.erpmesbackend.erpmesbackend.production.service.ReportService; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.http.HttpStatus; 15 | import org.springframework.web.bind.annotation.*; 16 | 17 | import java.util.List; 18 | 19 | @RestController 20 | @CrossOrigin(origins = "*") 21 | public class ReportsController { 22 | 23 | private final String REPORT_NOT_FOUND = "Such report doesn't exist!"; 24 | 25 | private final CurrentReportRepository currentReportRepository; 26 | private final MonthlyReportRepository monthlyReportRepository; 27 | private final ReportService reportService; 28 | 29 | @Autowired 30 | public ReportsController(CurrentReportRepository currentReportRepository, 31 | MonthlyReportRepository monthlyReportRepository, 32 | ReportService reportService) { 33 | this.currentReportRepository = currentReportRepository; 34 | this.monthlyReportRepository = monthlyReportRepository; 35 | this.reportService = reportService; 36 | } 37 | 38 | @GetMapping("/reports") 39 | @ResponseStatus(HttpStatus.OK) 40 | public List getReports() { 41 | if (reportService.shouldSaveReport()) { 42 | reportService.saveReport(); 43 | } 44 | return monthlyReportRepository.findAll(); 45 | } 46 | 47 | @GetMapping("/reports/{id}") 48 | @ResponseStatus(HttpStatus.OK) 49 | public MonthlyReport getReport(@PathVariable("id") long id) { 50 | if (reportService.shouldSaveReport()) { 51 | reportService.saveReport(); 52 | } 53 | return monthlyReportRepository.findById(id) 54 | .orElseThrow(() -> new NotFoundException(REPORT_NOT_FOUND)); 55 | } 56 | 57 | @GetMapping("/current-report") 58 | @ResponseStatus(HttpStatus.OK) 59 | public CurrentReport getCurrentReport() { 60 | if (reportService.shouldSaveReport()) { 61 | reportService.saveReport(); 62 | } 63 | return currentReportRepository.findById((long) 1) 64 | .orElseThrow(() -> new NotFoundException(REPORT_NOT_FOUND)); 65 | } 66 | 67 | @PutMapping("/current-report") 68 | @ResponseStatus(HttpStatus.OK) 69 | public CurrentReport recalculateCosts(@RequestBody EstimatedCostsRequest reestimatedCosts) { 70 | if (reportService.shouldSaveReport()) { 71 | reportService.saveReport(); 72 | } 73 | return reportService.recalculateCosts(reestimatedCosts); 74 | } 75 | 76 | @PostMapping("/current-report/income") 77 | @ResponseStatus(HttpStatus.OK) 78 | public CurrentReport addIncome(@RequestBody double amount) { 79 | if (reportService.shouldSaveReport()) { 80 | reportService.saveReport(); 81 | } 82 | return reportService.addIncome(amount); 83 | } 84 | 85 | @PostMapping("/current-report/expense") 86 | @ResponseStatus(HttpStatus.OK) 87 | public CurrentReport addExpense(@RequestBody ExpenseRequest request) { 88 | if (reportService.shouldSaveReport()) { 89 | reportService.saveReport(); 90 | } 91 | return reportService.addExpense(request); 92 | } 93 | 94 | @GetMapping("current-report/recommended-recalculations") 95 | @ResponseStatus(HttpStatus.OK) 96 | public EstimatedCostsRequest countRecommendations() { 97 | return reportService.countRecommendations(); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/controller/TaskController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.dto.TaskDTO; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.TaskRequest; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.production.service.TaskService; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | import java.util.List; 10 | 11 | @RestController 12 | @CrossOrigin(origins = "*") 13 | public class TaskController { 14 | 15 | private final TaskService taskService; 16 | 17 | public TaskController(TaskService taskService) { 18 | this.taskService = taskService; 19 | } 20 | 21 | @GetMapping("/tasks") 22 | @ResponseStatus(HttpStatus.OK) 23 | public List getAllTasks() { 24 | return taskService.getAllTasks(); 25 | } 26 | 27 | @GetMapping("/tasks/{id}") 28 | @ResponseStatus(HttpStatus.OK) 29 | public TaskDTO getOneTask(@PathVariable("id") Long id) { 30 | return taskService.getOneTask(id); 31 | } 32 | 33 | @GetMapping("/kanban/{id}") 34 | @ResponseStatus(HttpStatus.OK) 35 | public List getTasksByAssignee(@PathVariable("id") Long id) { 36 | return taskService.getTasksByAssignee(id); 37 | } 38 | 39 | @PostMapping("/tasks") 40 | @ResponseStatus(HttpStatus.CREATED) 41 | public TaskDTO addOneTask(@RequestBody TaskRequest taskRequest) { 42 | return taskService.addOneTask(taskRequest); 43 | } 44 | 45 | @PutMapping("/tasks/{id}") 46 | @ResponseStatus(HttpStatus.OK) 47 | public TaskDTO setNextCategory(@PathVariable("id") Long id) { 48 | return taskService.setNextCategory(id); 49 | } 50 | 51 | @PutMapping("/tasks/{id}/assign") 52 | public HttpStatus assignToMe(@PathVariable("id") Long id) { 53 | taskService.assignToMe(id); 54 | return HttpStatus.OK; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/dto/TaskDTO.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.dto; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Category; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Task; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Type; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.dto.EmployeeDTO; 7 | import lombok.AllArgsConstructor; 8 | import lombok.Data; 9 | 10 | import java.time.LocalDateTime; 11 | import java.util.List; 12 | 13 | @Data 14 | @AllArgsConstructor 15 | public class TaskDTO { 16 | 17 | private long id; 18 | private String name; 19 | private Category category; 20 | private List precedingTaskIds; 21 | private EmployeeDTO author; 22 | private EmployeeDTO assignee; 23 | private LocalDateTime creationTime; 24 | private Integer estimatedTime; 25 | private LocalDateTime deadline; 26 | private LocalDateTime scheduledTime; 27 | private LocalDateTime startTime; 28 | private LocalDateTime endTime; 29 | private String details; 30 | private EmployeeDTO startEmployee; 31 | private EmployeeDTO endEmployee; 32 | private Type type; 33 | 34 | public TaskDTO(Task task) { 35 | this.id = task.getId(); 36 | this.name = task.getName(); 37 | this.category = task.getCategory(); 38 | this.precedingTaskIds = task.getPrecedingTaskIds(); 39 | this.author = new EmployeeDTO(task.getAuthor()); 40 | this.estimatedTime = task.getEstimatedTime(); 41 | this.creationTime = task.getCreationTime(); 42 | this.deadline = task.getDeadline(); 43 | this.type = task.getType(); 44 | 45 | if (task.getAssignee() != null) { 46 | this.assignee = new EmployeeDTO(task.getAssignee()); 47 | } 48 | 49 | if (task.getScheduledTime() != null) { 50 | this.scheduledTime = task.getScheduledTime(); 51 | } 52 | 53 | if (task.getStartTime() != null) { 54 | this.startTime = task.getStartTime(); 55 | } 56 | 57 | if (task.getEndTime() != null) { 58 | this.endTime = task.getEndTime(); 59 | } 60 | 61 | if (task.getDetails() != null) { 62 | this.details = task.getDetails(); 63 | } 64 | 65 | if (task.getStartTime() != null) { 66 | this.startTime = task.getStartTime(); 67 | this.startEmployee = new EmployeeDTO(task.getStartEmployee()); 68 | } 69 | 70 | if (task.getEndTime() != null) { 71 | this.endTime = task.getEndTime(); 72 | this.endEmployee = new EmployeeDTO(task.getEndEmployee()); 73 | } 74 | } 75 | 76 | public TaskDTO(String name, List precedingTaskIds, EmployeeDTO author, EmployeeDTO assignee, 77 | Integer estimatedTime) { 78 | this.name = name; 79 | this.precedingTaskIds = precedingTaskIds; 80 | this.author = author; 81 | this.assignee = assignee; 82 | this.estimatedTime = estimatedTime; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/factory/TaskFactory.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.factory; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Type; 4 | 5 | import java.time.LocalDateTime; 6 | import java.util.Random; 7 | 8 | public class TaskFactory { 9 | 10 | private final String[] NAMES = {"Wysłać przesyłkę #1425", "Wysłać list #1434", 11 | "Przekazać paczkę #1478", "Zapakować list #1447", "Skompletować paczkę #1442"}; 12 | 13 | private final String[] DETAILS = {"Dodać darmowy upominek", "Zmienić sposób dostarczenia na list ekonomiczny", 14 | "Zmienić sposób dostarczenia na list priorytetowy", "Nakleić informację: \"Uwaga! Szkło\""}; 15 | 16 | private final Random random; 17 | 18 | public TaskFactory() { 19 | random = new Random(); 20 | } 21 | 22 | private String generate(String[] array) { 23 | return array[random.nextInt(array.length)]; 24 | } 25 | 26 | public String generateName() { 27 | return generate(NAMES); 28 | } 29 | 30 | public String generateDetails() { 31 | return generate(DETAILS); 32 | } 33 | 34 | public int generateEstimatedTime() { 35 | return random.nextInt(15) + 5; 36 | } 37 | 38 | public LocalDateTime generateDeadline() { 39 | return LocalDateTime.now().plusDays(2); 40 | } 41 | 42 | public Type generateType() { 43 | return Type.values()[random.nextInt(Type.values().length)]; 44 | } 45 | 46 | public LocalDateTime generateScheduledTime() { 47 | return LocalDateTime.now().plusDays(1); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/Category.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | public enum Category { 4 | TO_DO, DOING, DONE 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/CurrentReport.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.EstimatedCosts; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Expense; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | 9 | import javax.persistence.*; 10 | import java.time.LocalDate; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | @Entity 15 | @Getter 16 | @NoArgsConstructor 17 | public class CurrentReport { 18 | 19 | @Id 20 | @GeneratedValue(strategy = GenerationType.IDENTITY) 21 | private long id; 22 | 23 | @OneToMany 24 | private List expenses; 25 | 26 | @ElementCollection 27 | private List income; 28 | 29 | @OneToOne 30 | private EstimatedCosts estimatedCosts; 31 | 32 | @Setter 33 | private LocalDate startDate; 34 | 35 | public CurrentReport(EstimatedCosts estimatedCosts) { 36 | this.estimatedCosts = estimatedCosts; 37 | expenses = new ArrayList<>(); 38 | income = new ArrayList<>(); 39 | startDate = LocalDate.now(); 40 | } 41 | 42 | public void clearReport() { 43 | income = new ArrayList<>(); 44 | expenses = new ArrayList<>(); 45 | startDate = LocalDate.now(); 46 | } 47 | 48 | public void updateEstimatedCosts(EstimatedCosts reestimatedCosts) { 49 | this.estimatedCosts = reestimatedCosts; 50 | } 51 | 52 | public void addExpense(Expense expense) { 53 | expenses.add(expense); 54 | } 55 | 56 | public void addIncome(double amount) { 57 | income.add(amount); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/DailyPlan.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | 11 | @Entity 12 | @Getter 13 | @Setter 14 | public class DailyPlan { 15 | 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | 20 | private int employeesPerDay; 21 | private int ordersPerDay; 22 | private int returnsPerDay; 23 | private int complaintsResolvedPerDay; 24 | 25 | public DailyPlan() { 26 | this.employeesPerDay = 5; 27 | this.ordersPerDay = 15; 28 | this.returnsPerDay = 5; 29 | this.complaintsResolvedPerDay = 5; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/EstimatedCosts.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.EstimatedCostsRequest; 4 | import lombok.Getter; 5 | 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | 11 | @Entity 12 | @Getter 13 | public class EstimatedCosts { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private long id; 18 | 19 | private double estimatedIncome; 20 | private double estimatedShippingCosts; 21 | private double estimatedBills; 22 | private double rent; 23 | private double salaries; 24 | private double stockCosts; 25 | private double socialFund; 26 | private double unexpected; 27 | private double taxes; 28 | 29 | public EstimatedCosts() { 30 | estimatedIncome = 175000.00; 31 | estimatedShippingCosts = 5000.00; 32 | estimatedBills = 3000.00; 33 | rent = 10000.00; 34 | salaries = 100000.00; 35 | stockCosts = 30000.00; 36 | socialFund = 2000.00; 37 | unexpected = 5000.00; 38 | taxes = 0.18 * (estimatedIncome + salaries); 39 | } 40 | 41 | public void recalculateCosts(EstimatedCostsRequest reestimatedCosts) { 42 | this.estimatedIncome = reestimatedCosts.getEstimatedIncome(); 43 | this.estimatedShippingCosts = reestimatedCosts.getEstimatedShippingCosts(); 44 | this.estimatedBills = reestimatedCosts.getEstimatedBills(); 45 | this.rent = reestimatedCosts.getRent(); 46 | this.salaries = reestimatedCosts.getSalaries(); 47 | this.stockCosts = reestimatedCosts.getStockCosts(); 48 | this.socialFund = reestimatedCosts.getSocialFund(); 49 | this.unexpected = reestimatedCosts.getUnexpected(); 50 | taxes = 0.18 * (estimatedIncome + salaries); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/Expense.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | 8 | @Entity 9 | @Getter 10 | @NoArgsConstructor 11 | public class Expense { 12 | 13 | @Id 14 | @GeneratedValue(strategy = GenerationType.IDENTITY) 15 | private long id; 16 | 17 | @Enumerated(EnumType.STRING) 18 | private ExpenseType expenseType; 19 | 20 | private double amount; 21 | 22 | public Expense(ExpenseType expenseType, double amount) { 23 | this.expenseType = expenseType; 24 | this.amount = amount; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/ExpenseType.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | public enum ExpenseType { 4 | SHIPPING, BILLS, RENT, SALARIES, STOCK, SOCIAL_FUND, UNEXPECTED, TAXES 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/Indicators.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | @Data 8 | @NoArgsConstructor 9 | @AllArgsConstructor 10 | public class Indicators { 11 | 12 | private long numberTasksEmployee; 13 | private long numberTasksEverybody; 14 | 15 | private long numberTasksEmployeeToDo; 16 | private long numberTasksEverybodyToDo; 17 | private long numberTasksEmployeeDoing; 18 | private long numberTasksEverybodyDoing; 19 | private long numberTasksEmployeeDone; 20 | private long numberTasksEverybodyDone; 21 | 22 | private Long numberTasksEmployeeDoneBeforeDeadline; 23 | private Long numberTasksEverybodyDoneBeforeDeadline; 24 | 25 | private long numberSuggestionsEmployee; 26 | private long numberSuggestionsEverybody; 27 | 28 | private long numberSuggestionsEmployeeReported; 29 | private long numberSuggestionsEverybodyReported; 30 | private long numberSuggestionsEmployeeInImplementation; 31 | private long numberSuggestionsEverybodyInImplementation; 32 | private long numberSuggestionsEmployeeImplemented; 33 | private long numberSuggestionsEverybodyImplemented; 34 | 35 | private Long averageTimeTasksEmployeeBetweenDeadlineAndEndTime; 36 | private Long averageTimeTasksEverybodyBetweenDeadlineAndEndTime; 37 | 38 | private Long averageTimeNotificationsEmployeeBetweenStartTimeAndCreationTime; 39 | private Long averageTimeNotificationsEverybodyBetweenStartTimeAndCreationTime; 40 | 41 | private Long averageTimeNotificationsEmployeeBetweenEndTimeAndStartTime; 42 | private Long averageTimeNotificationsEverybodyBetweenEndTimeAndStartTime; 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/MonthlyReport.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | import java.time.LocalDate; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | @Entity 12 | @Getter 13 | @NoArgsConstructor 14 | public class MonthlyReport { 15 | 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | 20 | @ManyToMany 21 | private List expenses; 22 | 23 | @ElementCollection 24 | private List income; 25 | 26 | private LocalDate startDate; 27 | 28 | private double overallExpenses; 29 | private double overallIncome; 30 | private double balance; 31 | 32 | @OneToOne 33 | private EstimatedCosts estimatedCosts; 34 | 35 | public MonthlyReport(CurrentReport currentReport) { 36 | estimatedCosts = currentReport.getEstimatedCosts(); 37 | expenses = new ArrayList<>(); 38 | income = new ArrayList<>(); 39 | startDate = currentReport.getStartDate(); 40 | updateIncome(); 41 | updateExpenses(); 42 | balance = overallIncome - overallExpenses; 43 | } 44 | 45 | public void setExpenses(List expenses) { 46 | this.expenses = expenses; 47 | updateExpenses(); 48 | } 49 | 50 | public void setIncome(List income) { 51 | this.income = income; 52 | updateIncome(); 53 | } 54 | 55 | private void updateIncome() { 56 | overallIncome = income.stream() 57 | .mapToDouble(Double::doubleValue) 58 | .sum(); 59 | balance = overallIncome - overallExpenses; 60 | } 61 | 62 | private void updateExpenses() { 63 | overallExpenses = expenses.stream() 64 | .map(Expense::getAmount) 65 | .mapToDouble(Double::doubleValue) 66 | .sum(); 67 | balance = overallIncome - overallExpenses; 68 | } 69 | 70 | public void payTaxes(Expense taxes) { 71 | expenses.add(taxes); 72 | updateExpenses(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/SpecialPlan.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | import java.time.LocalDate; 8 | 9 | @Entity 10 | @Getter 11 | @NoArgsConstructor 12 | public class SpecialPlan { 13 | 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private long id; 17 | 18 | private String description; 19 | private LocalDate day; 20 | private int employeesPerDay; 21 | private int ordersPerDay; 22 | private int returnsPerDay; 23 | private int complaintsResolvedPerDay; 24 | 25 | public SpecialPlan(String description, LocalDate day, int employeesPerDay, int ordersPerDay, 26 | int returnsPerDay, int complaintsResolvedPerDay) { 27 | this.description = description; 28 | this.day = day; 29 | this.employeesPerDay = employeesPerDay; 30 | this.ordersPerDay = ordersPerDay; 31 | this.returnsPerDay = returnsPerDay; 32 | this.complaintsResolvedPerDay = complaintsResolvedPerDay; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/Task.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | 8 | import javax.persistence.*; 9 | import javax.validation.constraints.Size; 10 | import java.time.LocalDateTime; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | @Entity 15 | @Getter 16 | @Setter 17 | @NoArgsConstructor 18 | public class Task { 19 | 20 | @Id 21 | @GeneratedValue(strategy = GenerationType.IDENTITY) 22 | private Long id; 23 | 24 | @Column(nullable = false) 25 | @Size(max = 25) 26 | private String name; 27 | 28 | @Column(nullable = false) 29 | @Enumerated(EnumType.STRING) 30 | private Category category = Category.TO_DO; 31 | 32 | @ElementCollection 33 | private List precedingTaskIds = new ArrayList<>(); 34 | 35 | @OneToOne 36 | private Employee author; 37 | 38 | @OneToOne 39 | private Employee assignee; 40 | 41 | @Column(nullable = false) 42 | private LocalDateTime creationTime; 43 | 44 | @Column(nullable = false) 45 | private Integer estimatedTime; 46 | 47 | @Column(nullable = false) 48 | private LocalDateTime deadline; 49 | 50 | private LocalDateTime scheduledTime; 51 | private LocalDateTime startTime; 52 | private LocalDateTime endTime; 53 | 54 | @Size(max = 250) 55 | private String details; 56 | 57 | @OneToOne 58 | private Employee startEmployee; 59 | 60 | @OneToOne 61 | private Employee endEmployee; 62 | 63 | @Column(nullable = false) 64 | @Enumerated(EnumType.STRING) 65 | private Type type; 66 | 67 | public Task(String name, List precedingTaskIds, Employee author, Employee assignee, 68 | LocalDateTime scheduledTime, Integer estimatedTime, LocalDateTime deadline, String details, Type type) { 69 | this.name = name; 70 | this.precedingTaskIds = precedingTaskIds; 71 | this.author = author; 72 | this.assignee = assignee; 73 | this.creationTime = LocalDateTime.now(); 74 | this.scheduledTime = scheduledTime; 75 | this.estimatedTime = estimatedTime; 76 | this.deadline = deadline; 77 | this.details = details; 78 | this.type = type; 79 | } 80 | 81 | public static int compare(Task t1, Task t2) { 82 | Integer sizePrecedingTasksFirst = t1.getPrecedingTaskIds().size(); 83 | Integer sizePrecedingTasksSecond = t2.getPrecedingTaskIds().size(); 84 | int comparison = sizePrecedingTasksFirst.compareTo(sizePrecedingTasksSecond); 85 | 86 | if (comparison == 0) { 87 | comparison = t1.getEstimatedTime().compareTo(t2.getEstimatedTime()); 88 | } 89 | 90 | return comparison; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/model/Type.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.model; 2 | 3 | public enum Type { 4 | DELIVERY, ORDER, COMPLAINT, RETURN, OTHER; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/repository/CurrentReportRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.CurrentReport; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface CurrentReportRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/repository/DailyPlanRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.DailyPlan; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface DailyPlanRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/repository/EstimatedCostsRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.EstimatedCosts; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface EstimatedCostsRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/repository/ExpenseRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Expense; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface ExpenseRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/repository/MonthlyReportRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.MonthlyReport; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface MonthlyReportRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/repository/SpecialPlanRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.SpecialPlan; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.time.LocalDate; 8 | import java.util.List; 9 | import java.util.Optional; 10 | 11 | @Repository 12 | public interface SpecialPlanRepository extends JpaRepository { 13 | 14 | Optional> findByDay(LocalDate day); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/repository/TaskRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Category; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Task; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.data.repository.query.Param; 8 | import org.springframework.stereotype.Repository; 9 | 10 | import java.time.LocalDateTime; 11 | import java.util.List; 12 | import java.util.Optional; 13 | 14 | @Repository 15 | public interface TaskRepository extends JpaRepository { 16 | 17 | long countTasksByAssigneeIdAndCreationTimeAfter(Long id, LocalDateTime timeRange); 18 | 19 | long countTasksByCreationTimeAfter(LocalDateTime timeRange); 20 | 21 | long countTasksByAssigneeIdAndCategoryAndCreationTimeAfter(Long id, Category category, LocalDateTime timeRange); 22 | 23 | long countTasksByCategoryAndCreationTimeAfter(Category category, LocalDateTime timeRange); 24 | 25 | @Query(value = "SELECT COUNT(t.id) FROM task t WHERE t.assignee_id = :assignee_id AND t.category = 'DONE' AND" + 26 | " t.end_time <= t.deadline", nativeQuery = true) 27 | Long countDoneTasksByAssigneeIdAndEndTimeIsLessThanDeadline(@Param("assignee_id") Long assignee_id); 28 | 29 | @Query(value = "SELECT COUNT(t.id) FROM task t WHERE t.category = 'DONE' AND t.end_time <= t.deadline", 30 | nativeQuery = true) 31 | Long countDoneTasksByAssigneeIdAndEndTimeIsLessThanDeadline(); 32 | 33 | @Query(value = "SELECT EXTRACT(EPOCH FROM (SELECT avg(t.deadline - t.end_time) FROM task t WHERE" + 34 | " t.category = 'DONE' AND t.assignee_id = :assignee_id))", nativeQuery = true) 35 | Long countAverageDifferenceBetweenDeadlineAndEndTime(@Param("assignee_id") Long assignee_id); 36 | 37 | @Query(value = "SELECT EXTRACT(EPOCH FROM (SELECT avg(t.deadline - t.end_time) FROM task t WHERE" + 38 | " t.category = 'DONE'))", nativeQuery = true) 39 | Long countAverageDifferenceBetweenDeadlineAndEndTime(); 40 | 41 | Optional> findTasksByAssigneeIdAndCreationTimeAfterOrderByDeadlineAsc(Long id,LocalDateTime timeRange); 42 | 43 | Optional> findTaskByAssigneeIsNull(); 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/request/AssignmentRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | import lombok.NonNull; 7 | 8 | import java.time.LocalDateTime; 9 | import java.util.List; 10 | 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | public class AssignmentRequest { 15 | 16 | @NonNull 17 | private List taskIds; 18 | 19 | @NonNull 20 | private List assigneeIds; 21 | 22 | @NonNull 23 | private LocalDateTime startTime; 24 | 25 | @NonNull 26 | private LocalDateTime endTime; 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/request/DailyPlanRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import javax.validation.constraints.NotNull; 8 | 9 | @Data 10 | @AllArgsConstructor 11 | @NoArgsConstructor 12 | public class DailyPlanRequest { 13 | 14 | @NotNull 15 | private int employeesPerDay; 16 | 17 | @NotNull 18 | private int ordersPerDay; 19 | 20 | @NotNull 21 | private int returnsPerDay; 22 | 23 | @NotNull 24 | private int complaintsResolvedPerDay; 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/request/EstimatedCostsRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import javax.validation.constraints.NotNull; 8 | 9 | @Data 10 | @NoArgsConstructor 11 | @AllArgsConstructor 12 | public class EstimatedCostsRequest { 13 | 14 | @NotNull 15 | private double estimatedIncome; 16 | 17 | @NotNull 18 | private double estimatedShippingCosts; 19 | 20 | @NotNull 21 | private double estimatedBills; 22 | 23 | @NotNull 24 | private double rent; 25 | 26 | @NotNull 27 | private double salaries; 28 | 29 | @NotNull 30 | private double stockCosts; 31 | 32 | @NotNull 33 | private double socialFund; 34 | 35 | @NotNull 36 | private double unexpected; 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/request/ExpenseRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.request; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Expense; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.ExpenseType; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | import javax.validation.constraints.NotNull; 10 | 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | public class ExpenseRequest { 15 | 16 | @NotNull 17 | private ExpenseType expenseType; 18 | 19 | @NotNull 20 | private double amount; 21 | 22 | public Expense extractExpense() { 23 | return new Expense(expenseType, amount); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/request/SpecialPlanRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.request; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.SpecialPlan; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.validation.constraints.NotNull; 9 | import java.time.LocalDate; 10 | 11 | @Data 12 | @AllArgsConstructor 13 | @NoArgsConstructor 14 | public class SpecialPlanRequest { 15 | 16 | @NotNull 17 | private String description; 18 | 19 | @NotNull 20 | private LocalDate day; 21 | 22 | @NotNull 23 | private int employeesPerDay; 24 | 25 | @NotNull 26 | private int ordersPerDay; 27 | 28 | @NotNull 29 | private int returnsPerDay; 30 | 31 | @NotNull 32 | private int complaintsResolvedPerDay; 33 | 34 | public SpecialPlan extractSpecialPlan() { 35 | return new SpecialPlan(description, day, employeesPerDay, ordersPerDay, returnsPerDay, 36 | complaintsResolvedPerDay); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/production/request/TaskRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.production.request; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Category; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Type; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | import lombok.NonNull; 9 | 10 | import java.time.LocalDateTime; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | @Data 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | public class TaskRequest { 18 | 19 | @NonNull 20 | private String name; 21 | 22 | private List precedingTaskIds; 23 | 24 | private Long assigneeId; 25 | 26 | @NonNull 27 | private Integer estimatedTime; 28 | 29 | @NonNull 30 | private LocalDateTime deadline; 31 | 32 | private LocalDateTime scheduledTime; 33 | private String details; 34 | 35 | @NonNull 36 | private Type type; 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/security/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.security; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.repository.EmployeeRepository; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.security.authentication.AuthenticationManager; 8 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 9 | import org.springframework.security.core.Authentication; 10 | import org.springframework.security.core.AuthenticationException; 11 | import org.springframework.security.core.context.SecurityContextHolder; 12 | import org.springframework.web.bind.annotation.CrossOrigin; 13 | import org.springframework.web.bind.annotation.PostMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | @RestController 18 | @CrossOrigin(origins = "*") 19 | public class AuthController { 20 | 21 | private final AuthenticationManager authenticationManager; 22 | private final JwtTokenUtil jwtTokenUtil; 23 | private final EmployeeRepository employeeRepository; 24 | 25 | @Autowired 26 | public AuthController(AuthenticationManager authenticationManager, JwtTokenUtil jwtTokenUtil, 27 | EmployeeRepository employeeRepository) { 28 | this.authenticationManager = authenticationManager; 29 | this.jwtTokenUtil = jwtTokenUtil; 30 | this.employeeRepository = employeeRepository; 31 | } 32 | 33 | @PostMapping("/generate-token") 34 | public JwtToken login(@RequestBody Credentials credentials) throws AuthenticationException { 35 | 36 | Authentication authentication = authenticationManager.authenticate( 37 | new UsernamePasswordAuthenticationToken( 38 | credentials.getEmail(), 39 | credentials.getPassword() 40 | ) 41 | ); 42 | SecurityContextHolder.getContext().setAuthentication(authentication); 43 | checkIfEmployeeExists(credentials.getEmail()); 44 | Employee employee = employeeRepository.findByEmail(credentials.getEmail()).get(); 45 | String token = jwtTokenUtil.generateToken(employee); 46 | return new JwtToken(token); 47 | } 48 | 49 | private void checkIfEmployeeExists(String email) { 50 | if (!employeeRepository.findByEmail(email).isPresent()) { 51 | throw new NotFoundException("Such employees doesn't exist!"); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/security/Credentials.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.security; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | @Data 8 | @AllArgsConstructor 9 | @NoArgsConstructor 10 | public class Credentials { 11 | 12 | private String email; 13 | private String password; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/security/JwtAuthEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.security; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | import org.springframework.security.web.AuthenticationEntryPoint; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | import java.io.IOException; 10 | import java.io.Serializable; 11 | 12 | @Component 13 | public class JwtAuthEntryPoint implements AuthenticationEntryPoint, Serializable { 14 | 15 | @Override 16 | public void commence(HttpServletRequest request, 17 | HttpServletResponse response, 18 | AuthenticationException authException) throws IOException { 19 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/security/JwtAuthFilter.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 5 | import org.springframework.security.core.context.SecurityContextHolder; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.security.core.userdetails.UserDetailsService; 8 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 9 | import org.springframework.web.filter.OncePerRequestFilter; 10 | 11 | import javax.annotation.Resource; 12 | import javax.servlet.FilterChain; 13 | import javax.servlet.ServletException; 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | import java.io.IOException; 17 | 18 | public class JwtAuthFilter extends OncePerRequestFilter { 19 | 20 | @Resource(name = "userService") 21 | private UserDetailsService userDetailsService; 22 | 23 | @Autowired 24 | private JwtTokenUtil jwtTokenUtil; 25 | 26 | @Override 27 | protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { 28 | String header = req.getHeader("Authorization"); 29 | String username = null; 30 | String authToken = null; 31 | if (header != null && header.startsWith("Bearer ")) { 32 | authToken = header.replace("Bearer ", ""); 33 | try { 34 | username = jwtTokenUtil.getUsernameFromToken(authToken); 35 | } catch (Exception e) { 36 | e.printStackTrace(); 37 | } 38 | } 39 | if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { 40 | UserDetails userDetails = userDetailsService.loadUserByUsername(username); 41 | if (jwtTokenUtil.validateToken(authToken, userDetails)) { 42 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, 43 | null, userDetails.getAuthorities()); 44 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req)); 45 | SecurityContextHolder.getContext().setAuthentication(authentication); 46 | } 47 | } 48 | chain.doFilter(req, res); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/security/JwtToken.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.security; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | @Data 7 | @AllArgsConstructor 8 | public class JwtToken { 9 | 10 | private String token; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/security/JwtTokenUtil.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.security; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Role; 5 | import io.jsonwebtoken.Claims; 6 | import io.jsonwebtoken.Jwts; 7 | import io.jsonwebtoken.SignatureAlgorithm; 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.stereotype.Component; 11 | 12 | import java.io.Serializable; 13 | import java.util.Arrays; 14 | import java.util.Date; 15 | import java.util.function.Function; 16 | 17 | @Component 18 | public class JwtTokenUtil implements Serializable { 19 | 20 | public String getUsernameFromToken(String token) { 21 | return getClaimFromToken(token, Claims::getSubject); 22 | } 23 | 24 | public Date getExpirationDateFromToken(String token) { 25 | return getClaimFromToken(token, Claims::getExpiration); 26 | } 27 | 28 | public T getClaimFromToken(String token, Function claimsResolver) { 29 | final Claims claims = getAllClaimsFromToken(token); 30 | return claimsResolver.apply(claims); 31 | } 32 | 33 | private Claims getAllClaimsFromToken(String token) { 34 | return Jwts.parser() 35 | .setSigningKey("erpmes0123") 36 | .parseClaimsJws(token) 37 | .getBody(); 38 | } 39 | 40 | private Boolean isTokenExpired(String token) { 41 | final Date expiration = getExpirationDateFromToken(token); 42 | return expiration.before(new Date()); 43 | } 44 | 45 | public String generateToken(Employee employee) { 46 | return doGenerateToken(employee.getEmail(), employee.getRole()); 47 | } 48 | 49 | private String doGenerateToken(String subject, Role role) { 50 | 51 | Claims claims = Jwts.claims().setSubject(subject); 52 | claims.put("scopes", Arrays.asList(new SimpleGrantedAuthority(role.name()))); 53 | 54 | return Jwts.builder() 55 | .setClaims(claims) 56 | .setIssuer("com.erpmes0123.example") 57 | .setIssuedAt(new Date(System.currentTimeMillis())) 58 | .setExpiration(new Date(System.currentTimeMillis() + 5 * 60 * 60 * 1000)) 59 | .signWith(SignatureAlgorithm.HS256, "erpmes0123") 60 | .compact(); 61 | } 62 | 63 | public Boolean validateToken(String token, UserDetails userDetails) { 64 | final String username = getUsernameFromToken(token); 65 | return ( 66 | username.equals(userDetails.getUsername()) 67 | && !isTokenExpired(token)); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/security/UserService.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.security; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.repository.EmployeeRepository; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 8 | import org.springframework.security.core.userdetails.User; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.security.core.userdetails.UserDetailsService; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.util.Arrays; 14 | import java.util.List; 15 | 16 | @Service("userService") 17 | public class UserService implements UserDetailsService { 18 | 19 | private final EmployeeRepository employeeRepository; 20 | 21 | @Autowired 22 | public UserService(EmployeeRepository employeeRepository) { 23 | this.employeeRepository = employeeRepository; 24 | } 25 | 26 | public UserDetails loadUserByUsername(String username) throws NotFoundException { 27 | if(!employeeRepository.findByEmail(username).isPresent()){ 28 | throw new NotFoundException("Invalid username or password."); 29 | } 30 | Employee employee = employeeRepository.findByEmail(username).get(); 31 | return new User(employee.getEmail(), employee.getPassword(), getAuthority(employee)); 32 | } 33 | 34 | private List getAuthority(Employee employee) { 35 | return Arrays.asList(new SimpleGrantedAuthority(employee.getRole().name())); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/controller/ComplaintController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.service.EmailService; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Complaint; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.repository.ComplaintRepository; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.ComplaintStatus; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Resolution; 8 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.service.ShopService; 9 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.ShopServiceRequest; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | import java.util.List; 15 | 16 | @RestController 17 | @CrossOrigin("*") 18 | public class ComplaintController { 19 | 20 | private final ComplaintRepository complaintRepository; 21 | private final ShopService shopService; 22 | private final EmailService emailService; 23 | 24 | @Autowired 25 | public ComplaintController(ComplaintRepository complaintRepository, ShopService shopService, 26 | EmailService emailService) { 27 | this.complaintRepository = complaintRepository; 28 | this.shopService = shopService; 29 | this.emailService = emailService; 30 | } 31 | 32 | @GetMapping("/complaints") 33 | @ResponseStatus(HttpStatus.OK) 34 | public List getAllOrders() { 35 | return complaintRepository.findAll(); 36 | } 37 | 38 | @PostMapping("/complaints") 39 | @ResponseStatus(HttpStatus.CREATED) 40 | public Complaint addOneComplaint(@RequestBody ShopServiceRequest request) { 41 | Complaint complaint = shopService.addNewComplaint(request); 42 | emailService.sensNewComplaintRegisteredMessage(complaint.getId()); 43 | return complaint; 44 | } 45 | 46 | @GetMapping("/complaints/{id}") 47 | @ResponseStatus(HttpStatus.OK) 48 | public Complaint getOneComplaint(@PathVariable("id") Long id) { 49 | shopService.checkIfComplaintExists(id); 50 | return complaintRepository.findById(id).get(); 51 | } 52 | 53 | @PutMapping("/complaints/{id}") 54 | @ResponseStatus(HttpStatus.OK) 55 | public Complaint updateStatusComplaint(@PathVariable("id") Long id, @RequestBody String status) { 56 | shopService.checkIfComplaintExists(id); 57 | emailService.sendComplaintStatusChangeMessage(id, status); 58 | return shopService.updateComplaintStatus(id, ComplaintStatus.valueOf(status)); 59 | } 60 | 61 | @PutMapping("/complaints/{id}/resolution") 62 | @ResponseStatus(HttpStatus.OK) 63 | public Complaint updateComplaintResolution(@PathVariable("id") Long id, @RequestBody String resolution) { 64 | shopService.checkIfComplaintExists(id); 65 | emailService.sendComplaintResolutionChangeMessage(id, resolution); 66 | return shopService.updateComplaintResolution(id, Resolution.valueOf(resolution)); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/controller/DeliveryController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Delivery; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.repository.DeliveryRepository; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.DeliveryItemRequest; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.DeliveryRequest; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.service.DeliveryService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.web.bind.annotation.*; 11 | 12 | import java.util.List; 13 | 14 | @RestController 15 | @CrossOrigin(origins = "*") 16 | public class DeliveryController { 17 | 18 | private final DeliveryRepository deliveryRepository; 19 | private final DeliveryService deliveryService; 20 | 21 | @Autowired 22 | public DeliveryController(DeliveryRepository deliveryRepository, DeliveryService deliveryService) { 23 | this.deliveryRepository = deliveryRepository; 24 | this.deliveryService = deliveryService; 25 | } 26 | 27 | @GetMapping("/deliveries") 28 | @ResponseStatus(HttpStatus.OK) 29 | public List getAllDeliveries() { 30 | return deliveryRepository.findAll(); 31 | } 32 | 33 | @PostMapping("/deliveries") 34 | @ResponseStatus(HttpStatus.CREATED) 35 | public Delivery addNewDelivery(@RequestBody DeliveryRequest request) { 36 | return deliveryService.addDelivery(request); 37 | } 38 | 39 | @GetMapping("/deliveries/{id}") 40 | @ResponseStatus(HttpStatus.OK) 41 | public Delivery getOneDelivery(@PathVariable("id") long id) { 42 | deliveryService.checkIfDeliveryExists(id); 43 | return deliveryRepository.findById(id).get(); 44 | } 45 | 46 | @PostMapping("/deliveries/{id}") 47 | @ResponseStatus(HttpStatus.OK) 48 | public Delivery confirmDelivery(@PathVariable("id") long id) { 49 | deliveryService.checkIfDeliveryExists(id); 50 | Delivery delivery = deliveryRepository.findById(id).get(); 51 | delivery.confirm(); 52 | deliveryRepository.save(delivery); 53 | return delivery; 54 | } 55 | 56 | @GetMapping("/deliveries/recommended-delivery") 57 | public List recommendDelivery() { 58 | return deliveryService.getRecommendedDelivery(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/controller/ItemController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Item; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.repository.ItemRepository; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.ItemRequest; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.service.ItemService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.List; 12 | 13 | @RestController 14 | @CrossOrigin(origins = "*") 15 | public class ItemController { 16 | 17 | private final ItemRepository itemRepository; 18 | private final ItemService itemService; 19 | 20 | @Autowired 21 | public ItemController(ItemRepository itemRepository, ItemService itemService) { 22 | this.itemRepository = itemRepository; 23 | this.itemService = itemService; 24 | } 25 | 26 | @GetMapping("/items") 27 | @ResponseStatus(HttpStatus.OK) 28 | public List getAllItems() { 29 | return itemRepository.findAll(); 30 | } 31 | 32 | @PostMapping("/items") 33 | @ResponseStatus(HttpStatus.CREATED) 34 | public Item addNewItem(@RequestBody ItemRequest request) { 35 | Item item = request.extractItem(); 36 | itemRepository.save(item); 37 | return item; 38 | } 39 | 40 | @GetMapping("/items/{id}") 41 | @ResponseStatus(HttpStatus.OK) 42 | public Item getOneItem(@PathVariable("id") long id) { 43 | itemService.checkIfItemExists(id); 44 | return itemRepository.findById(id).get(); 45 | } 46 | 47 | @PostMapping("/items/{id}") 48 | @ResponseStatus(HttpStatus.OK) 49 | public Item changeCurrentPrice(@PathVariable("id") long id, @RequestBody double price) { 50 | itemService.checkIfItemExists(id); 51 | Item item = itemRepository.findById(id).get(); 52 | item.setCurrentPrice(price); 53 | itemRepository.save(item); 54 | return item; 55 | } 56 | 57 | @PostMapping("/items/{id}/supply") 58 | @ResponseStatus(HttpStatus.OK) 59 | public Item supplyItem(@PathVariable("id") long id, @RequestBody int q) { 60 | itemService.checkIfItemExists(id); 61 | return itemService.supplyItem(id, q); 62 | } 63 | 64 | @PostMapping("/items/{id}/buy") 65 | @ResponseStatus(HttpStatus.OK) 66 | public Item buyItem(@PathVariable("id") long id, @RequestBody int q) { 67 | itemService.checkIfItemExists(id); 68 | return itemService.buyItem(id, q); 69 | } 70 | 71 | @PostMapping("/set-special-offer") 72 | @ResponseStatus(HttpStatus.OK) 73 | public List setSpecialOffer(@RequestParam(value = "percentOff") Double percentOff, 74 | @RequestParam(required = false, value = "query") String query) { 75 | return itemService.updateItems(1 - percentOff / 100, query); 76 | } 77 | 78 | @PostMapping("/cancel-special-offer") 79 | @ResponseStatus(HttpStatus.OK) 80 | public List cancelSpecialOffer() { 81 | return itemService.updateItems(1, ""); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.service.EmailService; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Order; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Status; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.repository.OrderRepository; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.ShopServiceRequest; 8 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.service.ShopService; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import java.util.List; 14 | 15 | @RestController 16 | @CrossOrigin(origins = "*") 17 | public class OrderController { 18 | 19 | private final OrderRepository orderRepository; 20 | private final ShopService shopService; 21 | private final EmailService emailService; 22 | 23 | @Autowired 24 | public OrderController(OrderRepository orderRepository, ShopService shopService, EmailService emailService) { 25 | this.orderRepository = orderRepository; 26 | this.shopService = shopService; 27 | this.emailService = emailService; 28 | } 29 | 30 | @GetMapping("/orders") 31 | @ResponseStatus(HttpStatus.OK) 32 | public List getAllOrders() { 33 | return orderRepository.findAll(); 34 | } 35 | 36 | @PostMapping("/orders") 37 | @ResponseStatus(HttpStatus.CREATED) 38 | public Order addOneOrder(@RequestBody ShopServiceRequest orderRequest) { 39 | Order order = shopService.addNewOrder(orderRequest); 40 | emailService.sensNewOrderRegisteredMessage(order.getId()); 41 | return order; 42 | } 43 | 44 | @GetMapping("/orders/{id}") 45 | @ResponseStatus(HttpStatus.OK) 46 | public Order getOneOrder(@PathVariable("id") Long id) { 47 | shopService.checkIfOrderExists(id); 48 | return orderRepository.findById(id).get(); 49 | } 50 | 51 | @PutMapping("/orders/{id}") 52 | @ResponseStatus(HttpStatus.OK) 53 | public Order updateStatusOrder(@PathVariable("id") Long id, @RequestBody String status) { 54 | shopService.checkIfOrderExists(id); 55 | emailService.sendOrderStatusChangeMessage(id, status); 56 | return shopService.updateOrderStatus(id, Status.valueOf(status)); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/controller/ReturnController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.service.EmailService; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.service.ShopService; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.ShopServiceRequest; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Return; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.repository.ReturnRepository; 8 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.ReturnStatus; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import java.util.List; 14 | 15 | @RestController 16 | @CrossOrigin("*") 17 | public class ReturnController { 18 | 19 | private final ReturnRepository returnRepository; 20 | private final ShopService shopService; 21 | private final EmailService emailService; 22 | 23 | @Autowired 24 | public ReturnController(ReturnRepository returnRepository, ShopService shopService, 25 | EmailService emailService) { 26 | this.returnRepository = returnRepository; 27 | this.shopService = shopService; 28 | this.emailService = emailService; 29 | } 30 | 31 | @GetMapping("/returns") 32 | @ResponseStatus(HttpStatus.OK) 33 | public List getAllOrders() { 34 | return returnRepository.findAll(); 35 | } 36 | 37 | @PostMapping("/returns") 38 | @ResponseStatus(HttpStatus.CREATED) 39 | public Return addOnReturn(@RequestBody ShopServiceRequest request) { 40 | Return r = shopService.addNewReturn(request); 41 | emailService.sendNewReturnRegisteredMessage(r.getId()); 42 | return r; 43 | } 44 | 45 | @GetMapping("/returns/{id}") 46 | @ResponseStatus(HttpStatus.OK) 47 | public Return getOneReturn(@PathVariable("id") Long id) { 48 | shopService.checkIfReturnExists(id); 49 | return returnRepository.findById(id).get(); 50 | } 51 | 52 | @PutMapping("/returns/{id}") 53 | @ResponseStatus(HttpStatus.OK) 54 | public Return updateStatusReturn(@PathVariable("id") Long id, @RequestBody String status) { 55 | shopService.checkIfReturnExists(id); 56 | emailService.sendReturnStatusChangeMessage(id, status); 57 | return shopService.updateReturnStatus(id, ReturnStatus.valueOf(status)); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/factory/ShopServiceFactory.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.factory; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Resolution; 4 | 5 | import java.util.Random; 6 | 7 | public class ShopServiceFactory { 8 | 9 | private final String[] FIRST_NAMES = {"Piotr", "Jan", "Beniamin", "Anna", "Maria"}; 10 | 11 | private final String[] LAST_NAMES = {"Woźniak", "Krawczyk", "Zając", "Król", "Szewczyk"}; 12 | 13 | private final String[] EMAILS = {"firma@firma.pl", "przedsiebiorstwo@przedsiebiorstwo.pl", "business@business.pl", 14 | "uczelnia@uczelnia.pl", "hurtownia@hurtownia.pl"}; 15 | 16 | private final String[] PHONE_NUMBERS = {"625875322", "158643422", "567154333", "312312800", "321212890"}; 17 | 18 | private final String[] STREETS = {"ul. Witolda Pileckiego", "ul. Krakowska", "ul. Zbigniewa Herberta", 19 | "ul. 11 Listopada", "ul. Tadeusza Gajcego"}; 20 | 21 | private final String[] HOUSE_NUMBERS = {"11/16", "36", "239b", "8e", "16b"}; 22 | 23 | private final String[] CITIES = {"Nisko", "Zakopane", "Tarnobrzeg", "Warszawa", "Tuchola"}; 24 | 25 | private final String[] POSTAL_CODES = {"96-111", "44-144", "77-140", "11-997", "50-001"}; 26 | 27 | private final Random random; 28 | 29 | public ShopServiceFactory() { 30 | random = new Random(); 31 | } 32 | 33 | private String generate(String[] array) { 34 | return array[random.nextInt(array.length)]; 35 | } 36 | 37 | public String generateFirstName() { 38 | return generate(FIRST_NAMES); 39 | } 40 | 41 | public String generateLastName() { 42 | return generate(LAST_NAMES); 43 | } 44 | 45 | public String generateEmail() { 46 | return generate(EMAILS); 47 | } 48 | 49 | public String generatePhoneNumber() { 50 | return generate(PHONE_NUMBERS); 51 | } 52 | 53 | public String generateStreet() { 54 | return generate(STREETS); 55 | } 56 | 57 | public String generateHouseNumber() { 58 | return generate(HOUSE_NUMBERS); 59 | } 60 | 61 | public String generateCity() { 62 | return generate(CITIES); 63 | } 64 | 65 | public String generatePostalCode() { 66 | return generate(POSTAL_CODES); 67 | } 68 | 69 | public Resolution generateResolution() { 70 | return Resolution.values()[random.nextInt(Resolution.values().length)]; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/model/Complaint.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | import javax.validation.constraints.Email; 8 | import java.time.LocalDate; 9 | import java.util.List; 10 | 11 | @Entity 12 | @Getter 13 | @NoArgsConstructor 14 | public class Complaint { 15 | 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | 20 | @Enumerated(EnumType.STRING) 21 | private ComplaintStatus status; 22 | 23 | @Enumerated(EnumType.STRING) 24 | private Resolution requestedResolution; 25 | 26 | @Enumerated(EnumType.STRING) 27 | private Resolution resolution; 28 | 29 | private String firstName; 30 | private String lastName; 31 | 32 | @Email 33 | private String email; 34 | 35 | private String phoneNumber; 36 | private String street; 37 | private String houseNumber; 38 | private String city; 39 | private String postalCode; 40 | 41 | @OneToMany 42 | private List deliveryItems; 43 | 44 | private LocalDate scheduledFor; 45 | private Double value; 46 | private String fault; 47 | 48 | public Complaint(Resolution requestedResolution, String firstName, String lastName, String email, String phoneNumber, String street, 49 | String houseNumber, String city, String postalCode, List deliveryItems, 50 | LocalDate scheduledFor, String fault) { 51 | this.status = ComplaintStatus.IN_PROGRESS; 52 | this.resolution = Resolution.UNRESOLVED; 53 | this.requestedResolution = requestedResolution; 54 | this.firstName = firstName; 55 | this.lastName = lastName; 56 | this.email = email; 57 | this.phoneNumber = phoneNumber; 58 | this.street = street; 59 | this.houseNumber = houseNumber; 60 | this.city = city; 61 | this.postalCode = postalCode; 62 | this.deliveryItems = deliveryItems; 63 | this.scheduledFor = scheduledFor; 64 | this.value = deliveryItems.stream() 65 | .map(deliveryItem -> deliveryItem.getItem().getCurrentPrice() * deliveryItem.getQuantity()) 66 | .mapToDouble(Double::doubleValue) 67 | .sum(); 68 | this.fault = fault; 69 | } 70 | 71 | public void updateStatus(ComplaintStatus status) { 72 | this.status = status; 73 | } 74 | 75 | public void updateResolution(Resolution resolution) { 76 | this.resolution = resolution; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/model/ComplaintStatus.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.model; 2 | 3 | public enum ComplaintStatus { 4 | IN_PROGRESS, ACCEPTED, DECLINED, MONEY_RETURNED, NEW_ITEM_SENT, REPAIRING_ITEM, REPAIRED_ITEM_SENT, DECLINED_ITEM_SENT 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/model/Delivery.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | import java.time.LocalDate; 8 | import java.util.List; 9 | 10 | @Entity 11 | @Getter 12 | @NoArgsConstructor 13 | public class Delivery { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private long id; 18 | 19 | @OneToMany 20 | List deliveryItems; 21 | 22 | private LocalDate scheduledFor; 23 | private double value; 24 | private boolean confirmed; 25 | 26 | public Delivery(List deliveryItems, LocalDate scheduledFor) { 27 | this.deliveryItems = deliveryItems; 28 | this.scheduledFor = scheduledFor; 29 | this.value = deliveryItems.stream() 30 | .map(deliveryItem -> deliveryItem.getItem().getStockPrice()*deliveryItem.getQuantity()) 31 | .mapToDouble(Double::doubleValue) 32 | .sum(); 33 | this.confirmed = false; 34 | } 35 | 36 | public void confirm() { 37 | this.confirmed = true; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/model/DeliveryItem.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | 8 | @Entity 9 | @Getter 10 | @NoArgsConstructor 11 | public class DeliveryItem { 12 | 13 | @Id 14 | @GeneratedValue(strategy = GenerationType.IDENTITY) 15 | private long id; 16 | 17 | @ManyToOne 18 | private Item item; 19 | 20 | private int quantity; 21 | 22 | public DeliveryItem(Item item, int quantity) { 23 | this.item = item; 24 | this.quantity = quantity; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/model/Item.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | import lombok.Setter; 6 | 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.GenerationType; 10 | import javax.persistence.Id; 11 | 12 | @Entity 13 | @Getter 14 | @NoArgsConstructor 15 | public class Item { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | private String name; 22 | private int quantity; 23 | private double stockPrice; 24 | private double originalPrice; 25 | 26 | @Setter 27 | private double currentPrice; 28 | 29 | public Item(String name, int quantity, double stockPrice, double price) { 30 | this.name = name; 31 | this.quantity = quantity; 32 | this.stockPrice = stockPrice; 33 | this.originalPrice = price; 34 | this.currentPrice = price; 35 | } 36 | 37 | public void supply(int q) { 38 | quantity += q; 39 | } 40 | 41 | public void sell(int q) { 42 | quantity -= q; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/model/Order.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | import lombok.Setter; 6 | 7 | import javax.persistence.*; 8 | import javax.validation.constraints.Email; 9 | import javax.validation.constraints.Pattern; 10 | import java.time.LocalDate; 11 | import java.util.List; 12 | 13 | @Entity 14 | @Getter 15 | @Setter 16 | @NoArgsConstructor 17 | @Table(name = "orders") 18 | public class Order { 19 | 20 | @Id 21 | @GeneratedValue(strategy = GenerationType.IDENTITY) 22 | private long id; 23 | 24 | @Column(nullable = false) 25 | @Enumerated(EnumType.STRING) 26 | private Status status; 27 | 28 | @Column(nullable = false) 29 | private String firstName; 30 | 31 | @Column(nullable = false) 32 | private String lastName; 33 | 34 | @Column(nullable = false) 35 | @Email 36 | private String email; 37 | 38 | @Column(nullable = false) 39 | @Pattern(regexp = "[0-9]{9}") 40 | private String phoneNumber; 41 | 42 | @Column(nullable = false) 43 | private String street; 44 | 45 | @Column(nullable = false) 46 | private String houseNumber; 47 | 48 | @Column(nullable = false) 49 | private String city; 50 | 51 | @Column(nullable = false) 52 | @Pattern(regexp = "[0-9]{2}-?[0-9]{3}") 53 | private String postalCode; 54 | 55 | @Column(nullable = false) 56 | @OneToMany 57 | private List deliveryItems; 58 | 59 | @Column(nullable = false) 60 | private LocalDate scheduledFor; 61 | private LocalDate submissionDate; 62 | private LocalDate closingDate; 63 | 64 | @Column(nullable = false) 65 | private Double value; 66 | 67 | public Order(String firstName, String lastName, String email, String phoneNumber, String street, 68 | String houseNumber, String city, String postalCode, List deliveryItems, 69 | LocalDate scheduledFor) { 70 | this.status = Status.WAITING_FOR_PAYMENT; 71 | this.firstName = firstName; 72 | this.lastName = lastName; 73 | this.email = email; 74 | this.phoneNumber = phoneNumber; 75 | this.street = street; 76 | this.houseNumber = houseNumber; 77 | this.city = city; 78 | this.postalCode = postalCode; 79 | this.deliveryItems = deliveryItems; 80 | this.scheduledFor = scheduledFor; 81 | this.value = deliveryItems.stream() 82 | .map(deliveryItem -> deliveryItem.getItem().getCurrentPrice() * deliveryItem.getQuantity()) 83 | .mapToDouble(Double::doubleValue) 84 | .sum(); 85 | this.submissionDate = LocalDate.now(); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/model/Resolution.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.model; 2 | 3 | public enum Resolution { 4 | UNRESOLVED, MONEY_RETURN, REPAIR, EXCHANGE_FOR_NEW 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/model/Return.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | import javax.validation.constraints.Email; 8 | import java.time.LocalDate; 9 | import java.util.List; 10 | 11 | @Entity 12 | @Getter 13 | @NoArgsConstructor 14 | public class Return { 15 | 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | 20 | @Enumerated(EnumType.STRING) 21 | private ReturnStatus status; 22 | 23 | private String firstName; 24 | private String lastName; 25 | 26 | @Email 27 | private String email; 28 | 29 | private String phoneNumber; 30 | private String street; 31 | private String houseNumber; 32 | private String city; 33 | private String postalCode; 34 | 35 | @OneToMany 36 | private List deliveryItems; 37 | 38 | private LocalDate scheduledFor; 39 | private Double value; 40 | 41 | public Return(String firstName, String lastName, String email, String phoneNumber, String street, 42 | String houseNumber, String city, String postalCode, List deliveryItems, 43 | LocalDate scheduledFor) { 44 | this.status = ReturnStatus.IN_PROGRESS; 45 | this.firstName = firstName; 46 | this.lastName = lastName; 47 | this.email = email; 48 | this.phoneNumber = phoneNumber; 49 | this.street = street; 50 | this.houseNumber = houseNumber; 51 | this.city = city; 52 | this.postalCode = postalCode; 53 | this.deliveryItems = deliveryItems; 54 | this.scheduledFor = scheduledFor; 55 | this.value = deliveryItems.stream() 56 | .map(deliveryItem -> deliveryItem.getItem().getCurrentPrice() * deliveryItem.getQuantity()) 57 | .mapToDouble(Double::doubleValue) 58 | .sum(); 59 | } 60 | 61 | public void updateStatus(ReturnStatus status) { 62 | this.status = status; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/model/ReturnStatus.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.model; 2 | 3 | public enum ReturnStatus { 4 | IN_PROGRESS, ACCEPTED, DECLINED, MONEY_RETURNED 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/model/Status.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.model; 2 | 3 | public enum Status { 4 | WAITING_FOR_PAYMENT, IN_PROGRESS, SENT, DECLINED; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/repository/ComplaintRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Complaint; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface ComplaintRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/repository/DeliveryItemRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.DeliveryItem; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface DeliveryItemRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/repository/DeliveryRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Delivery; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface DeliveryRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/repository/ItemRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Item; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface ItemRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/repository/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Order; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface OrderRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/repository/ReturnRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Return; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface ReturnRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/request/DeliveryItemRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import javax.validation.constraints.NotNull; 8 | 9 | @Data 10 | @NoArgsConstructor 11 | @AllArgsConstructor 12 | public class DeliveryItemRequest { 13 | 14 | @NotNull 15 | private long itemId; 16 | 17 | @NotNull 18 | private int quantity; 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/request/DeliveryRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import javax.validation.constraints.NotNull; 8 | import java.time.LocalDate; 9 | import java.util.List; 10 | 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | public class DeliveryRequest { 15 | 16 | @NotNull 17 | private List deliveryItemRequests; 18 | 19 | @NotNull 20 | private LocalDate scheduledFor; 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/request/ItemRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.request; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Item; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.validation.constraints.NotNull; 9 | 10 | @Data 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | public class ItemRequest { 14 | 15 | @NotNull 16 | private String name; 17 | 18 | @NotNull 19 | private double stockPrice; 20 | 21 | @NotNull 22 | private double price; 23 | 24 | public Item extractItem() { 25 | return new Item(name, 0, stockPrice, price); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/request/ShopServiceRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.request; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Resolution; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.DeliveryItemRequest; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | import lombok.NonNull; 9 | 10 | import java.time.LocalDate; 11 | import java.util.List; 12 | 13 | @Data 14 | @NoArgsConstructor 15 | @AllArgsConstructor 16 | public class ShopServiceRequest { 17 | 18 | @NonNull 19 | private String firstName; 20 | 21 | @NonNull 22 | private String lastName; 23 | 24 | @NonNull 25 | private String email; 26 | 27 | private String phoneNumber; 28 | 29 | @NonNull 30 | private String street; 31 | 32 | @NonNull 33 | private String houseNumber; 34 | 35 | @NonNull 36 | private String city; 37 | 38 | @NonNull 39 | private String postalCode; 40 | 41 | @NonNull 42 | private List deliveryItemRequests; 43 | 44 | @NonNull 45 | private LocalDate scheduledFor; 46 | 47 | private Resolution RequestedResolution; 48 | private String fault; 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/service/DeliveryService.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.service; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Delivery; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.DeliveryItem; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Item; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Order; 8 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.repository.DeliveryItemRepository; 9 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.repository.DeliveryRepository; 10 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.repository.ItemRepository; 11 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.repository.OrderRepository; 12 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.DeliveryItemRequest; 13 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.DeliveryRequest; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.stereotype.Service; 16 | 17 | import java.time.LocalDate; 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | import java.util.stream.Collectors; 21 | 22 | import static java.time.temporal.ChronoUnit.DAYS; 23 | 24 | @Service 25 | public class DeliveryService { 26 | 27 | private final ItemRepository itemRepository; 28 | private final DeliveryItemRepository deliveryItemRepository; 29 | private final DeliveryRepository deliveryRepository; 30 | private final OrderRepository orderRepository; 31 | 32 | @Autowired 33 | public DeliveryService(ItemRepository itemRepository, DeliveryItemRepository deliveryItemRepository, 34 | DeliveryRepository deliveryRepository, OrderRepository orderRepository) { 35 | this.itemRepository = itemRepository; 36 | this.deliveryItemRepository = deliveryItemRepository; 37 | this.deliveryRepository = deliveryRepository; 38 | this.orderRepository = orderRepository; 39 | } 40 | 41 | public Delivery addDelivery(DeliveryRequest request) { 42 | List deliveryItems = new ArrayList<>(); 43 | request.getDeliveryItemRequests().forEach(deliveryItemRequest -> { 44 | addDeliveryItem(deliveryItemRequest, deliveryItems); 45 | }); 46 | Delivery delivery = new Delivery(deliveryItems, request.getScheduledFor()); 47 | deliveryRepository.save(delivery); 48 | return delivery; 49 | } 50 | 51 | public void addDeliveryItem(DeliveryItemRequest deliveryItemRequest, List deliveryItems) { 52 | if (itemRepository.findById(deliveryItemRequest.getItemId()).isPresent()) { 53 | Item item = itemRepository.findById(deliveryItemRequest.getItemId()).get(); 54 | DeliveryItem deliveryItem = new DeliveryItem(item, deliveryItemRequest.getQuantity()); 55 | deliveryItemRepository.save(deliveryItem); 56 | deliveryItems.add(deliveryItem); 57 | } 58 | } 59 | 60 | 61 | public void checkIfDeliveryExists(long id) { 62 | if (!deliveryRepository.findById(id).isPresent()) { 63 | throw new NotFoundException("Such delivery doesn't exist!"); 64 | } 65 | } 66 | 67 | public List getRecommendedDelivery() { 68 | List deliveryItems = new ArrayList<>(); 69 | List items = itemRepository.findAll(); 70 | List orders = orderRepository.findAll().stream() 71 | .filter(order -> DAYS.between(order.getSubmissionDate(), LocalDate.now()) < 30) 72 | .collect(Collectors.toList()); 73 | if (orders == null || orders.size() == 0) { 74 | return deliveryItems; 75 | } 76 | for (Item item : items) { 77 | int sum = 0; 78 | for (Order order : orders) { 79 | for (DeliveryItem deliveryItem: order.getDeliveryItems()) { 80 | if (deliveryItem.getItem().getId() == item.getId()) { 81 | sum += deliveryItem.getQuantity(); 82 | } 83 | } 84 | } 85 | if (sum > 0) { 86 | deliveryItems.add(new DeliveryItemRequest(item.getId(), sum)); 87 | } 88 | } 89 | return deliveryItems; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/shop/service/ItemService.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.shop.service; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.InvalidRequestException; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Item; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.repository.ItemRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | import java.util.stream.Collectors; 13 | 14 | @Service 15 | public class ItemService { 16 | 17 | private final ItemRepository itemRepository; 18 | 19 | @Autowired 20 | public ItemService(ItemRepository itemRepository) { 21 | this.itemRepository = itemRepository; 22 | } 23 | 24 | public List updateItems(double multiplier, String query) { 25 | List items = itemRepository.findAll(); 26 | if (query != null && !query.equals("")) { 27 | items = items.stream().filter(item -> item.getName().toLowerCase().contains(query.toLowerCase())) 28 | .collect(Collectors.toList()); 29 | } 30 | List updatedItems = new ArrayList<>(); 31 | items.forEach(item -> { 32 | item.setCurrentPrice(item.getOriginalPrice() * multiplier); 33 | itemRepository.save(item); 34 | updatedItems.add(item); 35 | }); 36 | return updatedItems; 37 | } 38 | 39 | public void checkIfItemExists(long id) { 40 | if (!itemRepository.findById(id).isPresent()) { 41 | throw new NotFoundException("Such item doesn't exist!"); 42 | } 43 | } 44 | 45 | public void checkIfIsEnough(Item item, int q) { 46 | if (q > item.getQuantity()) { 47 | throw new InvalidRequestException("There's not enough of this item!"); 48 | } 49 | } 50 | 51 | public Item supplyItem(long id, int quantity) { 52 | Item item = itemRepository.findById(id).get(); 53 | item.supply(quantity); 54 | itemRepository.save(item); 55 | return item; 56 | } 57 | 58 | public Item buyItem(long id, int quantity) { 59 | Item item = itemRepository.findById(id).get(); 60 | checkIfIsEnough(item, quantity); 61 | item.sell(quantity); 62 | itemRepository.save(item); 63 | return item; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/controller/HolidayController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.service.EmployeeService; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.repository.HolidayRepository; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.request.HolidayRequest; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.service.HolidayService; 8 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Holiday; 9 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.HolidayType; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | import java.nio.file.AccessDeniedException; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | @RestController 19 | @CrossOrigin(origins = "*") 20 | public class HolidayController { 21 | 22 | private final String HOLIDAY_NOT_FOUND = "Such holiday request doesn't exist!"; 23 | 24 | private final HolidayRepository holidayRepository; 25 | private final HolidayService holidayService; 26 | private final EmployeeService employeeService; 27 | 28 | @Autowired 29 | public HolidayController(HolidayRepository holidayRepository, HolidayService holidayService, 30 | EmployeeService employeeService) { 31 | this.holidayRepository = holidayRepository; 32 | this.holidayService = holidayService; 33 | this.employeeService = employeeService; 34 | } 35 | 36 | @GetMapping("/employees/{id}/holidays") 37 | @ResponseStatus(HttpStatus.OK) 38 | public List getAllHolidays(@PathVariable("id") long id) { 39 | employeeService.checkIfEmployeeExists(id); 40 | return holidayRepository.findByEmployeeId(id) 41 | .orElse(new ArrayList<>()); 42 | } 43 | 44 | @PostMapping("/employees/{id}/holidays") 45 | @ResponseStatus(HttpStatus.CREATED) 46 | public Holiday addNewHoliday(@PathVariable("id") long id, 47 | @RequestBody HolidayRequest request) throws AccessDeniedException { 48 | employeeService.checkIfEmployeeExists(id); 49 | employeeService.checkIfUserLoggedIn(id); 50 | if (request.getHolidayType().equals(HolidayType.VACATION)) { 51 | holidayService.checkIfCanTakeDaysOff(id, request); 52 | } 53 | return holidayService.addHoliday(request, id); 54 | } 55 | 56 | @GetMapping("/employees/{managerId}/subordinates/holiday-requests") 57 | @ResponseStatus(HttpStatus.OK) 58 | public List getHolidays(@PathVariable("managerId") long managerId) { 59 | employeeService.checkIfEmployeeExists(managerId); 60 | employeeService.checkIfIsManager(managerId); 61 | return holidayService.getHolidayRequests(managerId); 62 | } 63 | 64 | @PostMapping("/employees/{managerId}/subordinates/{subordinateId}/holidays") 65 | @ResponseStatus(HttpStatus.OK) 66 | public Holiday manageHolidayRequest(@PathVariable("managerId") long managerId, 67 | @PathVariable("subordinateId") long subordinateId, 68 | @RequestBody long holidayId, 69 | @RequestParam(value = "approve") boolean approve) { 70 | checkEmployees(managerId, subordinateId); 71 | Holiday holiday = holidayRepository.findById(holidayId) 72 | .orElseThrow(() -> new NotFoundException(HOLIDAY_NOT_FOUND)); 73 | holidayService.checkIfHolidayPending(holidayId); 74 | if (approve) { 75 | holiday.approve(); 76 | } else { 77 | holiday.decline(); 78 | } 79 | holidayRepository.save(holiday); 80 | return holiday; 81 | } 82 | 83 | private void checkEmployees(long managerId, long subordinateId) { 84 | employeeService.checkIfEmployeeExists(managerId); 85 | employeeService.checkIfIsManager(managerId); 86 | employeeService.checkIfEmployeeExists(subordinateId); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/controller/TeamController.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.controller; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.dto.TeamDTO; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.repository.EmployeeRepository; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.repository.TeamRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | @RestController 15 | @CrossOrigin(origins = "*") 16 | public class TeamController { 17 | 18 | private final String TEAM_NOT_FOUND = "Such team doesn't exist!"; 19 | 20 | private final TeamRepository teamRepository; 21 | 22 | @Autowired 23 | public TeamController(TeamRepository teamRepository) { 24 | this.teamRepository = teamRepository; 25 | } 26 | 27 | @GetMapping("/teams") 28 | @ResponseStatus(HttpStatus.OK) 29 | public List getAllTeams() { 30 | List teamDTOS = new ArrayList<>(); 31 | teamRepository.findAll().forEach(team -> teamDTOS.add(new TeamDTO(team))); 32 | return teamDTOS; 33 | } 34 | 35 | @GetMapping("/teams/{id}") 36 | @ResponseStatus(HttpStatus.OK) 37 | public TeamDTO getOneTeam(@PathVariable("id") long id) { 38 | return new TeamDTO(teamRepository.findById(id) 39 | .orElseThrow(() -> new NotFoundException(TEAM_NOT_FOUND))); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/dto/EmployeeDTO.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.dto; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Role; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | 8 | @Data 9 | @AllArgsConstructor 10 | public class EmployeeDTO { 11 | 12 | private long id; 13 | private String firstName; 14 | private String lastName; 15 | private String email; 16 | private Role role; 17 | 18 | public EmployeeDTO(Employee employee) { 19 | this.id = employee.getId(); 20 | this.firstName = employee.getFirstName(); 21 | this.lastName = employee.getLastName(); 22 | this.email = employee.getEmail(); 23 | this.role = employee.getRole(); 24 | } 25 | 26 | public boolean isManager() { 27 | return role.name().contains("ADMIN"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/dto/TeamDTO.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.dto; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Role; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Team; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | @Data 12 | @AllArgsConstructor 13 | public class TeamDTO { 14 | 15 | private long id; 16 | private Role role; 17 | private EmployeeDTO manager; 18 | private List employees; 19 | 20 | public TeamDTO(Team team) { 21 | this.id = team.getId(); 22 | this.role = team.getRole(); 23 | this.manager = team.getManager() == null ? null : new EmployeeDTO(team.getManager()); 24 | employees = new ArrayList<>(); 25 | if(team.getEmployees().size() > 0) { 26 | team.getEmployees().forEach(employee -> employees.add(new EmployeeDTO(employee))); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/dto/UserDTO.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.dto; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Contract; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Role; 6 | import lombok.AllArgsConstructor; 7 | import lombok.Data; 8 | 9 | @Data 10 | @AllArgsConstructor 11 | public class UserDTO { 12 | 13 | private long id; 14 | private String firstName; 15 | private String lastName; 16 | private String email; 17 | private Role role; 18 | private Contract contract; 19 | boolean isPasswordValid; 20 | 21 | public UserDTO(Employee employee) { 22 | this.id = employee.getId(); 23 | this.firstName = employee.getFirstName(); 24 | this.lastName = employee.getLastName(); 25 | this.email = employee.getEmail(); 26 | this.role = employee.getRole(); 27 | this.contract = employee.getContract(); 28 | this.isPasswordValid = employee.isPasswordValid(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/factory/EmployeeFactory.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.factory; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.request.ContractRequest; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.request.EmployeeRequest; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Role; 7 | 8 | import java.util.Arrays; 9 | import java.util.List; 10 | import java.util.Random; 11 | import java.util.stream.Collectors; 12 | 13 | public class EmployeeFactory { 14 | 15 | private final String[] FIRST_NAMES = {"Jolanta", "Jakub", "Mateusz", 16 | "Wojciech", "Karolina", "Klara", "Justyna", "Maciej", 17 | "Krzysztof", "Marcin", "Anna", "Katarzyna", "Michał"}; 18 | private final String[] LAST_NAMES = {"Kowalski", "Nowak", "Wójcik", 19 | "Wojciechowski", "Jędrzejczyk", "Grabowski", "Kopeć"}; 20 | private final Random r; 21 | 22 | public EmployeeFactory() { 23 | r = new Random(); 24 | } 25 | 26 | private String generate(String[] table) { 27 | return table[r.nextInt(table.length)]; 28 | } 29 | 30 | private String generateEmail(String firstName, String lastName) { 31 | return firstName.toLowerCase() + "." + lastName.toLowerCase() + r.nextInt() + "@domain.com"; 32 | } 33 | 34 | public Role generateRole() { 35 | return Role.values()[r.nextInt(Role.values().length)]; 36 | } 37 | 38 | private Role generateAdminRole() { 39 | List roles = Arrays.asList(Role.values()); 40 | List adminRoles = roles.stream() 41 | .filter(role -> role.name().contains("ADMIN")) 42 | .collect(Collectors.toList()); 43 | return adminRoles.get(r.nextInt(adminRoles.size())); 44 | } 45 | 46 | private Role generateNonAdminRole() { 47 | List roles = Arrays.asList(Role.values()); 48 | List nonAdminRoles = roles.stream() 49 | .filter(role -> !role.name().contains("ADMIN")) 50 | .collect(Collectors.toList()); 51 | return nonAdminRoles.get(r.nextInt(nonAdminRoles.size())); 52 | } 53 | 54 | private ContractRequest generateContractRequest() { 55 | StringBuilder accountNumberBuilder = new StringBuilder(); 56 | for(int i = 0; i < 26; i++) { 57 | accountNumberBuilder.append(r.nextInt(10)); 58 | } 59 | return new ContractRequest(accountNumberBuilder.toString(), r.nextInt(7)+20, 60 | r.nextDouble()+2000.00); 61 | } 62 | 63 | public EmployeeRequest generateEmployeeRequestWithRole(Role role) { 64 | String firstName = generate(FIRST_NAMES); 65 | String lastName = generate(LAST_NAMES); 66 | return new EmployeeRequest(firstName, lastName, generateEmail(firstName, lastName), 67 | role, generateContractRequest()); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/factory/HolidayFactory.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.factory; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.request.HolidayRequest; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.HolidayType; 5 | 6 | import java.time.LocalDate; 7 | import java.util.Random; 8 | import java.util.concurrent.ThreadLocalRandom; 9 | 10 | public class HolidayFactory { 11 | 12 | private Random r; 13 | 14 | public HolidayFactory() { 15 | r = new Random(); 16 | } 17 | 18 | private LocalDate generateStartDate() { 19 | long today = LocalDate.now().toEpochDay(); 20 | long randomDay = ThreadLocalRandom.current().nextLong(today + 1, today + 20); 21 | return LocalDate.ofEpochDay(randomDay); 22 | } 23 | 24 | private int generateDuration() { 25 | return r.nextInt(5) + 1; 26 | } 27 | 28 | public HolidayRequest generateHolidayRequest() { 29 | return new HolidayRequest(generateStartDate(), generateDuration(), HolidayType.VACATION); 30 | } 31 | 32 | public HolidayRequest generateHolidayRequestWithType(HolidayType type) { 33 | return new HolidayRequest(generateStartDate(), generateDuration(), type); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/model/ApprovalState.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.model; 2 | 3 | public enum ApprovalState { 4 | APPROVED, DECLINED, PENDING 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/model/Contract.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | 11 | @Entity 12 | @Getter 13 | @NoArgsConstructor 14 | public class Contract { 15 | 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | 20 | private String accountNumber; 21 | private int daysOffPerYear; 22 | private double salary; 23 | 24 | public Contract(String accountNumber, int daysOffPerYear, double salary) { 25 | this.accountNumber = accountNumber; 26 | this.daysOffPerYear = daysOffPerYear; 27 | this.salary = salary; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/model/Employee.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | import javax.validation.constraints.Email; 8 | import java.util.Random; 9 | 10 | @Entity 11 | @Getter 12 | @NoArgsConstructor 13 | public class Employee { 14 | 15 | private final int PASSWORD_LENGTH = 8; 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | private String firstName; 22 | private String lastName; 23 | 24 | @Email 25 | private String email; 26 | 27 | @Enumerated(EnumType.STRING) 28 | private Role role; 29 | 30 | private String password; 31 | private boolean isPasswordValid; 32 | 33 | @OneToOne 34 | private Contract contract; 35 | 36 | public Employee(String firstName, String lastName, String email, Role role, Contract contract) { 37 | this.firstName = firstName; 38 | this.lastName = lastName; 39 | this.email = email; 40 | this.role = role; 41 | this.password = passwordGenerator(); 42 | this.isPasswordValid = false; 43 | this.contract = contract; 44 | } 45 | 46 | public boolean isManager() { 47 | return role.name().contains("ADMIN"); 48 | } 49 | 50 | private String passwordGenerator() { 51 | char[] password = new char[PASSWORD_LENGTH]; 52 | Random r = new Random(); 53 | for (int i = 0; i < PASSWORD_LENGTH; i++) { 54 | password[i] = (char) (r.nextInt('z' - 'a') + 'a'); 55 | } 56 | return new String(password); 57 | } 58 | 59 | public void encodePassword(String hashedPassword) { 60 | this.password = hashedPassword; 61 | } 62 | 63 | public void changePassword(String newPassword) { 64 | this.password = newPassword; 65 | this.isPasswordValid = true; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/model/Holiday.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | import java.time.DayOfWeek; 8 | import java.time.LocalDate; 9 | 10 | @Entity 11 | @Getter 12 | @NoArgsConstructor 13 | public class Holiday { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private long id; 18 | 19 | private LocalDate startDate; 20 | private int duration; 21 | 22 | @Enumerated(EnumType.STRING) 23 | private HolidayType holidayType; 24 | 25 | ApprovalState approvalState; 26 | 27 | @ManyToOne 28 | private Employee employee; 29 | 30 | public Holiday(LocalDate startDate, int duration, HolidayType holidayType, Employee employee) { 31 | this.startDate = startDate; 32 | this.duration = duration; 33 | this.holidayType = holidayType; 34 | this.employee = employee; 35 | this.approvalState = (!holidayType.equals(HolidayType.VACATION) || employee.getRole().equals(Role.ADMIN)) ? 36 | ApprovalState.APPROVED : ApprovalState.PENDING; 37 | } 38 | 39 | public void approve() { 40 | approvalState = ApprovalState.APPROVED; 41 | } 42 | 43 | public void decline() { 44 | approvalState = ApprovalState.DECLINED; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/model/HolidayType.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.model; 2 | 3 | public enum HolidayType { 4 | VACATION, SICK_LEAVE, PARENTAL_LEAVE, BEREAVEMENT, EMERGENCY_CHILD_CARE 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.model; 2 | 3 | public enum Role { 4 | ADMIN, ACCOUNTANT, ADMIN_ACCOUNTANT, ANALYST, ADMIN_ANALYST, WAREHOUSE, ADMIN_WAREHOUSE 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/model/Team.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.model; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | @Entity 11 | @Getter 12 | @NoArgsConstructor 13 | public class Team { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private long id; 18 | 19 | @Enumerated(EnumType.STRING) 20 | private Role role; 21 | 22 | @ManyToOne 23 | private Employee manager; 24 | 25 | @ManyToMany 26 | private List employees; 27 | 28 | public Team(Role role) { 29 | this.role = role; 30 | employees = new ArrayList<>(); 31 | } 32 | 33 | public void addEmployee(Employee employee) { 34 | if(employee.getRole().name().contains("ADMIN")) { 35 | if(employee.getRole().equals(Role.ADMIN) && manager == null && role.equals(Role.ADMIN)) { 36 | manager = employee; 37 | } else if (!employee.getRole().equals(Role.ADMIN) && role.equals(Role.ADMIN)) { 38 | employees.add(employee); 39 | } else if (!employee.getRole().equals(Role.ADMIN) && manager == null) { 40 | manager = employee; 41 | } 42 | } else { 43 | if (employee.getRole().name().contains(role.name())) { 44 | employees.add(employee); 45 | } 46 | } 47 | } 48 | 49 | public void removeManager() { 50 | manager = null; 51 | } 52 | 53 | public void removeEmployee(Employee employee) { 54 | employees.remove(employee); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/repository/ContractRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Contract; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface ContractRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/repository/EmployeeRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Role; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.List; 9 | import java.util.Optional; 10 | 11 | @Repository 12 | public interface EmployeeRepository extends JpaRepository { 13 | 14 | Optional> findByRole(Role role); 15 | 16 | Optional findByEmail(String email); 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/repository/HolidayRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Holiday; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.List; 8 | import java.util.Optional; 9 | 10 | @Repository 11 | public interface HolidayRepository extends JpaRepository { 12 | 13 | Optional> findByEmployeeId(long id); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/repository/TeamRepository.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.repository; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Role; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Team; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.Optional; 9 | 10 | @Repository 11 | public interface TeamRepository extends JpaRepository { 12 | 13 | Optional findByManagerId(Long id); 14 | 15 | Team findByRole(Role role); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/request/AdminRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.request; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Role; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | import javax.validation.constraints.Email; 10 | import javax.validation.constraints.NotNull; 11 | 12 | @Data 13 | @NoArgsConstructor 14 | @AllArgsConstructor 15 | public class AdminRequest { 16 | 17 | @NotNull 18 | private String firstName; 19 | 20 | @NotNull 21 | private String lastName; 22 | 23 | @Email 24 | @NotNull 25 | private String email; 26 | 27 | @NotNull 28 | private String password; 29 | 30 | @NotNull 31 | private ContractRequest contractRequest; 32 | 33 | public Employee extractUser() { 34 | Employee employee = new Employee(firstName, lastName, email, Role.ADMIN, 35 | contractRequest.extractContract()); 36 | employee.changePassword(password); 37 | return employee; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/request/ContractRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.request; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Contract; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.validation.constraints.NotNull; 9 | 10 | @Data 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | public class ContractRequest { 14 | 15 | @NotNull 16 | private String accountNumber; 17 | 18 | @NotNull 19 | private int daysOffPerYear; 20 | 21 | @NotNull 22 | private double salary; 23 | 24 | Contract extractContract() { 25 | return new Contract(accountNumber, daysOffPerYear, salary); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/request/EmployeeRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.request; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Role; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | import javax.validation.constraints.Email; 10 | import javax.validation.constraints.NotNull; 11 | 12 | @Data 13 | @NoArgsConstructor 14 | @AllArgsConstructor 15 | public class EmployeeRequest { 16 | 17 | @NotNull 18 | private String firstName; 19 | 20 | @NotNull 21 | private String lastName; 22 | 23 | @Email 24 | @NotNull 25 | private String email; 26 | 27 | @NotNull 28 | private Role role; 29 | 30 | @NotNull 31 | private ContractRequest contractRequest; 32 | 33 | public Employee extractUser() { 34 | return new Employee(firstName, lastName, email, role, 35 | contractRequest.extractContract()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/request/HolidayRequest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.request; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.HolidayType; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.validation.constraints.NotNull; 9 | import java.time.LocalDate; 10 | 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | public class HolidayRequest { 15 | 16 | @NotNull 17 | private LocalDate startDate; 18 | 19 | @NotNull 20 | private int duration; 21 | 22 | @NotNull 23 | private HolidayType holidayType; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/herokuapp/erpmesbackend/erpmesbackend/staff/service/HolidayService.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.staff.service; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Employee; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.repository.EmployeeRepository; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.InvalidRequestException; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.exceptions.NotFoundException; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.request.HolidayRequest; 8 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.ApprovalState; 9 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.Holiday; 10 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.model.HolidayType; 11 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.repository.HolidayRepository; 12 | import com.herokuapp.erpmesbackend.erpmesbackend.staff.repository.TeamRepository; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.stereotype.Service; 15 | 16 | import java.time.DayOfWeek; 17 | import java.time.LocalDate; 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | @Service 22 | public class HolidayService { 23 | 24 | private final EmployeeRepository employeeRepository; 25 | private final HolidayRepository holidayRepository; 26 | private final TeamRepository teamRepository; 27 | 28 | @Autowired 29 | public HolidayService(EmployeeRepository employeeRepository, HolidayRepository holidayRepository, 30 | TeamRepository teamRepository) { 31 | this.employeeRepository = employeeRepository; 32 | this.holidayRepository = holidayRepository; 33 | this.teamRepository = teamRepository; 34 | } 35 | 36 | public void checkIfCanTakeDaysOff(long id, HolidayRequest request) { 37 | Employee employee = employeeRepository.findById(id) 38 | .orElseThrow(NotFoundException::new); 39 | if (holidayRepository.findByEmployeeId(id).isPresent()) { 40 | List holidays = holidayRepository.findByEmployeeId(id).get(); 41 | int daysOffTaken = holidays.stream() 42 | .filter(holiday -> holiday.getHolidayType().equals(HolidayType.VACATION)) 43 | .filter(holiday -> holiday.getStartDate().getYear() == LocalDate.now().getYear()) 44 | .map(Holiday::getDuration) 45 | .mapToInt(Integer::intValue) 46 | .sum(); 47 | int daysOffPerYear = employee.getContract().getDaysOffPerYear(); 48 | int requestedDuration = 0; 49 | for (int i = 0; i < request.getDuration(); i++) { 50 | if (!request.getStartDate().plusDays(i).getDayOfWeek().equals(DayOfWeek.SATURDAY) && 51 | !request.getStartDate().plusDays(i).getDayOfWeek().equals(DayOfWeek.SATURDAY)) { 52 | requestedDuration++; 53 | } 54 | } 55 | if (daysOffTaken == daysOffPerYear) { 56 | throw new InvalidRequestException("You've already used all your vacation days for this year!"); 57 | } else if ((daysOffPerYear - daysOffTaken) < requestedDuration) { 58 | throw new InvalidRequestException("You don't have enough available days to take such a long vacation this year!"); 59 | } 60 | } 61 | } 62 | 63 | public List getHolidayRequests(Long managerId) { 64 | List holidays = new ArrayList<>(); 65 | if (!teamRepository.findByManagerId(managerId).isPresent()) { 66 | return new ArrayList<>(); 67 | } 68 | List employees = teamRepository.findByManagerId(managerId) 69 | .get().getEmployees(); 70 | if (employees.size() == 0) { 71 | return new ArrayList<>(); 72 | } 73 | employees.forEach(employee -> { 74 | if (holidayRepository 75 | .findByEmployeeId(employee.getId()).isPresent()) { 76 | holidays.addAll(holidayRepository 77 | .findByEmployeeId(employee.getId()).get()); 78 | } 79 | }); 80 | return holidays.size() > 0 ? holidays : new ArrayList<>(); 81 | } 82 | 83 | public void checkIfHolidayPending(long id) { 84 | if (!holidayRepository.findById(id) 85 | .orElseThrow(NotFoundException::new) 86 | .getApprovalState().equals(ApprovalState.PENDING)) { 87 | throw new InvalidRequestException("This holiday has already been managed!"); 88 | } 89 | } 90 | 91 | public Holiday addHoliday(HolidayRequest request, Long id) { 92 | Employee employee = employeeRepository.findById(id) 93 | .orElseThrow(NotFoundException::new); 94 | Holiday holiday = new Holiday(request.getStartDate(), request.getDuration(), 95 | request.getHolidayType(), employee); 96 | holidayRepository.save(holiday); 97 | return holiday; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.driverClassName=org.postgresql.Driver 2 | spring.datasource.hikari.maximum-pool-size=2 3 | spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false 4 | spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect 5 | spring.datasource.url=jdbc:postgresql://localhost:5432/erpmes 6 | spring.datasource.username=postgres 7 | spring.datasource.password=postgres1 8 | spring.jpa.hibernate.ddl-auto=update 9 | -------------------------------------------------------------------------------- /src/main/resources/db/changelog/db.changelog-master.yaml: -------------------------------------------------------------------------------- 1 | databaseChangeLog: 2 | - changeSet: 3 | id: 1 4 | author: admin 5 | -------------------------------------------------------------------------------- /src/test/java/com/herokuapp/erpmesbackend/erpmesbackend/erpmesbackend/ErpMesBackendApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ErpMesBackendApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/herokuapp/erpmesbackend/erpmesbackend/erpmesbackend/controllers/DeliveryControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.controllers; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.TestConfig; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Delivery; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.DeliveryItemRequest; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.http.HttpEntity; 11 | import org.springframework.http.HttpMethod; 12 | import org.springframework.http.HttpStatus; 13 | import org.springframework.http.ResponseEntity; 14 | import org.springframework.test.context.junit4.SpringRunner; 15 | 16 | import static org.assertj.core.api.Assertions.assertThat; 17 | 18 | @RunWith(SpringRunner.class) 19 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 20 | public class DeliveryControllerTest extends TestConfig { 21 | 22 | @Before 23 | public void init() { 24 | setup(); 25 | setupToken(); 26 | setupItems(); 27 | setupDeliveries(); 28 | } 29 | 30 | @Test 31 | public void readAllDeliveriesTest() { 32 | ResponseEntity forEntity = restTemplate.exchange("/deliveries", HttpMethod.GET, 33 | new HttpEntity<>(null, requestHeaders), Delivery[].class); 34 | 35 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 36 | assertThat(forEntity.getBody().length).isGreaterThan(0); 37 | } 38 | 39 | @Test 40 | public void addNewDeliveryTest() { 41 | ResponseEntity deliveryResponseEntity = restTemplate.postForEntity("/deliveries", 42 | new HttpEntity<>(getOneDeliveryRequest(), requestHeaders), Delivery.class); 43 | assertThat(deliveryResponseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED); 44 | } 45 | 46 | @Test 47 | public void readOneDeliveryTest() { 48 | for (int i = 0; i < deliveryRequests.size(); i++) { 49 | ResponseEntity forEntity = restTemplate.exchange("/deliveries/{id}", 50 | HttpMethod.GET, new HttpEntity<>(null, requestHeaders), 51 | Delivery.class, i + 1); 52 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 53 | assertThat(forEntity.getBody()).isNotNull(); 54 | } 55 | } 56 | 57 | @Test 58 | public void recommendDeliveryTest() { 59 | setupItemsAndSupply(); 60 | setupOrders(); 61 | 62 | ResponseEntity exchange = restTemplate.exchange("/deliveries/recommended-delivery", 63 | HttpMethod.GET, new HttpEntity<>(null, requestHeaders), DeliveryItemRequest[].class); 64 | assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); 65 | assertThat(exchange.getBody().length).isGreaterThan(0); 66 | } 67 | 68 | @Test 69 | public void shouldReturn404NotFound() { 70 | ResponseEntity forEntity = restTemplate.exchange("/deliveries/{id}", 71 | HttpMethod.GET, new HttpEntity<>(null, requestHeaders), 72 | String.class, 1234); 73 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/test/java/com/herokuapp/erpmesbackend/erpmesbackend/erpmesbackend/controllers/EmailControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.controllers; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.EmailEntity; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.TestConfig; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.http.HttpEntity; 10 | import org.springframework.http.HttpMethod; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | 15 | import static org.assertj.core.api.Assertions.assertThat; 16 | 17 | @RunWith(SpringRunner.class) 18 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 19 | public class EmailControllerTest extends TestConfig { 20 | 21 | @Before 22 | public void init() { 23 | setup(); 24 | setupToken(); 25 | } 26 | 27 | @Test 28 | public void readInboxTest() { 29 | ResponseEntity exchange = restTemplate.exchange("/emails/inbox", HttpMethod.GET, 30 | new HttpEntity<>(null, requestHeaders), EmailEntity[].class); 31 | 32 | assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); 33 | assertThat(exchange.getBody()).isNotNull(); 34 | } 35 | 36 | @Test 37 | public void readOutboxTest() { 38 | ResponseEntity exchange = restTemplate.exchange("/emails/outbox", HttpMethod.GET, 39 | new HttpEntity<>(null, requestHeaders), EmailEntity[].class); 40 | 41 | assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); 42 | assertThat(exchange.getBody()).isNotNull(); 43 | } 44 | 45 | @Test 46 | public void shouldReturn404NotFound() { 47 | ResponseEntity exchange = restTemplate.exchange("/emails/{id}", HttpMethod.GET, 48 | new HttpEntity<>(null, requestHeaders), String.class, 1234); 49 | assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/com/herokuapp/erpmesbackend/erpmesbackend/erpmesbackend/controllers/NotificationControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.controllers; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.dto.NotificationDTO; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.State; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.request.NotificationRequest; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.TestConfig; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.http.HttpEntity; 12 | import org.springframework.http.HttpMethod; 13 | import org.springframework.http.HttpStatus; 14 | import org.springframework.http.ResponseEntity; 15 | import org.springframework.test.context.junit4.SpringRunner; 16 | 17 | import java.util.Arrays; 18 | import java.util.List; 19 | 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | import static org.junit.Assert.assertTrue; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | public class NotificationControllerTest extends TestConfig { 26 | 27 | @Before 28 | public void init() { 29 | setup(); 30 | setupToken(); 31 | setupNotifications(); 32 | } 33 | 34 | @Test 35 | public void readAllNotificationsTest() { 36 | ResponseEntity forEntity = restTemplate.exchange("/notifications", HttpMethod.GET, 37 | new HttpEntity<>(null, requestHeaders), NotificationDTO[].class); 38 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 39 | 40 | List notificationDTOS = Arrays.asList(forEntity.getBody()); 41 | notificationRequests.forEach(request -> notificationDTOS.stream() 42 | .anyMatch(notificationDTO -> checkIfNotificationDtoAndRequestMatch(notificationDTO, request)) 43 | ); 44 | } 45 | 46 | @Test 47 | public void readOneNotificationTest() { 48 | for (int i = 0; i < notificationRequests.size(); i++) { 49 | ResponseEntity forEntity = restTemplate.exchange("/notifications/{id}", HttpMethod.GET, 50 | new HttpEntity<>(null, requestHeaders), NotificationDTO.class, i + 1); 51 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 52 | assertThat(forEntity.getBody()).isNotNull(); 53 | } 54 | } 55 | 56 | @Test 57 | public void addOneNotificationTest() { 58 | Long[] ids = {2L, 3L}; 59 | NotificationRequest oneNotificationRequestWithIds = getOneNotificationRequestWithIds(ids); 60 | ResponseEntity notificationDTOResponseEntity = restTemplate.postForEntity("/notifications", 61 | new HttpEntity<>(oneNotificationRequestWithIds, requestHeaders), NotificationDTO.class); 62 | assertThat(notificationDTOResponseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED); 63 | assertTrue(checkIfNotificationDtoAndRequestMatch(notificationDTOResponseEntity.getBody(), 64 | oneNotificationRequestWithIds)); 65 | } 66 | 67 | @Test 68 | public void updateNotificationStateTest() { 69 | ResponseEntity exchange = restTemplate.exchange("/notifications/{id}", HttpMethod.GET, 70 | new HttpEntity<>(null, requestHeaders), NotificationDTO.class, 1); 71 | 72 | assertThat(exchange.getBody().getState()).isEqualTo(State.REPORTED); 73 | 74 | ResponseEntity notificationResponseEntity = restTemplate.exchange("/notifications/{id}", 75 | HttpMethod.PUT, new HttpEntity<>(State.IN_PROGRESS.name(), requestHeaders), 76 | NotificationDTO.class, 1); 77 | 78 | assertThat(notificationResponseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 79 | assertThat(notificationResponseEntity.getBody().getState()).isEqualTo(State.IN_PROGRESS); 80 | } 81 | 82 | @Test 83 | public void shouldReturn404NotFound() { 84 | ResponseEntity forEntity = restTemplate.exchange("/notifications/{id}", HttpMethod.GET, 85 | new HttpEntity<>(null, requestHeaders), String.class, 1234); 86 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); 87 | } 88 | 89 | private boolean checkIfNotificationDtoAndRequestMatch(NotificationDTO notificationDTO, NotificationRequest request) { 90 | return notificationDTO.getDescription().equals(request.getDescription()) && 91 | notificationDTO.getInstruction().equals(request.getInstruction()) && 92 | notificationDTO.getConsignees().size() == request.getConsigneeIds().size(); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/com/herokuapp/erpmesbackend/erpmesbackend/erpmesbackend/controllers/OrderControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.controllers; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.TestConfig; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Order; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Status; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.ShopServiceRequest; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.http.HttpEntity; 12 | import org.springframework.http.HttpMethod; 13 | import org.springframework.http.HttpStatus; 14 | import org.springframework.http.ResponseEntity; 15 | import org.springframework.test.context.junit4.SpringRunner; 16 | 17 | import java.util.Arrays; 18 | import java.util.List; 19 | 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | import static org.junit.Assert.assertTrue; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | public class OrderControllerTest extends TestConfig { 26 | 27 | @Before 28 | public void init() { 29 | setup(); 30 | setupToken(); 31 | setupItemsAndSupply(); 32 | setupOrders(); 33 | } 34 | 35 | @Test 36 | public void readAllOrdersTest() { 37 | ResponseEntity forEntity = restTemplate.exchange("/orders", HttpMethod.GET, 38 | new HttpEntity<>(null, requestHeaders), Order[].class); 39 | 40 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 41 | List orders = Arrays.asList(forEntity.getBody()); 42 | orderRequests.forEach(request -> orders.stream() 43 | .anyMatch(order -> checkIfOrderAndRequestMatch(order, request)) 44 | ); 45 | } 46 | 47 | @Test 48 | public void readOneOrderTest() { 49 | for (int i = 0; i < orderRequests.size(); i++) { 50 | ResponseEntity forEntity = restTemplate.exchange("/orders/{id}", HttpMethod.GET, 51 | new HttpEntity<>(null, requestHeaders), Order.class, i + 1); 52 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 53 | assertThat(forEntity.getBody()).isNotNull(); 54 | } 55 | } 56 | 57 | @Test 58 | public void addNewOrderTest() { 59 | ShopServiceRequest oneShopServiceRequestWithItemId = getOneShopServiceRequestWithItemId(1); 60 | ResponseEntity orderResponseEntity = restTemplate.postForEntity("/orders", 61 | new HttpEntity<>(oneShopServiceRequestWithItemId, requestHeaders), Order.class); 62 | assertThat(orderResponseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED); 63 | assertTrue(checkIfOrderAndRequestMatch(orderResponseEntity.getBody(), oneShopServiceRequestWithItemId)); 64 | } 65 | 66 | @Test 67 | public void changeOrderStatusTest() { 68 | ResponseEntity exchange = restTemplate.exchange("/orders/{id}", HttpMethod.GET, 69 | new HttpEntity<>(null, requestHeaders), Order.class, 1); 70 | assertThat(exchange.getBody().getStatus()).isEqualTo(Status.WAITING_FOR_PAYMENT); 71 | 72 | ResponseEntity updateStatusResponse = restTemplate.exchange("/orders/{id}", 73 | HttpMethod.PUT, new HttpEntity<>(Status.IN_PROGRESS.name(), requestHeaders), Order.class, 74 | 1); 75 | assertThat(updateStatusResponse.getStatusCode()).isEqualTo(HttpStatus.OK); 76 | assertThat(updateStatusResponse.getBody().getStatus()).isEqualTo(Status.IN_PROGRESS); 77 | } 78 | 79 | @Test 80 | public void shouldReturn404NotFound() { 81 | ResponseEntity forEntity = restTemplate.exchange("/orders/{id}", HttpMethod.GET, 82 | new HttpEntity<>(null, requestHeaders), String.class, 1234); 83 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); 84 | } 85 | 86 | private boolean checkIfOrderAndRequestMatch(Order order, ShopServiceRequest request) { 87 | return order.getFirstName().equals(request.getFirstName()) && 88 | order.getLastName().equals(request.getLastName()) && 89 | order.getEmail().equals(request.getEmail()) && 90 | order.getPhoneNumber().equals(request.getPhoneNumber()) && 91 | order.getStreet().equals(request.getStreet()) && 92 | order.getHouseNumber().equals(request.getHouseNumber()) && 93 | order.getCity().equals(request.getCity()) && 94 | order.getPostalCode().equals(request.getPostalCode()) && 95 | order.getScheduledFor().equals(request.getScheduledFor()) && 96 | order.getDeliveryItems().size() == request.getDeliveryItemRequests().size(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/test/java/com/herokuapp/erpmesbackend/erpmesbackend/erpmesbackend/controllers/PlanningControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.controllers; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.TestConfig; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.DailyPlan; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.SpecialPlan; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.DailyPlanRequest; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.SpecialPlanRequest; 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.http.HttpEntity; 13 | import org.springframework.http.HttpMethod; 14 | import org.springframework.http.HttpStatus; 15 | import org.springframework.http.ResponseEntity; 16 | import org.springframework.test.context.junit4.SpringRunner; 17 | 18 | import java.util.Arrays; 19 | import java.util.List; 20 | 21 | import static org.assertj.core.api.Assertions.assertThat; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | public class PlanningControllerTest extends TestConfig { 26 | 27 | @Before 28 | public void init() { 29 | setup(); 30 | setupToken(); 31 | setupSpecialPlans(); 32 | } 33 | 34 | @Test 35 | public void addSpecialPlanTest() { 36 | ResponseEntity specialPlanResponseEntity = restTemplate.postForEntity("/special-plan", 37 | new HttpEntity<>(getOneSpecialPlanRequest(), requestHeaders), SpecialPlan.class); 38 | assertThat(specialPlanResponseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED); 39 | } 40 | 41 | @Test 42 | public void readAllSpecialPlans() { 43 | ResponseEntity forEntity = restTemplate.exchange("/special-plans", HttpMethod.GET, 44 | new HttpEntity<>(null, requestHeaders), SpecialPlan[].class); 45 | 46 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 47 | List specialPlans = Arrays.asList(forEntity.getBody()); 48 | specialPlanRequests.forEach(request -> specialPlans.stream() 49 | .anyMatch(specialPlan -> checkIfSpecialPlanAndRequestMatch(specialPlan, request)) 50 | ); 51 | } 52 | 53 | @Test 54 | public void readOneSpecialPlanTest() { 55 | for (int i = 0; i < specialPlanRequests.size(); i++) { 56 | ResponseEntity forEntity = restTemplate.exchange("/special-plans/{id}", HttpMethod.GET, 57 | new HttpEntity<>(null, requestHeaders), SpecialPlan.class, i + 1); 58 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 59 | assertThat(forEntity.getBody()).isNotNull(); 60 | } 61 | } 62 | 63 | @Test 64 | public void readDailyPlanTest() { 65 | ResponseEntity exchange = restTemplate.exchange("/daily-plan", HttpMethod.GET, 66 | new HttpEntity<>(null, requestHeaders), DailyPlan.class); 67 | assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); 68 | assertThat(exchange.getBody()).isNotNull(); 69 | } 70 | 71 | @Test 72 | public void updateDailyPlanTest() { 73 | DailyPlan body = restTemplate.exchange("/daily-plan", HttpMethod.GET, 74 | new HttpEntity<>(null, requestHeaders), DailyPlan.class).getBody(); 75 | DailyPlanRequest request = new DailyPlanRequest(10, 30, 10, 15); 76 | ResponseEntity exchange = restTemplate.exchange("/daily-plan", HttpMethod.PUT, 77 | new HttpEntity<>(request, requestHeaders), DailyPlan.class); 78 | assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); 79 | assertThat(exchange.getBody()).isNotEqualTo(body); 80 | } 81 | 82 | @Test 83 | public void shouldReturn404NotFound() { 84 | ResponseEntity forEntity = restTemplate.exchange("/special-plans/{id}", HttpMethod.GET, 85 | new HttpEntity<>(null, requestHeaders), String.class, 1234); 86 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); 87 | } 88 | 89 | private boolean checkIfSpecialPlanAndRequestMatch(SpecialPlan specialPlan, SpecialPlanRequest request) { 90 | return request.getDescription().equals(specialPlan.getDescription()) && 91 | request.getDay().equals(specialPlan.getDay()) && 92 | request.getEmployeesPerDay() == specialPlan.getEmployeesPerDay() && 93 | request.getOrdersPerDay() == specialPlan.getOrdersPerDay() && 94 | request.getReturnsPerDay() == specialPlan.getReturnsPerDay() && 95 | request.getComplaintsResolvedPerDay() == specialPlan.getComplaintsResolvedPerDay(); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/java/com/herokuapp/erpmesbackend/erpmesbackend/erpmesbackend/controllers/ReportsControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.controllers; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.TestConfig; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.CurrentReport; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Expense; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.ExpenseType; 7 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.ExpenseRequest; 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.http.HttpEntity; 13 | import org.springframework.http.HttpMethod; 14 | import org.springframework.http.HttpStatus; 15 | import org.springframework.http.ResponseEntity; 16 | import org.springframework.test.context.junit4.SpringRunner; 17 | 18 | import java.time.LocalDate; 19 | import java.util.List; 20 | 21 | import static org.assertj.core.api.Assertions.assertThat; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | public class ReportsControllerTest extends TestConfig { 26 | 27 | @Before 28 | public void init() { 29 | setup(); 30 | setupToken(); 31 | } 32 | 33 | @Test 34 | public void readCurrentReportTest() { 35 | ResponseEntity forEntity = restTemplate.exchange("/current-report", HttpMethod.GET, 36 | new HttpEntity<>(null, requestHeaders), CurrentReport.class); 37 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 38 | assertThat(forEntity.getBody().getStartDate().getMonth()) 39 | .isEqualTo(LocalDate.now().getMonth()); 40 | } 41 | 42 | @Test 43 | public void addIncomeTest() { 44 | CurrentReport report = restTemplate.exchange("/current-report", HttpMethod.GET, 45 | new HttpEntity<>(null, requestHeaders), CurrentReport.class).getBody(); 46 | List income = report.getIncome(); 47 | ResponseEntity currentReportResponseEntity = restTemplate.postForEntity( 48 | "/current-report/income", new HttpEntity<>(2000.00, requestHeaders), CurrentReport.class); 49 | assertThat(currentReportResponseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 50 | assertThat(currentReportResponseEntity.getBody().getIncome().size() - income.size()).isEqualTo(1); 51 | } 52 | 53 | @Test 54 | public void addExpenseTest() { 55 | CurrentReport report = restTemplate.exchange("/current-report", HttpMethod.GET, 56 | new HttpEntity<>(null, requestHeaders), CurrentReport.class).getBody(); 57 | List expenses = report.getExpenses(); 58 | ExpenseRequest request = new ExpenseRequest(ExpenseType.RENT, 5000.00); 59 | ResponseEntity currentReportResponseEntity = restTemplate.postForEntity( 60 | "/current-report/expense", new HttpEntity<>(request, requestHeaders), CurrentReport.class); 61 | assertThat(currentReportResponseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 62 | assertThat(currentReportResponseEntity.getBody().getExpenses().size() - expenses.size()).isEqualTo(1); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/com/herokuapp/erpmesbackend/erpmesbackend/erpmesbackend/controllers/ReturnControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.controllers; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.TestConfig; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.Return; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.model.ReturnStatus; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.shop.request.ShopServiceRequest; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.http.HttpEntity; 12 | import org.springframework.http.HttpMethod; 13 | import org.springframework.http.HttpStatus; 14 | import org.springframework.http.ResponseEntity; 15 | import org.springframework.test.context.junit4.SpringRunner; 16 | 17 | import java.util.Arrays; 18 | import java.util.List; 19 | 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | import static org.junit.Assert.assertTrue; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | public class ReturnControllerTest extends TestConfig { 26 | 27 | @Before 28 | public void init() { 29 | setup(); 30 | setupToken(); 31 | setupItemsAndSupply(); 32 | setupReturns(); 33 | } 34 | 35 | @Test 36 | public void readAllReturnsTest() { 37 | ResponseEntity forEntity = restTemplate.exchange("/returns", HttpMethod.GET, 38 | new HttpEntity<>(null, requestHeaders), Return[].class); 39 | 40 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 41 | List returns = Arrays.asList(forEntity.getBody()); 42 | returnRequests.forEach(request -> returns.stream() 43 | .anyMatch(ret -> checkIfReturnAndRequestMatch(ret, request)) 44 | ); 45 | } 46 | 47 | @Test 48 | public void readOneReturnTest() { 49 | for (int i = 0; i < returnRequests.size(); i++) { 50 | ResponseEntity forEntity = restTemplate.exchange("/returns/{id}", HttpMethod.GET, 51 | new HttpEntity<>(null, requestHeaders), Return.class, i + 1); 52 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 53 | assertThat(forEntity.getBody()).isNotNull(); 54 | } 55 | } 56 | 57 | @Test 58 | public void addNewReturnTest() { 59 | ShopServiceRequest oneShopServiceRequestWithItemId = getOneShopServiceRequestWithItemId(1); 60 | ResponseEntity returnResponseEntity = restTemplate.postForEntity("/returns", 61 | new HttpEntity<>(oneShopServiceRequestWithItemId, requestHeaders), Return.class); 62 | assertThat(returnResponseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED); 63 | assertTrue(checkIfReturnAndRequestMatch(returnResponseEntity.getBody(), oneShopServiceRequestWithItemId)); 64 | } 65 | 66 | @Test 67 | public void changeReturnStatusTest() { 68 | ResponseEntity exchange = restTemplate.exchange("/returns/{id}", HttpMethod.GET, 69 | new HttpEntity<>(null, requestHeaders), Return.class, 1); 70 | assertThat(exchange.getBody().getStatus()).isEqualTo(ReturnStatus.IN_PROGRESS); 71 | 72 | ResponseEntity updateStatusResponse = restTemplate.exchange("/returns/{id}", 73 | HttpMethod.PUT, new HttpEntity<>(ReturnStatus.ACCEPTED.name(), requestHeaders), Return.class, 74 | 1); 75 | assertThat(updateStatusResponse.getStatusCode()).isEqualTo(HttpStatus.OK); 76 | assertThat(updateStatusResponse.getBody().getStatus()).isEqualTo(ReturnStatus.ACCEPTED); 77 | } 78 | 79 | @Test 80 | public void shouldReturn404NotFound() { 81 | ResponseEntity forEntity = restTemplate.exchange("/returns/{id}", HttpMethod.GET, 82 | new HttpEntity<>(null, requestHeaders), String.class, 1234); 83 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); 84 | } 85 | 86 | private boolean checkIfReturnAndRequestMatch(Return ret, ShopServiceRequest request) { 87 | return ret.getFirstName().equals(request.getFirstName()) && 88 | ret.getLastName().equals(request.getLastName()) && 89 | ret.getEmail().equals(request.getEmail()) && 90 | ret.getPhoneNumber().equals(request.getPhoneNumber()) && 91 | ret.getStreet().equals(request.getStreet()) && 92 | ret.getHouseNumber().equals(request.getHouseNumber()) && 93 | ret.getCity().equals(request.getCity()) && 94 | ret.getPostalCode().equals(request.getPostalCode()) && 95 | ret.getScheduledFor().equals(request.getScheduledFor()) && 96 | ret.getDeliveryItems().size() == request.getDeliveryItemRequests().size(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/test/java/com/herokuapp/erpmesbackend/erpmesbackend/erpmesbackend/controllers/SuggestionControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.controllers; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.dto.SuggestionDTO; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.model.Phase; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.communication.request.SuggestionRequest; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.TestConfig; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.http.HttpEntity; 12 | import org.springframework.http.HttpMethod; 13 | import org.springframework.http.HttpStatus; 14 | import org.springframework.http.ResponseEntity; 15 | import org.springframework.test.context.junit4.SpringRunner; 16 | 17 | import java.util.Arrays; 18 | import java.util.List; 19 | 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | import static org.junit.Assert.assertTrue; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | public class SuggestionControllerTest extends TestConfig { 26 | 27 | @Before 28 | public void init() { 29 | setup(); 30 | setupToken(); 31 | setupSuggestions(); 32 | } 33 | 34 | @Test 35 | public void readAllSuggestionsTest() { 36 | ResponseEntity forEntity = restTemplate.exchange("/suggestions", HttpMethod.GET, 37 | new HttpEntity<>(null, requestHeaders), SuggestionDTO[].class); 38 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 39 | 40 | List suggestionDTOS = Arrays.asList(forEntity.getBody()); 41 | suggestionRequests.forEach(request -> suggestionDTOS.stream() 42 | .anyMatch(suggestionDTO -> checkIfSuggestionDtoAndRequestMatch(suggestionDTO, request)) 43 | ); 44 | } 45 | 46 | @Test 47 | public void readOneSuggestionTest() { 48 | for (int i = 0; i < suggestionRequests.size(); i++) { 49 | ResponseEntity forEntity = restTemplate.exchange("/suggestions/{id}", HttpMethod.GET, 50 | new HttpEntity<>(null, requestHeaders), SuggestionDTO.class, i + 1); 51 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 52 | assertThat(forEntity.getBody()).isNotNull(); 53 | } 54 | } 55 | 56 | @Test 57 | public void addOneSuggestionTest() { 58 | Long[] ids = {2L, 3L}; 59 | SuggestionRequest oneSuggestionRequestWithIds = getOneSuggestionRequestWithIds(ids); 60 | ResponseEntity suggestionDTOResponseEntity = restTemplate.postForEntity("/suggestions", 61 | new HttpEntity<>(oneSuggestionRequestWithIds, requestHeaders), SuggestionDTO.class); 62 | assertThat(suggestionDTOResponseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED); 63 | assertTrue(checkIfSuggestionDtoAndRequestMatch(suggestionDTOResponseEntity.getBody(), 64 | oneSuggestionRequestWithIds)); 65 | } 66 | 67 | @Test 68 | public void updateSuggestionPhaseTest() { 69 | ResponseEntity exchange = restTemplate.exchange("/suggestions/{id}", HttpMethod.GET, 70 | new HttpEntity<>(null, requestHeaders), SuggestionDTO.class, 1); 71 | 72 | assertThat(exchange.getBody().getPhase()).isEqualTo(Phase.REPORTED); 73 | 74 | ResponseEntity suggestionResponseEntity = restTemplate.exchange("/suggestions/{id}", 75 | HttpMethod.PUT, new HttpEntity<>(Phase.IN_IMPLEMENTATION.name(), requestHeaders), 76 | SuggestionDTO.class, 1); 77 | 78 | assertThat(suggestionResponseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 79 | assertThat(suggestionResponseEntity.getBody().getPhase()).isEqualTo(Phase.IN_IMPLEMENTATION); 80 | } 81 | 82 | @Test 83 | public void shouldReturn404NotFound() { 84 | ResponseEntity forEntity = restTemplate.exchange("/suggestions/{id}", HttpMethod.GET, 85 | new HttpEntity<>(null, requestHeaders), String.class, 1234); 86 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); 87 | } 88 | 89 | private boolean checkIfSuggestionDtoAndRequestMatch(SuggestionDTO suggestionDTO, SuggestionRequest request) { 90 | return suggestionDTO.getDescription().equals(request.getDescription()) && 91 | suggestionDTO.getName().equals(request.getName()) && 92 | suggestionDTO.getRecipients().size() == request.getRecipientIds().size(); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/com/herokuapp/erpmesbackend/erpmesbackend/erpmesbackend/controllers/TaskControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.controllers; 2 | 3 | import com.herokuapp.erpmesbackend.erpmesbackend.erpmesbackend.TestConfig; 4 | import com.herokuapp.erpmesbackend.erpmesbackend.production.dto.TaskDTO; 5 | import com.herokuapp.erpmesbackend.erpmesbackend.production.model.Category; 6 | import com.herokuapp.erpmesbackend.erpmesbackend.production.request.TaskRequest; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.http.HttpEntity; 12 | import org.springframework.http.HttpMethod; 13 | import org.springframework.http.HttpStatus; 14 | import org.springframework.http.ResponseEntity; 15 | import org.springframework.test.context.junit4.SpringRunner; 16 | 17 | import java.util.Arrays; 18 | import java.util.List; 19 | 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | import static org.junit.Assert.assertTrue; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | public class TaskControllerTest extends TestConfig { 26 | 27 | @Before 28 | public void init() { 29 | setup(); 30 | setupToken(); 31 | setupTasks(); 32 | } 33 | 34 | @Test 35 | public void readAllTasksTest() { 36 | ResponseEntity forEntity = restTemplate.exchange("/tasks", HttpMethod.GET, 37 | new HttpEntity<>(null, requestHeaders), TaskDTO[].class); 38 | assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 39 | 40 | List taskDTOs = Arrays.asList(forEntity.getBody()); 41 | taskRequests.forEach(request -> taskDTOs.stream() 42 | .anyMatch(taskDTO -> checkIfTaskDtoAndRequestMatch(taskDTO, request)) 43 | ); 44 | } 45 | 46 | @Test 47 | public void readOneTaskTest() { 48 | for (int i = 0; i < taskRequests.size(); i++) { 49 | ResponseEntity exchange = restTemplate.exchange("/tasks/{id}", HttpMethod.GET, 50 | new HttpEntity<>(null, requestHeaders), TaskDTO.class, i + 1); 51 | assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); 52 | assertThat(exchange.getBody()).isNotNull(); 53 | } 54 | } 55 | 56 | @Test 57 | public void addOneTaskTest() { 58 | TaskRequest oneTaskRequestWithAssigneeId = getOneTaskRequestWithAssigneeId(2); 59 | ResponseEntity taskDTOResponseEntity = restTemplate.postForEntity("/tasks", 60 | new HttpEntity<>(oneTaskRequestWithAssigneeId, requestHeaders), TaskDTO.class); 61 | assertThat(taskDTOResponseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED); 62 | assertTrue(checkIfTaskDtoAndRequestMatch(taskDTOResponseEntity.getBody(), oneTaskRequestWithAssigneeId)); 63 | } 64 | 65 | @Test 66 | public void updateTaskCategoryTest() { 67 | ResponseEntity exchange = restTemplate.exchange("/tasks/{id}", HttpMethod.GET, 68 | new HttpEntity<>(null, requestHeaders), TaskDTO.class, 1); 69 | assertThat(exchange.getBody().getCategory()).isEqualTo(Category.TO_DO); 70 | 71 | ResponseEntity taskResponseEntity = restTemplate.exchange("/tasks/{id}", 72 | HttpMethod.PUT, new HttpEntity<>(Category.DOING.name(), requestHeaders), TaskDTO.class, 1); 73 | assertThat(taskResponseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 74 | assertThat(taskResponseEntity.getBody().getCategory()).isEqualTo(Category.DOING); 75 | } 76 | 77 | @Test 78 | public void shouldReturn404NotFound() { 79 | ResponseEntity exchange = restTemplate.exchange("/tasks/{id}", HttpMethod.GET, 80 | new HttpEntity<>(null, requestHeaders), String.class, 1234); 81 | assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); 82 | } 83 | 84 | private boolean checkIfTaskDtoAndRequestMatch(TaskDTO task, TaskRequest request) { 85 | return request.getName().equals(task.getName()) && 86 | request.getPrecedingTaskIds().size() == task.getPrecedingTaskIds().size() && 87 | request.getEstimatedTime().equals(task.getEstimatedTime()); 88 | } 89 | } 90 | --------------------------------------------------------------------------------