From 26f635155d6734dd5a055fb5711c0536fb178daf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcios=20Rodrigues?= Date: Fri, 5 Jan 2024 00:34:08 -0300 Subject: [PATCH] =?UTF-8?q?[feat]=20Recorr=C3=AAncia=20de=20agendamentos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 3 + pom.xml | 2 +- .../com/nivlabs/cliniv/ApplicationMain.java | 2 - .../config/security/SecurityConfig.java | 22 +++--- .../controller/AppointmentController.java | 4 +- .../cliniv/controller/ReportController.java | 4 +- .../cliniv/controller/SupplierController.java | 18 +++++ .../nivlabs/cliniv/enums/IntervalType.java | 11 +++ .../cliniv/exception/HandlerExceptions.java | 46 +++++------ .../cliniv/models/dto/AppointmentInfoDTO.java | 76 +++++-------------- .../dto/AppointmentRecurrenceSettingsDTO.java | 49 ++++++++++++ .../cliniv/repository/AllergyRepository.java | 3 +- ...tsService.java => AppointmentService.java} | 2 +- .../CreateAppointmentBusinessHandler.java | 55 +++++++++++++- .../CreateAttendanceEventBusinessHandler.java | 25 +++--- .../CreatePrescriptionBusinessHandler.java | 29 ++++--- .../ProcessDashboardCardsBusinessHandler.java | 4 +- .../service/supplier/SupplierService.java | 10 +++ src/main/resources/application.properties | 2 + 19 files changed, 226 insertions(+), 141 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 src/main/java/br/com/nivlabs/cliniv/controller/SupplierController.java create mode 100644 src/main/java/br/com/nivlabs/cliniv/enums/IntervalType.java create mode 100644 src/main/java/br/com/nivlabs/cliniv/models/dto/AppointmentRecurrenceSettingsDTO.java rename src/main/java/br/com/nivlabs/cliniv/service/appointment/{AppointmentsService.java => AppointmentService.java} (97%) create mode 100644 src/main/java/br/com/nivlabs/cliniv/service/supplier/SupplierService.java diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 00000000..26d33521 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/pom.xml b/pom.xml index bc96ff41..5776ff60 100644 --- a/pom.xml +++ b/pom.xml @@ -12,7 +12,7 @@ br.com.nivlabs cliniv-api - v1.0.0 + v1.1.0 CliNiv API API da aplicação de CliNiv jar diff --git a/src/main/java/br/com/nivlabs/cliniv/ApplicationMain.java b/src/main/java/br/com/nivlabs/cliniv/ApplicationMain.java index 9679893e..c34f8cb9 100644 --- a/src/main/java/br/com/nivlabs/cliniv/ApplicationMain.java +++ b/src/main/java/br/com/nivlabs/cliniv/ApplicationMain.java @@ -13,8 +13,6 @@ @SpringBootApplication @EnableEurekaClient public class ApplicationMain { - - public static AppSettings SETTINGS; public static final String AMERICA_SAO_PAULO; static { diff --git a/src/main/java/br/com/nivlabs/cliniv/config/security/SecurityConfig.java b/src/main/java/br/com/nivlabs/cliniv/config/security/SecurityConfig.java index 8bb39744..9fad14e4 100644 --- a/src/main/java/br/com/nivlabs/cliniv/config/security/SecurityConfig.java +++ b/src/main/java/br/com/nivlabs/cliniv/config/security/SecurityConfig.java @@ -1,6 +1,7 @@ package br.com.nivlabs.cliniv.config.security; import java.util.Arrays; +import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -21,9 +22,8 @@ /** * Classe SecurityConfig.java - * + * * @author Vinícios Rodrigues - * * @since 15 de set de 2019 */ @Configuration @@ -41,10 +41,10 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { private UserRepository userDao; private static final String[] PUBLIC_MATCHES = {"/v2/**", - "/webjars/**", - "/swagger-ui/**", - "/api-docs/**", - "/swagger-resources/**"}; + "/webjars/**", + "/swagger-ui/**", + "/api-docs/**", + "/swagger-resources/**"}; private static final String[] PUBLIC_MATCHES_GET = {"/server/", "/server", "/actuator/**", "/status", "/dashboard"}; @@ -73,23 +73,23 @@ protected void configure(HttpSecurity http) throws Exception { /** * Configura CORS - * + * * @return CorsConfigurationSource */ @Bean public CorsConfigurationSource corsConfigurationSource() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration configCors = new CorsConfiguration().applyPermitDefaultValues(); - configCors.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "DELETE", "OPTIONS")); - configCors.setAllowedHeaders(Arrays.asList("*")); - configCors.setAllowedOrigins(Arrays.asList("*")); + configCors.setAllowedMethods(List.of("POST", "GET", "PUT", "DELETE", "OPTIONS")); + configCors.setAllowedHeaders(List.of("*")); + configCors.setAllowedOrigins(List.of("*")); source.registerCorsConfiguration("/**", configCors); return source; } /** * Define a estratégia de criptografia da API - * + * * @return BCryptPasswordEncoder */ @Bean diff --git a/src/main/java/br/com/nivlabs/cliniv/controller/AppointmentController.java b/src/main/java/br/com/nivlabs/cliniv/controller/AppointmentController.java index d47c8cac..2f0ba240 100644 --- a/src/main/java/br/com/nivlabs/cliniv/controller/AppointmentController.java +++ b/src/main/java/br/com/nivlabs/cliniv/controller/AppointmentController.java @@ -15,14 +15,14 @@ import br.com.nivlabs.cliniv.controller.filters.AppointmentFilters; import br.com.nivlabs.cliniv.models.dto.AppointmentInfoDTO; import br.com.nivlabs.cliniv.models.dto.AppointmentsResponseDTO; -import br.com.nivlabs.cliniv.service.appointment.AppointmentsService; +import br.com.nivlabs.cliniv.service.appointment.AppointmentService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; @Tag(name = "Agenda", description = "Endpoint - Operações da Agenda") @RestController @RequestMapping(value = "/appointment") -public class AppointmentController extends BaseController { +public class AppointmentController extends BaseController { @Operation(summary = "appointment-get", description = "Busca informações de agendamentos baseados num filtro") @GetMapping diff --git a/src/main/java/br/com/nivlabs/cliniv/controller/ReportController.java b/src/main/java/br/com/nivlabs/cliniv/controller/ReportController.java index 78d84f9e..512e0905 100644 --- a/src/main/java/br/com/nivlabs/cliniv/controller/ReportController.java +++ b/src/main/java/br/com/nivlabs/cliniv/controller/ReportController.java @@ -1,7 +1,5 @@ package br.com.nivlabs.cliniv.controller; -import javax.validation.constraints.NotNull; - import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; @@ -68,7 +66,7 @@ public ResponseEntity persist(@Validated @RequestBody(requi @PostMapping("/{id}") @PreAuthorize("hasAnyRole('RELATORIO_ESCRITA', 'RELATORIO_LEITURA', 'ADMIN')") public ResponseEntity generateReport(@Validated @RequestBody(required = true) ReportGenerationRequestDTO reportParam, - @NotNull @PathVariable("id") Long id) { + @PathVariable("id") Long id) { return ResponseEntity.status(HttpStatus.CREATED).body(service.generateDocumentFromReportLayout(id, reportParam)); } diff --git a/src/main/java/br/com/nivlabs/cliniv/controller/SupplierController.java b/src/main/java/br/com/nivlabs/cliniv/controller/SupplierController.java new file mode 100644 index 00000000..250a2c63 --- /dev/null +++ b/src/main/java/br/com/nivlabs/cliniv/controller/SupplierController.java @@ -0,0 +1,18 @@ +package br.com.nivlabs.cliniv.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import br.com.nivlabs.cliniv.service.supplier.SupplierService; +import io.swagger.v3.oas.annotations.tags.Tag; + +@Tag(name = "Fornecedor", description = "Endpoint - Operações com Fornecedor") +@RestController +@RequestMapping(value = "/supplier") +public class SupplierController extends BaseController { + + @Autowired + private ApplicationEventPublisher publisher; +} diff --git a/src/main/java/br/com/nivlabs/cliniv/enums/IntervalType.java b/src/main/java/br/com/nivlabs/cliniv/enums/IntervalType.java new file mode 100644 index 00000000..104f7342 --- /dev/null +++ b/src/main/java/br/com/nivlabs/cliniv/enums/IntervalType.java @@ -0,0 +1,11 @@ +package br.com.nivlabs.cliniv.enums; + +/** + * Tipos de intervalos + */ +public enum IntervalType { + DAILY, + WEEKLY, + MONTHLY, + YEARLY +} diff --git a/src/main/java/br/com/nivlabs/cliniv/exception/HandlerExceptions.java b/src/main/java/br/com/nivlabs/cliniv/exception/HandlerExceptions.java index c906868f..511cca01 100644 --- a/src/main/java/br/com/nivlabs/cliniv/exception/HandlerExceptions.java +++ b/src/main/java/br/com/nivlabs/cliniv/exception/HandlerExceptions.java @@ -1,11 +1,8 @@ package br.com.nivlabs.cliniv.exception; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - +import br.com.nivlabs.cliniv.models.exception.ErrorItem; +import com.netflix.discovery.shared.transport.TransportException; +import io.jsonwebtoken.ExpiredJwtException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataIntegrityViolationException; @@ -18,17 +15,19 @@ import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; -import br.com.nivlabs.cliniv.models.exception.ErrorItem; -import io.jsonwebtoken.ExpiredJwtException; +import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; @ControllerAdvice public class HandlerExceptions { - private Logger logger = LoggerFactory.getLogger(HandlerExceptions.class); + final private Logger logger = LoggerFactory.getLogger(HandlerExceptions.class); /** * Captura erros não esperados - * + * * @param e * @param req * @return @@ -37,14 +36,14 @@ public class HandlerExceptions { public ResponseEntity objetoNaoEncontrado(Throwable e, HttpServletRequest req) { logger.error("Falha interna não esperada :: ", e); StandardErrorSpring err = new StandardErrorSpring(System.currentTimeMillis(), - HttpStatus.INTERNAL_SERVER_ERROR.value(), "Falha interna", Arrays.asList(), e.getMessage(), + HttpStatus.INTERNAL_SERVER_ERROR.value(), "Falha interna", List.of(), e.getMessage(), req.getRequestURI()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(err); } /** * Captura erros de padrões da API - * + * * @param e * @param req * @return @@ -53,7 +52,7 @@ public ResponseEntity objetoNaoEncontrado(Throwable e, Http public ResponseEntity validationException(HttpException e, HttpServletRequest req) { logger.error("Erro da requisição", e); StandardErrorSpring err = new StandardErrorSpring(System.currentTimeMillis(), e.getStatus().value(), - "Erro da requisição", Arrays.asList(), e.getMessage(), req.getRequestURI()); + "Erro da requisição", List.of(), e.getMessage(), req.getRequestURI()); return ResponseEntity.status(e.getStatus()).body(err); } @@ -62,14 +61,14 @@ public ResponseEntity validationException(HttpException e, public ResponseEntity expiredJwtException(ExpiredJwtException e, HttpServletRequest req) { logger.error("Token expirado", e); StandardErrorSpring err = new StandardErrorSpring(System.currentTimeMillis(), HttpStatus.UNAUTHORIZED.value(), - "Token expirado", Arrays.asList(), "Token expirado!", req.getRequestURI()); + "Token expirado", List.of(), "Token expirado!", req.getRequestURI()); return ResponseEntity.status(err.getStatus()).body(err); } /** * Trata exceções de propriedades inválidas - * + * * @param e * @param req * @return @@ -79,7 +78,7 @@ public ResponseEntity objetoNaoEncontrado(HttpMessageNotRea HttpServletRequest req) { logger.error("Falha interna não esperada :: ", e); StandardErrorSpring err = new StandardErrorSpring(System.currentTimeMillis(), - HttpStatus.UNPROCESSABLE_ENTITY.value(), "Propriedade não reconhecida", Arrays.asList(), + HttpStatus.UNPROCESSABLE_ENTITY.value(), "Propriedade não reconhecida", List.of(), getPropertyMessageError(e), req.getRequestURI()); return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(err); @@ -87,7 +86,7 @@ public ResponseEntity objetoNaoEncontrado(HttpMessageNotRea /** * Captura nome da propriedade inválida do corpo da requisição - * + * * @param e * @return */ @@ -100,7 +99,7 @@ private String getPropertyMessageError(HttpMessageNotReadableException e) { /** * Erro de validação - * + * * @param e * @param req * @return @@ -118,7 +117,7 @@ public ResponseEntity methodArgumentNotValidException(Metho /** * Trata a falta de permissão - * + * * @param e * @param req * @return @@ -128,7 +127,7 @@ public ResponseEntity methodArgumentNotValidException(Acces HttpServletRequest req) { logger.error("Acesso negado :: ", e); StandardErrorSpring err = new StandardErrorSpring(System.currentTimeMillis(), HttpStatus.FORBIDDEN.value(), - "Sem permissões", Arrays.asList(), "Seu usuário não tem permissão para acessar este recurso", + "Sem permissões", List.of(), "Seu usuário não tem permissão para acessar este recurso", req.getRequestURI()); return ResponseEntity.status(HttpStatus.FORBIDDEN).body(err); @@ -139,17 +138,12 @@ public ResponseEntity dataIntegrityViolationException(DataI HttpServletRequest req) { logger.error("Violação de Integridade :: ", e); StandardErrorSpring err = new StandardErrorSpring(System.currentTimeMillis(), HttpStatus.UNPROCESSABLE_ENTITY.value(), - "Violação de Integridade", Arrays.asList(), "Violação de integridade, esta ação não pode ser concluída", + "Violação de Integridade", List.of(), "Violação de integridade, esta ação não pode ser concluída", req.getRequestURI()); return ResponseEntity.status(HttpStatus.CONFLICT).body(err); } - /** - * - * @param e - * @return - */ private List getValidations(MethodArgumentNotValidException e) { List errors = new ArrayList<>(); for (FieldError error : e.getBindingResult().getFieldErrors()) { diff --git a/src/main/java/br/com/nivlabs/cliniv/models/dto/AppointmentInfoDTO.java b/src/main/java/br/com/nivlabs/cliniv/models/dto/AppointmentInfoDTO.java index 08e1669b..a101f177 100644 --- a/src/main/java/br/com/nivlabs/cliniv/models/dto/AppointmentInfoDTO.java +++ b/src/main/java/br/com/nivlabs/cliniv/models/dto/AppointmentInfoDTO.java @@ -11,7 +11,6 @@ @Schema(description = "Informações do agendamento") public class AppointmentInfoDTO extends DataTransferObjectBase { - private static final long serialVersionUID = -7082539967186369611L; @Schema(description = "Identificador único do agendamento") private Long id; @@ -36,6 +35,8 @@ public class AppointmentInfoDTO extends DataTransferObjectBase { @Schema(description = "Situação atual do agendamento") private AppointmentStatus status = AppointmentStatus.WAITING_CONFIRMATION; + private AppointmentRecurrenceSettingsDTO repeatSettings; + public AppointmentInfoDTO() { super(); } @@ -96,68 +97,25 @@ public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } - @Override - public String toString() { - return "AppointmentInfoDTO [id=" + id + ", patient=" + patient + ", professional=" + professional + ", schedulingDateAndTime=" - + schedulingDateAndTime + ", createdAt=" + createdAt + ", annotation=" + annotation + ", status=" + status + "]"; + public AppointmentRecurrenceSettingsDTO getRepeatSettings() { + return repeatSettings; } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((annotation == null) ? 0 : annotation.hashCode()); - result = prime * result + ((createdAt == null) ? 0 : createdAt.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((patient == null) ? 0 : patient.hashCode()); - result = prime * result + ((professional == null) ? 0 : professional.hashCode()); - result = prime * result + ((schedulingDateAndTime == null) ? 0 : schedulingDateAndTime.hashCode()); - result = prime * result + ((status == null) ? 0 : status.hashCode()); - return result; + public void setRepeatSettings(AppointmentRecurrenceSettingsDTO repeatSettings) { + this.repeatSettings = repeatSettings; } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - AppointmentInfoDTO other = (AppointmentInfoDTO) obj; - if (annotation == null) { - if (other.annotation != null) - return false; - } else if (!annotation.equals(other.annotation)) - return false; - if (createdAt == null) { - if (other.createdAt != null) - return false; - } else if (!createdAt.equals(other.createdAt)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (patient == null) { - if (other.patient != null) - return false; - } else if (!patient.equals(other.patient)) - return false; - if (professional == null) { - if (other.professional != null) - return false; - } else if (!professional.equals(other.professional)) - return false; - if (schedulingDateAndTime == null) { - if (other.schedulingDateAndTime != null) - return false; - } else if (!schedulingDateAndTime.equals(other.schedulingDateAndTime)) - return false; - if (status != other.status) - return false; - return true; + public String toString() { + return "AppointmentInfoDTO{" + + "id=" + id + + ", patient=" + patient + + ", professional=" + professional + + ", schedulingDateAndTime=" + schedulingDateAndTime + + ", createdAt=" + createdAt + + ", annotation='" + annotation + '\'' + + ", status=" + status + + ", repeatSettings=" + repeatSettings + + '}'; } - } diff --git a/src/main/java/br/com/nivlabs/cliniv/models/dto/AppointmentRecurrenceSettingsDTO.java b/src/main/java/br/com/nivlabs/cliniv/models/dto/AppointmentRecurrenceSettingsDTO.java new file mode 100644 index 00000000..c284db02 --- /dev/null +++ b/src/main/java/br/com/nivlabs/cliniv/models/dto/AppointmentRecurrenceSettingsDTO.java @@ -0,0 +1,49 @@ +package br.com.nivlabs.cliniv.models.dto; + +import br.com.nivlabs.cliniv.enums.IntervalType; +import io.swagger.v3.oas.annotations.media.Schema; + +@Schema(description = "Configurações de repetição de agenda") +public class AppointmentRecurrenceSettingsDTO extends DataTransferObjectBase { + + @Schema(description = "Número de ocorrências") + private int numberOfOccurrences; + @Schema(description = "Tipo de intervalo") + private IntervalType intervalType; + + @Schema(description = "Flag para definição de apenas dias úteis") + private boolean businessDaysOnly; + + public int getNumberOfOccurrences() { + return numberOfOccurrences; + } + + public void setNumberOfOccurrences(int numberOfOccurrences) { + this.numberOfOccurrences = numberOfOccurrences; + } + + public IntervalType getIntervalType() { + return intervalType; + } + + public void setIntervalType(IntervalType intervalType) { + this.intervalType = intervalType; + } + + public boolean getBusinessDaysOnly() { + return businessDaysOnly; + } + + public void setBusinessDaysOnly(boolean businessDaysOnly) { + this.businessDaysOnly = businessDaysOnly; + } + + @Override + public String toString() { + return "AppointmentRecurrenceSettingsDTO{" + + "numberOfOccurrences=" + numberOfOccurrences + + ", interval=" + intervalType + + ", businessDaysOnly=" + businessDaysOnly + + '}'; + } +} diff --git a/src/main/java/br/com/nivlabs/cliniv/repository/AllergyRepository.java b/src/main/java/br/com/nivlabs/cliniv/repository/AllergyRepository.java index 4431b420..0c5c4822 100644 --- a/src/main/java/br/com/nivlabs/cliniv/repository/AllergyRepository.java +++ b/src/main/java/br/com/nivlabs/cliniv/repository/AllergyRepository.java @@ -6,6 +6,7 @@ import org.springframework.stereotype.Repository; import br.com.nivlabs.cliniv.models.domain.Allergy; +import br.com.nivlabs.cliniv.models.domain.AllergyID; import br.com.nivlabs.cliniv.repository.custom.allergy.AllergyRepositoryCustom; /** @@ -14,7 +15,7 @@ * */ @Repository -public interface AllergyRepository extends JpaRepository, AllergyRepositoryCustom { +public interface AllergyRepository extends JpaRepository, AllergyRepositoryCustom { public Optional findByDescriptionIgnoreCase(String description); diff --git a/src/main/java/br/com/nivlabs/cliniv/service/appointment/AppointmentsService.java b/src/main/java/br/com/nivlabs/cliniv/service/appointment/AppointmentService.java similarity index 97% rename from src/main/java/br/com/nivlabs/cliniv/service/appointment/AppointmentsService.java rename to src/main/java/br/com/nivlabs/cliniv/service/appointment/AppointmentService.java index 92d81251..d576a6c1 100644 --- a/src/main/java/br/com/nivlabs/cliniv/service/appointment/AppointmentsService.java +++ b/src/main/java/br/com/nivlabs/cliniv/service/appointment/AppointmentService.java @@ -19,7 +19,7 @@ * */ @Service -public class AppointmentsService implements BaseService { +public class AppointmentService implements BaseService { @Autowired private Logger logger; diff --git a/src/main/java/br/com/nivlabs/cliniv/service/appointment/business/CreateAppointmentBusinessHandler.java b/src/main/java/br/com/nivlabs/cliniv/service/appointment/business/CreateAppointmentBusinessHandler.java index 017ef7bf..18b08966 100644 --- a/src/main/java/br/com/nivlabs/cliniv/service/appointment/business/CreateAppointmentBusinessHandler.java +++ b/src/main/java/br/com/nivlabs/cliniv/service/appointment/business/CreateAppointmentBusinessHandler.java @@ -7,6 +7,9 @@ import br.com.nivlabs.cliniv.models.domain.Appointment; import br.com.nivlabs.cliniv.models.dto.AppointmentInfoDTO; +import java.time.DayOfWeek; +import java.time.LocalDateTime; + @Component public class CreateAppointmentBusinessHandler extends CreateOrUpdateAppointmentBaseBusinessHandler { @@ -14,14 +17,60 @@ public class CreateAppointmentBusinessHandler extends CreateOrUpdateAppointmentB private Logger logger; @Override - public AppointmentInfoDTO execute(AppointmentInfoDTO request) { + public AppointmentInfoDTO execute(final AppointmentInfoDTO request) { logger.info("Iniciando processo de criação de agendamento"); - request.setId(null); + request.setId(null); super.validateRequest(null, request); Appointment entity = convertObject(request); - entity = principalRepo.saveAndFlush(entity); + if (request.getRepeatSettings() != null && request.getRepeatSettings().getNumberOfOccurrences() > 0) { + applyRecurrence(request); + } + principalRepo.saveAndFlush(entity); request.setId(entity.getId()); return request; } + /** + * Gera agenda recursiva + * + * @param request Reqyisição de geração de agendamento + */ + private void applyRecurrence(AppointmentInfoDTO request) { + final var schedulingDate = request.getSchedulingDateAndTime(); + final var occurrenceQuantity = request.getRepeatSettings().getNumberOfOccurrences(); + final var isBusinessDaysOnly = request.getRepeatSettings().getBusinessDaysOnly(); + logger.info("Iniciando processo de geração de agendamento recorrentes..."); + logger.info("Data do primeiro agendamento :: {}", schedulingDate); + logger.info("Quantidade de ocorrências :: {}", occurrenceQuantity); + logger.info("Usa dias não úteis? :: {}", isBusinessDaysOnly ? "SIM" : "NÃO"); + LocalDateTime newDateTime = schedulingDate; + for (int i = 0; i < occurrenceQuantity; i++) { + switch (request.getRepeatSettings().getIntervalType()) { + case DAILY -> { + newDateTime = newDateTime.plusDays(1); + } + case WEEKLY -> { + newDateTime = newDateTime.plusWeeks(1); + } + case MONTHLY -> { + newDateTime = newDateTime.plusMonths(1); + } + case YEARLY -> { + newDateTime = newDateTime.plusYears(1); + } + } + if (isBusinessDaysOnly) { + if (newDateTime.getDayOfWeek() == DayOfWeek.SATURDAY) + newDateTime = newDateTime.plusDays(2); + else if (newDateTime.getDayOfWeek() == DayOfWeek.MONDAY) + newDateTime = newDateTime.plusDays(1); + } + var entity = convertObject(request); + entity.setAppointmentDateAndTime(newDateTime); + principalRepo.saveAndFlush(entity); + logger.info("Agendamento para o dia/hora :: {}", newDateTime); + } + + } + } diff --git a/src/main/java/br/com/nivlabs/cliniv/service/attendance/business/CreateAttendanceEventBusinessHandler.java b/src/main/java/br/com/nivlabs/cliniv/service/attendance/business/CreateAttendanceEventBusinessHandler.java index 42e751fb..86f834c6 100644 --- a/src/main/java/br/com/nivlabs/cliniv/service/attendance/business/CreateAttendanceEventBusinessHandler.java +++ b/src/main/java/br/com/nivlabs/cliniv/service/attendance/business/CreateAttendanceEventBusinessHandler.java @@ -36,12 +36,10 @@ import br.com.nivlabs.cliniv.util.StringUtils; /** - * * Camada de negócio relacionada à processo de criação de evento de atendimento - * + * * @author viniciosarodrigues * @since 19-09-2021 - * */ @Component public class CreateAttendanceEventBusinessHandler implements BaseBusinessHandler { @@ -54,7 +52,6 @@ public class CreateAttendanceEventBusinessHandler implements BaseBusinessHandler private AttendanceRepository attendanceRepository; @Autowired private ProcedureRepository procedureRepository; - @Autowired private DigitalDocumentService docService; @Autowired @@ -66,7 +63,7 @@ public class CreateAttendanceEventBusinessHandler implements BaseBusinessHandler /** * Cria um novo evento de atendimento - * + * * @param request Objeto de requisição de criação de novo evento de atendimento */ public void create(NewAttendanceEventDTO request) { @@ -100,10 +97,10 @@ public void create(NewAttendanceEventDTO request) { if (request.getProcedure() != null && !StringUtils.isNullOrEmpty(request.getProcedure().getDescription())) { newAttendanceEvent .setTitle(request.getProcedure().getId().toString().concat(" - ").concat(request.getProcedure().getDescription())); - } else if (request.getEventType() == EventType.REPORT && !request.getDocuments().isEmpty() && request.getDocuments().size() == 1) { + } else if (request.getEventType() == EventType.REPORT && request.getDocuments().size() == 1) { final String documentName = request.getDocuments().get(0).getName(); logger.info("É um evento de relatório e possui apenas um documento, o nome do evento será o nome do documento :: {}", - documentName); + documentName); newAttendanceEvent.setTitle(documentName); } newAttendanceEvent.setProcedure(convertProcedure(request.getProcedure())); @@ -120,9 +117,9 @@ public void create(NewAttendanceEventDTO request) { } if (request.getObservations() != null) { - var digitalDocumentoFromDocumentTemplate = reportService + var digitalDocumentFromDocumentTemplate = reportService .generateDocumentFromFormatedText(newEventId, newAttendanceEvent.getTitle(), request.getObservations()); - request.getDocuments().add(digitalDocumentoFromDocumentTemplate); + request.getDocuments().add(digitalDocumentFromDocumentTemplate); } insertDocuments(newEventId, request.getDocuments()); @@ -130,7 +127,7 @@ public void create(NewAttendanceEventDTO request) { /** * Busca o responsável pela criação de evento de atendimento - * + * * @param requestOwner Usuário da solicitação * @return Responsável logado */ @@ -146,7 +143,7 @@ private ResponsibleInfoDTO getResponsibleFromUser(UserInfoDTO requestOwner) { /** * Converte uma acomodação DTO para Entity - * + * * @param accommodation Acomodação do novo evento (DTO) * @return Acomodação do novo evento (Entity) */ @@ -163,9 +160,9 @@ private Accommodation convertAccommodation(AccommodationDTO accommodation) { /** * Insere documentos na base - * + * * @param attendanceEventId Identificador único do evento de atendimento - * @param documents Lista de documentos á serem inseridos na base + * @param documents Lista de documentos á serem inseridos na base */ private void insertDocuments(Long attendanceEventId, List documents) { logger.info("Inserindo documentos digitais..."); @@ -181,7 +178,7 @@ private void insertDocuments(Long attendanceEventId, List do /** * Converte o procedimento DTO para Entity - * + * * @param procedure Procedimento (DTO) * @return Procedimento (Entity) */ diff --git a/src/main/java/br/com/nivlabs/cliniv/service/attendance/prescription/business/CreatePrescriptionBusinessHandler.java b/src/main/java/br/com/nivlabs/cliniv/service/attendance/prescription/business/CreatePrescriptionBusinessHandler.java index 61cf37cc..ee9bb34a 100644 --- a/src/main/java/br/com/nivlabs/cliniv/service/attendance/prescription/business/CreatePrescriptionBusinessHandler.java +++ b/src/main/java/br/com/nivlabs/cliniv/service/attendance/prescription/business/CreatePrescriptionBusinessHandler.java @@ -39,12 +39,10 @@ import br.com.nivlabs.cliniv.util.SecurityContextUtil; /** - * * Componente específico para criação de prescriação * * @author viniciosarodrigues * @since 10-10-2021 - * */ @Component public class CreatePrescriptionBusinessHandler implements BaseBusinessHandler { @@ -73,7 +71,7 @@ public class CreatePrescriptionBusinessHandler implements BaseBusinessHandler { /** * Cria uma nova prescrição médica do paciente - * + * * @param request * @return */ @@ -90,9 +88,9 @@ public void createPrescription(PrescriptionInfoDTO request) { logger.info("Iniciando criação do documento digital da prescrição"); try { DigitalDocumentDTO document = reportService.genareteDocumentFromJxmlStream(request.getAttendanceId(), "Prescrição Médica", - getReportParam(insetedPrescription.getId(), user), - new ClassPathResource(REPORT_SOURCE) - .getInputStream()); + getReportParam(insetedPrescription.getId(), user), + new ClassPathResource(REPORT_SOURCE) + .getInputStream()); createDocumentEvent(request, document, responsible, medicalRecord); } catch (IOException e) { logger.error("Falha ao gerar documento de evolução", e); @@ -103,9 +101,9 @@ public void createPrescription(PrescriptionInfoDTO request) { /** * Converte itens da prescrição vindos da requisição em itens da prescrição no modelo relacional - * - * @param items Itens da prescrição - * @param medicalRecord Atendimento + * + * @param items Itens da prescrição + * @param prescription Precrição do paciente * @return Lista de itens da prescrição convertida */ private List convertItems(List items, Prescription prescription) { @@ -136,9 +134,9 @@ private List convertItems(List items, Pre /** * Insere uma prescrição médica na base de dados para controle da aplicação - * - * @param request Requisição de nova prescrição médica - * @param responsible Responsável pela solicitação + * + * @param request Requisição de nova prescrição médica + * @param responsible Responsável pela solicitação * @param medicalRecord Atendimento em questão */ private Prescription insertPrescription(PrescriptionInfoDTO request, ResponsibleInfoDTO responsible, MedicalRecordDTO medicalRecord) { @@ -178,7 +176,7 @@ private ReportParam getReportParam(Long prescriptionId, UserInfoDTO user) { /** * Cria um evento de documento para a prescrição - * + * * @param request * @param document * @param requestOwner @@ -189,9 +187,8 @@ private void createDocumentEvent(PrescriptionInfoDTO request, DigitalDocumentDTO NewAttendanceEventDTO event = new NewAttendanceEventDTO(); event.setEventType(EventType.PRESCRIPTION); event.setAttendanceId(request.getAttendanceId()); - event.setDocuments(Arrays.asList(document)); event.setEventDateTime(LocalDateTime.now()); - event.setObservations("Criação da prescrição"); + event.getDocuments().add(document); event.setResponsible(requestOwner); event.setAccommodation(medicalRecord.getLastAccommodation()); logger.info("Evento processado, inserindo evento na base de dados..."); @@ -202,7 +199,7 @@ private void createDocumentEvent(PrescriptionInfoDTO request, DigitalDocumentDTO /** * Busca o responsável pela requisição da prescrição baseado no usuário - * + * * @param requestOwner * @return */ diff --git a/src/main/java/br/com/nivlabs/cliniv/service/dashboard/business/ProcessDashboardCardsBusinessHandler.java b/src/main/java/br/com/nivlabs/cliniv/service/dashboard/business/ProcessDashboardCardsBusinessHandler.java index 54b0502c..63361bb9 100644 --- a/src/main/java/br/com/nivlabs/cliniv/service/dashboard/business/ProcessDashboardCardsBusinessHandler.java +++ b/src/main/java/br/com/nivlabs/cliniv/service/dashboard/business/ProcessDashboardCardsBusinessHandler.java @@ -21,7 +21,7 @@ import br.com.nivlabs.cliniv.repository.ResponsibleRepository; import br.com.nivlabs.cliniv.repository.UserRepository; import br.com.nivlabs.cliniv.service.BaseBusinessHandler; -import br.com.nivlabs.cliniv.service.appointment.AppointmentsService; +import br.com.nivlabs.cliniv.service.appointment.AppointmentService; import br.com.nivlabs.cliniv.service.sticker.StickerService; import br.com.nivlabs.cliniv.util.SecurityContextUtil; @@ -46,7 +46,7 @@ public class ProcessDashboardCardsBusinessHandler implements BaseBusinessHandler @Autowired private ResponsibleRepository responsibleRepo; @Autowired - private AppointmentsService appointmentsService; + private AppointmentService appointmentsService; @Autowired private StickerService stickerService; diff --git a/src/main/java/br/com/nivlabs/cliniv/service/supplier/SupplierService.java b/src/main/java/br/com/nivlabs/cliniv/service/supplier/SupplierService.java new file mode 100644 index 00000000..92bc4e24 --- /dev/null +++ b/src/main/java/br/com/nivlabs/cliniv/service/supplier/SupplierService.java @@ -0,0 +1,10 @@ +package br.com.nivlabs.cliniv.service.supplier; + +import org.springframework.stereotype.Service; + +import br.com.nivlabs.cliniv.service.BaseService; + +@Service +public class SupplierService implements BaseService { + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8ef4ffd5..c46d247c 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -50,6 +50,8 @@ spring.jackson.deserialization.fail-on-unknown-properties=true spring.jackson.date-format=yyyy-MM-dd spring.jackson.default-property-inclusion=NON_NULL + +nivlabs.application.zoneId=America/Sao_Paulo nivlabs.api.baseUrl=https://cliniv.cloud nivlabs.ui.baseUrl=https://cliniv.nivlabs.com.br swagger.owner.url=http://www.nivlabs.com.br/