From 1cff4f067c9e4c760c00accc348164d9e7a80462 Mon Sep 17 00:00:00 2001 From: davdarras Date: Mon, 22 Jul 2024 11:28:07 +0200 Subject: [PATCH 01/48] feat: change survey unit communication request - change the communication request for a survey unit - divide the survey unit dto to have a more adapted survey unit update dto including communication request - simplify ExceptionControllerAdvice handling for test purposes --- .../api/controller/SurveyUnitController.java | 14 +- .../insee/pearljam/api/domain/SurveyUnit.java | 27 ++-- .../dto/surveyunit/SurveyUnitCampaignDto.java | 4 +- .../dto/surveyunit/SurveyUnitDetailDto.java | 21 +-- .../dto/surveyunit/SurveyUnitOkNokDto.java | 14 +- ...o.java => SurveyUnitOkNokResponseDto.java} | 8 +- .../api/service/SurveyUnitService.java | 13 +- .../api/service/SurveyUnitUpdateService.java | 6 +- .../service/impl/SurveyUnitServiceImpl.java | 94 ++++++-------- .../impl/SurveyUnitUpdateServiceImpl.java | 20 ++- .../api/surveyunit/dto/CommentDto.java | 36 +++++- .../dto/CommunicationRequestCreateDto.java | 39 ++++++ .../dto/CommunicationRequestDto.java | 34 ----- .../dto/CommunicationRequestResponseDto.java | 42 ++++++ .../dto/CommunicationRequestStatusDto.java | 25 +++- .../api/surveyunit/dto/IdentificationDto.java | 3 + .../surveyunit/dto/SurveyUnitUpdateDto.java | 41 ++++++ .../web/exception/ApiExceptionComponent.java | 2 - .../exception/ExceptionControllerAdvice.java | 7 +- .../communication/CommunicationRequest.java | 20 ++- ....java => CommunicationRequestEmitter.java} | 2 +- .../CommunicationRequestStatus.java | 9 ++ .../infrastructure/mail/RestMailSender.java | 2 +- .../mail/exception/SendMailException.java | 4 +- .../surveyunit/entity/CommentDB.java | 13 ++ .../entity/CommunicationRequestDB.java | 33 +++-- .../540_alter_communication_request.xml | 20 +++ src/main/resources/db/master.xml | 3 + .../controller/dummy/MailFakeSender.java | 2 +- .../controller/CommentControllerTest.java | 8 +- .../controller/SurveyUnitControllerTest.java | 60 ++++----- .../dummy/SurveyUnitFakeService.java | 9 +- .../dto/SurveyUnitDetailDtoTest.java | 24 ++-- .../pearljam/api/utils/MockMvcTestUtils.java | 3 +- .../model/CommunicationRequestTest.java | 31 +++++ .../SurveyUnitUpdateServiceImplTest.java | 122 +++++++----------- .../entity/CommunicationRequestDBTest.java | 26 ++-- .../CommunicationRequestStatusDBTest.java | 6 +- 38 files changed, 510 insertions(+), 337 deletions(-) rename src/main/java/fr/insee/pearljam/api/dto/surveyunit/{SurveyUnitResponseDto.java => SurveyUnitOkNokResponseDto.java} (74%) create mode 100644 src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java delete mode 100644 src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitUpdateDto.java rename src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/{CommunicationRequestEmiter.java => CommunicationRequestEmitter.java} (68%) create mode 100644 src/main/resources/db/changelog/540_alter_communication_request.xml create mode 100644 src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java diff --git a/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java b/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java index ca482a52..89388001 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java @@ -4,6 +4,8 @@ import java.util.Optional; import java.util.Set; +import fr.insee.pearljam.api.dto.surveyunit.*; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.domain.exception.EntityNotFoundException; import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; import jakarta.servlet.http.HttpServletRequest; @@ -29,12 +31,6 @@ import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.dto.state.StateDto; import fr.insee.pearljam.api.dto.state.SurveyUnitStatesDto; -import fr.insee.pearljam.api.dto.surveyunit.HabilitationDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitCampaignDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitContextDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDetailDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitInterviewerLinkDto; import fr.insee.pearljam.api.exception.NotFoundException; import fr.insee.pearljam.api.exception.SurveyUnitException; import fr.insee.pearljam.api.service.SurveyUnitService; @@ -165,11 +161,11 @@ public ResponseEntity getSurveyUnitById(@PathVariable(value @Operation(summary = "Update the Survey Unit") @PutMapping(path = "/survey-unit/{id}") public SurveyUnitDetailDto updateSurveyUnit( - @Valid @NotNull @RequestBody SurveyUnitDetailDto surveyUnitDetails, + @Valid @NotNull @RequestBody SurveyUnitUpdateDto surveyUnitUpdateDto, @PathVariable(value = "id") String id) throws EntityNotFoundException { String userId = authenticatedUserService.getCurrentUserId(); - SurveyUnitDetailDto updatedSurveyUnit = surveyUnitService.updateSurveyUnitDetail(userId, - id, surveyUnitDetails); + SurveyUnitDetailDto updatedSurveyUnit = surveyUnitService.updateSurveyUnit(userId, + id, surveyUnitUpdateDto); log.info("SurveyUnit {} updated", id); return updatedSurveyUnit; } diff --git a/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java b/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java index 01d5afe5..08b41689 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java +++ b/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java @@ -8,7 +8,6 @@ import fr.insee.pearljam.domain.surveyunit.model.Identification; import fr.insee.pearljam.infrastructure.surveyunit.entity.IdentificationDB; import fr.insee.pearljam.api.surveyunit.dto.CommentDto; -import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestDto; import fr.insee.pearljam.domain.surveyunit.model.Comment; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommentDB; @@ -223,11 +222,6 @@ public void updateIdentification(Identification identification) { identificationDB.update(identification); } - public Set getDomainComments() { - return comments.stream().map(CommentDB::toModel) - .collect(Collectors.toSet()); - } - /** * update a list of comments for a survey unit * @param commentsToUpdate the comment to update @@ -250,16 +244,27 @@ public void updateComments(Set commentsToUpdate) { } /** - * update a list of communication requests for a survey unit - * @param communicationRequestsToUpdate the communication requests to update + * add a list of communication requests for a survey unit + * @param communicationRequestsToCreate the communication requests to add */ - public void updateCommunicationRequests(List communicationRequestsToUpdate) { - Set newCommunicationsRequests = communicationRequestsToUpdate.stream() - .filter(newCommunicationRequest -> newCommunicationRequest.id() == null) + public void addCommunicationRequests(List communicationRequestsToCreate) { + Set newCommunicationsRequests = communicationRequestsToCreate.stream() .map(newCommunicationRequest -> CommunicationRequestDB.fromModel(newCommunicationRequest, this)) .collect(Collectors.toSet()); this.getCommunicationRequests() .addAll(newCommunicationsRequests); } + + public Set getModelComments() { + return CommentDB.toModel(this.getComments()); + } + + public Identification getModelIdentification() { + return IdentificationDB.toModel(this.getIdentification()); + } + + public Set getModelCommunicationRequests() { + return CommunicationRequestDB.toModel(this.getCommunicationRequests()); + } } diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitCampaignDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitCampaignDto.java index ee8cd31b..9f46de37 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitCampaignDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitCampaignDto.java @@ -100,9 +100,7 @@ public SurveyUnitCampaignDto(SurveyUnit su) { this.state = currentState == null ? null : currentState.getType(); this.campaign = su.getCampaign().getLabel(); this.interviewer = su.getInterviewer() != null ? new InterviewerDto(su.getInterviewer()) : null; - this.comments = su.getDomainComments().stream() - .map(CommentDto::fromModel) - .toList(); + this.comments = CommentDto.fromModel(su.getModelComments()); if (su.getContactOucome() != null) { this.contactOutcome = new ContactOutcomeDto(su.getContactOucome()); } diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java index 46a3fee4..29c82cba 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java @@ -3,10 +3,9 @@ import java.util.Comparator; import java.util.List; -import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; +import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestResponseDto; import jakarta.validation.Valid; import lombok.Data; -import fr.insee.pearljam.infrastructure.surveyunit.entity.IdentificationDB; import com.fasterxml.jackson.annotation.JsonInclude; @@ -15,7 +14,6 @@ import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.api.dto.address.AddressDto; import fr.insee.pearljam.api.surveyunit.dto.CommentDto; -import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestDto; import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; @@ -40,7 +38,7 @@ public class SurveyUnitDetailDto { private ContactOutcomeDto contactOutcome; private IdentificationDto identification; @Valid - private List communicationRequests; + private List communicationRequests; public SurveyUnitDetailDto() { } @@ -56,9 +54,7 @@ public SurveyUnitDetailDto(SurveyUnit surveyUnit) { if (surveyUnit.getSampleIdentifier() != null) { this.sampleIdentifiers = new SampleIdentifiersDto(surveyUnit.getSampleIdentifier()); } - this.comments = surveyUnit.getDomainComments().stream() - .map(CommentDto::fromModel) - .toList(); + this.comments = CommentDto.fromModel(surveyUnit.getModelComments()); this.contactAttempts = surveyUnit.getContactAttempts().stream().map(ContactAttemptDto::new) .toList(); if (surveyUnit.getContactOucome() != null) { @@ -69,13 +65,10 @@ public SurveyUnitDetailDto(SurveyUnit surveyUnit) { .filter(s -> BussinessRules.stateCanBeSeenByInterviewerBussinessRules(s.getType())) .map(StateDto::new) .toList(); - if (surveyUnit.getIdentification() != null) { - this.identification = IdentificationDto.fromModel(IdentificationDB.toModel(surveyUnit.getIdentification())); - } + + this.identification = IdentificationDto.fromModel(surveyUnit.getModelIdentification()); + this.move = surveyUnit.getMove(); - this.communicationRequests = surveyUnit.getCommunicationRequests().stream() - .map(CommunicationRequestDB::toModel) - .map(CommunicationRequestDto::fromModel) - .toList(); + this.communicationRequests = CommunicationRequestResponseDto.fromModel(surveyUnit.getModelCommunicationRequests()); } } diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitOkNokDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitOkNokDto.java index 1c5759b8..79e22027 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitOkNokDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitOkNokDto.java @@ -7,10 +7,10 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class SurveyUnitOkNokDto { - List surveyUnitOK; - List surveyUnitNOK; + List surveyUnitOK; + List surveyUnitNOK; - public SurveyUnitOkNokDto(List surveyUnitOK, List surveyUnitNOK) { + public SurveyUnitOkNokDto(List surveyUnitOK, List surveyUnitNOK) { super(); this.surveyUnitOK = surveyUnitOK; this.surveyUnitNOK = surveyUnitNOK; @@ -25,25 +25,25 @@ public SurveyUnitOkNokDto() { /** * @return the surveyUnitOK */ - public List getSurveyUnitOK() { + public List getSurveyUnitOK() { return surveyUnitOK; } /** * @param surveyUnitOK the surveyUnitOK to set */ - public void setSurveyUnitOK(List surveyUnitOK) { + public void setSurveyUnitOK(List surveyUnitOK) { this.surveyUnitOK = surveyUnitOK; } /** * @return the surveyUnitNOK */ - public List getSurveyUnitNOK() { + public List getSurveyUnitNOK() { return surveyUnitNOK; } /** * @param surveyUnitNOK the surveyUnitNOK to set */ - public void setSurveyUnitNOK(List surveyUnitNOK) { + public void setSurveyUnitNOK(List surveyUnitNOK) { this.surveyUnitNOK = surveyUnitNOK; } diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitResponseDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitOkNokResponseDto.java similarity index 74% rename from src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitResponseDto.java rename to src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitOkNokResponseDto.java index 52ffa771..61f89e13 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitOkNokResponseDto.java @@ -6,20 +6,20 @@ import fr.insee.pearljam.api.dto.statedata.StateDataDto; @JsonInclude(JsonInclude.Include.NON_NULL) -public class SurveyUnitResponseDto { +public class SurveyUnitOkNokResponseDto { String id; private StateDataDto stateData; - public SurveyUnitResponseDto() { + public SurveyUnitOkNokResponseDto() { super(); } - public SurveyUnitResponseDto(String id, StateDataDto stateData) { + public SurveyUnitOkNokResponseDto(String id, StateDataDto stateData) { super(); this.id = id; this.stateData = stateData; } - public SurveyUnitResponseDto(String id) { + public SurveyUnitOkNokResponseDto(String id) { super(); this.id = id; } diff --git a/src/main/java/fr/insee/pearljam/api/service/SurveyUnitService.java b/src/main/java/fr/insee/pearljam/api/service/SurveyUnitService.java index e99b544c..7b9474c7 100644 --- a/src/main/java/fr/insee/pearljam/api/service/SurveyUnitService.java +++ b/src/main/java/fr/insee/pearljam/api/service/SurveyUnitService.java @@ -4,6 +4,8 @@ import java.util.Optional; import java.util.Set; +import fr.insee.pearljam.api.dto.surveyunit.*; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.domain.exception.PersonNotFoundException; import fr.insee.pearljam.domain.exception.SurveyUnitNotFoundException; import jakarta.servlet.http.HttpServletRequest; @@ -13,11 +15,6 @@ import org.springframework.http.HttpStatus; import fr.insee.pearljam.api.dto.state.StateDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitCampaignDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitContextDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDetailDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitInterviewerLinkDto; import fr.insee.pearljam.api.exception.NotFoundException; import fr.insee.pearljam.api.exception.SurveyUnitException; @@ -54,11 +51,11 @@ public interface SurveyUnitService { * * @param userId * @param id - * @param surveyUnitDetailDto + * @param surveyUnitUpdateDto * @return {@link SurveyUnitDetailDto} */ - SurveyUnitDetailDto updateSurveyUnitDetail(String userId, String id, - SurveyUnitDetailDto surveyUnitDetailDto) throws SurveyUnitNotFoundException, PersonNotFoundException; + SurveyUnitDetailDto updateSurveyUnit(String userId, String id, + SurveyUnitUpdateDto surveyUnitUpdateDto) throws SurveyUnitNotFoundException, PersonNotFoundException; /** * @param userId diff --git a/src/main/java/fr/insee/pearljam/api/service/SurveyUnitUpdateService.java b/src/main/java/fr/insee/pearljam/api/service/SurveyUnitUpdateService.java index 1ca571d4..027a9753 100644 --- a/src/main/java/fr/insee/pearljam/api/service/SurveyUnitUpdateService.java +++ b/src/main/java/fr/insee/pearljam/api/service/SurveyUnitUpdateService.java @@ -1,7 +1,7 @@ package fr.insee.pearljam.api.service; import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDetailDto; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; /** * Temporary service used for the full app refactoring to update survey unit infos @@ -10,7 +10,7 @@ public interface SurveyUnitUpdateService { /** * Update the SurveyUnit with details from Dto * @param surveyUnit existing survey unit to update - * @param surveyUnitDetailDto details to update + * @param surveyUnitUpdateDto details to update */ - void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitDetailDto surveyUnitDetailDto); + void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto); } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java index 8e098bdd..07781571 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java @@ -11,12 +11,11 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import fr.insee.pearljam.domain.surveyunit.model.Identification; -import fr.insee.pearljam.domain.surveyunit.model.Comment; +import fr.insee.pearljam.api.dto.surveyunit.*; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.domain.exception.PersonNotFoundException; import fr.insee.pearljam.domain.exception.SurveyUnitNotFoundException; import fr.insee.pearljam.domain.surveyunit.model.IdentificationState; -import fr.insee.pearljam.infrastructure.surveyunit.entity.IdentificationDB; import fr.insee.pearljam.api.service.SurveyUnitUpdateService; import jakarta.servlet.http.HttpServletRequest; @@ -33,16 +32,9 @@ import fr.insee.pearljam.api.bussinessrules.BussinessRules; import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; -import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; import fr.insee.pearljam.api.dto.person.PersonDto; import fr.insee.pearljam.api.dto.state.StateDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitCampaignDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitContextDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDetailDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitInterviewerLinkDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitOkNokDto; import fr.insee.pearljam.api.exception.BadRequestException; import fr.insee.pearljam.api.exception.NotFoundException; import fr.insee.pearljam.api.exception.SurveyUnitException; @@ -153,8 +145,8 @@ public boolean canBeSeenByInterviewer(String suId) { } @Transactional - public SurveyUnitDetailDto updateSurveyUnitDetail(String userId, String id, - SurveyUnitDetailDto surveyUnitDetailDto) throws SurveyUnitNotFoundException, PersonNotFoundException { + public SurveyUnitDetailDto updateSurveyUnit(String userId, String id, + SurveyUnitUpdateDto surveyUnitUpdate) throws SurveyUnitNotFoundException, PersonNotFoundException { log.info("Update Survey Unit {}", id); Optional surveyUnitOpt; @@ -164,29 +156,29 @@ public SurveyUnitDetailDto updateSurveyUnitDetail(String userId, String id, surveyUnitOpt = surveyUnitRepository.findByIdAndInterviewerIdIgnoreCase(id, userId); } SurveyUnit surveyUnit = surveyUnitOpt.orElseThrow(SurveyUnitNotFoundException::new); - surveyUnit.setMove(surveyUnitDetailDto.getMove()); - updateAddress(surveyUnit, surveyUnitDetailDto); - updatePersons(surveyUnitDetailDto); + surveyUnit.setMove(surveyUnitUpdate.move()); + updateAddress(surveyUnit, surveyUnitUpdate); + updatePersons(surveyUnitUpdate); - updateStates(surveyUnit, surveyUnitDetailDto); - updateContactAttempt(surveyUnit, surveyUnitDetailDto); - updateContactOutcome(surveyUnit, surveyUnitDetailDto); + updateStates(surveyUnit, surveyUnitUpdate); + updateContactAttempt(surveyUnit, surveyUnitUpdate); + updateContactOutcome(surveyUnit, surveyUnitUpdate); - surveyUnitUpdateService.updateSurveyUnitInfos(surveyUnit, surveyUnitDetailDto); + surveyUnitUpdateService.updateSurveyUnitInfos(surveyUnit, surveyUnitUpdate); surveyUnitRepository.save(surveyUnit); log.info("Survey Unit {} - update complete", id); return new SurveyUnitDetailDto(surveyUnitRepository.findById(id).get()); } - private void updateContactOutcome(SurveyUnit surveyUnit, SurveyUnitDetailDto surveyUnitDetailDto) { - if (surveyUnitDetailDto.getContactOutcome() != null) { + private void updateContactOutcome(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto) { + if (surveyUnitUpdateDto.contactOutcome() != null) { ContactOutcome contactOutcome = contactOutcomeRepository.findBySurveyUnit(surveyUnit) .orElseGet(ContactOutcome::new); - contactOutcome.setDate(surveyUnitDetailDto.getContactOutcome().getDate()); - contactOutcome.setType(surveyUnitDetailDto.getContactOutcome().getType()); + contactOutcome.setDate(surveyUnitUpdateDto.contactOutcome().getDate()); + contactOutcome.setType(surveyUnitUpdateDto.contactOutcome().getType()); contactOutcome.setTotalNumberOfContactAttempts( - surveyUnitDetailDto.getContactOutcome().getTotalNumberOfContactAttempts()); + surveyUnitUpdateDto.contactOutcome().getTotalNumberOfContactAttempts()); contactOutcome.setSurveyUnit(surveyUnit); surveyUnit.setContactOucome(contactOutcome); contactOutcomeRepository.save(contactOutcome); @@ -194,20 +186,20 @@ private void updateContactOutcome(SurveyUnit surveyUnit, SurveyUnitDetailDto sur log.info("Survey-unit {} - Contact outcome updated", surveyUnit.getId()); } - private void updateContactAttempt(SurveyUnit surveyUnit, SurveyUnitDetailDto surveyUnitDetailDto) { - if (surveyUnitDetailDto.getContactAttempts() != null) { + private void updateContactAttempt(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto) { + if (surveyUnitUpdateDto.contactAttempts() != null) { Set contactAttemps = surveyUnit.getContactAttempts(); contactAttemps.clear(); - Set newContactAttempts = surveyUnitDetailDto.getContactAttempts().stream() + Set newContactAttempts = surveyUnitUpdateDto.contactAttempts().stream() .map(dto -> new ContactAttempt(dto, surveyUnit)).collect(Collectors.toSet()); contactAttemps.addAll(newContactAttempts); log.info("Survey-unit {} - Contact attempts updated", surveyUnit.getId()); } } - private void updateStates(SurveyUnit surveyUnit, SurveyUnitDetailDto surveyUnitDetailDto) { - if (surveyUnitDetailDto.getStates() != null) { - surveyUnitDetailDto.getStates().stream() + private void updateStates(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto) { + if (surveyUnitUpdateDto.states() != null) { + surveyUnitUpdateDto.states().stream() .filter(s -> s.getId() == null || !stateRepository.existsById(s.getId())) .forEach(s -> stateRepository.save(new State(s.getDate(), surveyUnit, s.getType()))); } @@ -238,11 +230,11 @@ private void addStateAuto(SurveyUnit surveyUnit) { } } - private void updatePersons(SurveyUnitDetailDto surveyUnitDetailDto) throws PersonNotFoundException { - if (surveyUnitDetailDto.getPersons() == null) { + private void updatePersons(SurveyUnitUpdateDto surveyUnitUpdateDto) throws PersonNotFoundException { + if (surveyUnitUpdateDto.persons() == null) { return; } - for (PersonDto personDto : surveyUnitDetailDto.getPersons()) { + for (PersonDto personDto : surveyUnitUpdateDto.persons()) { Person pers = personRepository.findById(personDto.getId()).orElseThrow(PersonNotFoundException::new); updatePerson(personDto, pers); } @@ -278,27 +270,27 @@ private void updatePerson(PersonDto person, Person pers) { } } - private void updateAddress(SurveyUnit surveyUnit, SurveyUnitDetailDto surveyUnitDetailDto) { - if (surveyUnitDetailDto.getAddress() != null) { + private void updateAddress(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto) { + if (surveyUnitUpdateDto.address() != null) { InseeAddress inseeAddress; Optional optionalInseeAddress = addressRepository.findById(surveyUnit.getAddress().getId()); - if (!optionalInseeAddress.isPresent()) { - inseeAddress = new InseeAddress(surveyUnitDetailDto.getAddress()); + if (optionalInseeAddress.isEmpty()) { + inseeAddress = new InseeAddress(surveyUnitUpdateDto.address()); } else { inseeAddress = optionalInseeAddress.get(); - inseeAddress.setL1(surveyUnitDetailDto.getAddress().getL1()); - inseeAddress.setL2(surveyUnitDetailDto.getAddress().getL2()); - inseeAddress.setL3(surveyUnitDetailDto.getAddress().getL3()); - inseeAddress.setL4(surveyUnitDetailDto.getAddress().getL4()); - inseeAddress.setL5(surveyUnitDetailDto.getAddress().getL5()); - inseeAddress.setL6(surveyUnitDetailDto.getAddress().getL6()); - inseeAddress.setL7(surveyUnitDetailDto.getAddress().getL7()); - inseeAddress.setBuilding(surveyUnitDetailDto.getAddress().getBuilding()); - inseeAddress.setFloor(surveyUnitDetailDto.getAddress().getFloor()); - inseeAddress.setDoor(surveyUnitDetailDto.getAddress().getDoor()); - inseeAddress.setStaircase(surveyUnitDetailDto.getAddress().getStaircase()); - inseeAddress.setElevator(surveyUnitDetailDto.getAddress().getElevator()); - inseeAddress.setCityPriorityDistrict(surveyUnitDetailDto.getAddress().getCityPriorityDistrict()); + inseeAddress.setL1(surveyUnitUpdateDto.address().getL1()); + inseeAddress.setL2(surveyUnitUpdateDto.address().getL2()); + inseeAddress.setL3(surveyUnitUpdateDto.address().getL3()); + inseeAddress.setL4(surveyUnitUpdateDto.address().getL4()); + inseeAddress.setL5(surveyUnitUpdateDto.address().getL5()); + inseeAddress.setL6(surveyUnitUpdateDto.address().getL6()); + inseeAddress.setL7(surveyUnitUpdateDto.address().getL7()); + inseeAddress.setBuilding(surveyUnitUpdateDto.address().getBuilding()); + inseeAddress.setFloor(surveyUnitUpdateDto.address().getFloor()); + inseeAddress.setDoor(surveyUnitUpdateDto.address().getDoor()); + inseeAddress.setStaircase(surveyUnitUpdateDto.address().getStaircase()); + inseeAddress.setElevator(surveyUnitUpdateDto.address().getElevator()); + inseeAddress.setCityPriorityDistrict(surveyUnitUpdateDto.address().getCityPriorityDistrict()); } // Update Address addressRepository.save(inseeAddress); @@ -372,7 +364,7 @@ public List getClosableSurveyUnits(HttpServletRequest req return suToCheck.stream().map(su -> { SurveyUnitCampaignDto sudto = new SurveyUnitCampaignDto(su); - IdentificationState identificationResult = IdentificationState.getState(IdentificationDB.toModel(su.getIdentification())); + IdentificationState identificationResult = IdentificationState.getState(su.getModelIdentification()); sudto.setIdentificationState(identificationResult); String questionnaireState = Optional.ofNullable(map.get(su.getId())).orElse(Constants.UNAVAILABLE); sudto.setQuestionnaireState(questionnaireState); diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java index 914a1314..0a151e90 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java @@ -1,10 +1,10 @@ package fr.insee.pearljam.api.service.impl; import fr.insee.pearljam.api.domain.*; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDetailDto; import fr.insee.pearljam.api.surveyunit.dto.CommentDto; -import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestDto; +import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestCreateDto; import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.domain.surveyunit.model.Comment; import fr.insee.pearljam.domain.surveyunit.model.Identification; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; @@ -24,22 +24,20 @@ public class SurveyUnitUpdateServiceImpl implements SurveyUnitUpdateService { @Transactional @Override - public void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitDetailDto surveyUnitDetailDto) { - if(surveyUnitDetailDto.getComments() != null) { - Set commentsToUpdate = surveyUnitDetailDto.getComments().stream() + public void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto) { + if(surveyUnitUpdateDto.comments() != null) { + Set commentsToUpdate = surveyUnitUpdateDto.comments().stream() .map(commentDto -> CommentDto.toModel(surveyUnit.getId(), commentDto)) .collect(Collectors.toSet()); surveyUnit.updateComments(commentsToUpdate); } - if(surveyUnitDetailDto.getCommunicationRequests() != null) { - List communicationRequests = surveyUnitDetailDto.getCommunicationRequests().stream() - .map(CommunicationRequestDto::toModel) - .toList(); - surveyUnit.updateCommunicationRequests(communicationRequests); + if(surveyUnitUpdateDto.communicationRequests() != null) { + List communicationRequests = CommunicationRequestCreateDto.toModel(surveyUnitUpdateDto.communicationRequests()); + surveyUnit.addCommunicationRequests(communicationRequests); } - Identification identification = IdentificationDto.toModel(surveyUnitDetailDto.getIdentification()); + Identification identification = IdentificationDto.toModel(surveyUnitUpdateDto.identification()); surveyUnit.updateIdentification(identification); } } diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommentDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommentDto.java index df820183..814f2f01 100644 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommentDto.java +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommentDto.java @@ -5,6 +5,15 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; +import java.util.List; +import java.util.Set; + +/** + * Record representing a CommentDto + * + * @param type The type of the comment. + * @param value The value of the comment. + */ public record CommentDto( @NotNull CommentType type, @@ -12,11 +21,36 @@ public record CommentDto( @Size(max = 999) String value) { + /** + * Converts a CommentDto to a Comment model. + * + * @param surveyUnitId The ID of the survey unit associated with the comment. + * @param commentDto The CommentDto to convert. + * @return A new Comment model instance. + */ public static Comment toModel(String surveyUnitId, CommentDto commentDto) { return new Comment(commentDto.type(), commentDto.value(), surveyUnitId); } + /** + * Converts a Comment model to a CommentDto. + * + * @param comment The Comment model to convert. + * @return A new CommentDto instance. + */ public static CommentDto fromModel(Comment comment) { return new CommentDto(comment.type(), comment.value()); } -} + + /** + * Converts a set of Comment models to a list of CommentDto. + * + * @param comments The set of Comment models to convert. + * @return A list of CommentDto instances. + */ + public static List fromModel(Set comments) { + return comments.stream() + .map(CommentDto::fromModel) + .toList(); + } +} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java new file mode 100644 index 00000000..68c4de22 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java @@ -0,0 +1,39 @@ +package fr.insee.pearljam.api.surveyunit.dto; + +import fr.insee.pearljam.domain.surveyunit.model.communication.*; +import jakarta.validation.constraints.NotNull; + +import java.util.List; + +/** + * DTO for creating a communication request. + * + *

This class represents the data required to create a + * communication request, including the configuration ID, the + * creationTimestamp, and the reason for the request.

+ * + * @param communicationTemplateId the configuration ID, must not be null + * @param creationTimestamp the creationTimestamp of the request, must not be null + * @param reason the reason for the communication request, must not be null + */ +public record CommunicationRequestCreateDto( + @NotNull + Long communicationTemplateId, + @NotNull + Long creationTimestamp, + @NotNull + CommunicationRequestReason reason) { + + /** + * Converts a list of communication request DTOs into a list of communication request models. + * + * @param requests the list of communication request DTOs + * @return the list of communication request models + */ + public static List toModel(List requests) { + return requests.stream() + .map(request -> + CommunicationRequest.create(request.communicationTemplateId(), request.creationTimestamp(), request.reason())) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestDto.java deleted file mode 100644 index dbe5574d..00000000 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestDto.java +++ /dev/null @@ -1,34 +0,0 @@ -package fr.insee.pearljam.api.surveyunit.dto; - -import java.util.ArrayList; -import java.util.List; - -import fr.insee.pearljam.domain.surveyunit.model.communication.*; - -public record CommunicationRequestDto( - Long id, - String messhugahId, - CommunicationRequestType type, - CommunicationRequestReason reason, - CommunicationRequestMedium medium, - CommunicationRequestEmiter emiter, - List status) { - - public static CommunicationRequest toModel(CommunicationRequestDto request) { - List status = new ArrayList<>(); - if(request.status() != null) { - status = request.status().stream() - .map(CommunicationRequestStatusDto::toModel).toList(); - } - - return new CommunicationRequest(request.id(), request.messhugahId(), request.type(), - request.reason(), request.medium(), request.emiter(), status); - } - - public static CommunicationRequestDto fromModel(CommunicationRequest request) { - List status = request.status().stream() - .map(CommunicationRequestStatusDto::fromModel).toList(); - return new CommunicationRequestDto(request.id(), request.messhugahId(), request.type(), - request.reason(), request.medium(), request.emiter(), status); - } -} diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java new file mode 100644 index 00000000..d4e27354 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java @@ -0,0 +1,42 @@ +package fr.insee.pearljam.api.surveyunit.dto; + +import fr.insee.pearljam.domain.surveyunit.model.communication.*; + +import java.util.List; +import java.util.Set; + +/** + * Record representing a CommunicationRequestResponseDto + * @param id The ID of the communication request + * @param communicationTemplateId configuration id of the communication + * @param reason The reason for the communication request + * @param emitter The emitter of the communication request + * @param status The status of the communication request + */ +public record CommunicationRequestResponseDto( + Long id, + Long communicationTemplateId, + CommunicationRequestReason reason, + CommunicationRequestEmitter emitter, + List status) { + + /** + * Converts a list of CommunicationRequest models to a set of CommunicationRequestResponseDto. + * @param requests The set of CommunicationRequest models + * @return A list of CommunicationRequestResponseDto instances + */ + public static List fromModel(Set requests) { + return requests.stream() + .map(request -> { + List status = request.status().stream() + .map(CommunicationRequestStatusDto::fromModel) + .toList(); + return new CommunicationRequestResponseDto(request.id(), + request.communicationTemplateId(), + request.reason(), + request.emitter(), + status); + }) + .toList(); + } +} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestStatusDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestStatusDto.java index 9198a363..290ca6c7 100644 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestStatusDto.java +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestStatusDto.java @@ -3,15 +3,34 @@ import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestStatus; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationStatusType; +/** + * Record representing a CommunicationRequestStatusDto + * + * @param id The ID of the communication request status + * @param date The date of the communication request status + * @param status The status type of the communication request + */ public record CommunicationRequestStatusDto( - Long id, - Long date, - CommunicationStatusType status) { + Long id, + Long date, + CommunicationStatusType status) { + /** + * Converts a CommunicationRequestStatus model to a CommunicationRequestStatusDto. + * + * @param requestStatus The CommunicationRequestStatus model to convert. + * @return A new CommunicationRequestStatusDto instance. + */ public static CommunicationRequestStatusDto fromModel(CommunicationRequestStatus requestStatus) { return new CommunicationRequestStatusDto(requestStatus.id(), requestStatus.date(), requestStatus.status()); } + /** + * Converts a CommunicationRequestStatusDto to a CommunicationRequestStatus model. + * + * @param requestStatus The CommunicationRequestStatusDto to convert. + * @return A new CommunicationRequestStatus model instance. + */ public static CommunicationRequestStatus toModel(CommunicationRequestStatusDto requestStatus) { return new CommunicationRequestStatus(requestStatus.id(), requestStatus.date(), requestStatus.status()); } diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/IdentificationDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/IdentificationDto.java index 8d4010d1..72e7a110 100644 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/IdentificationDto.java +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/IdentificationDto.java @@ -28,6 +28,9 @@ public static Identification toModel(IdentificationDto identificationDto) { } public static IdentificationDto fromModel(Identification identification) { + if(identification == null) { + return null; + } return new IdentificationDto(identification.identification(), identification.access(), identification.situation(), diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitUpdateDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitUpdateDto.java new file mode 100644 index 00000000..a3e4639f --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitUpdateDto.java @@ -0,0 +1,41 @@ +package fr.insee.pearljam.api.surveyunit.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; +import fr.insee.pearljam.api.dto.address.AddressDto; +import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; +import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; +import fr.insee.pearljam.api.dto.person.PersonDto; +import fr.insee.pearljam.api.dto.state.StateDto; +import jakarta.validation.Valid; + +import java.util.List; + +/** + * Record representing a SurveyUnitResponseDto + * + * @param id The ID of the survey unit + * @param persons The list of persons associated with the survey unit + * @param address The address of the survey unit + * @param move Indicates if the survey unit has moved + * @param comments The list of comments related to the survey unit + * @param states The list of states of the survey unit + * @param contactAttempts The list of contact attempts for the survey unit + * @param contactOutcome The contact outcome of the survey unit + * @param identification The identification information of the survey unit + * @param communicationRequests The list of communication requests for the survey unit + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record SurveyUnitUpdateDto( + String id, + List persons, + AddressDto address, + Boolean move, + @Valid + List comments, + List states, + List contactAttempts, + ContactOutcomeDto contactOutcome, + IdentificationDto identification, + @Valid + List communicationRequests) { +} diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/ApiExceptionComponent.java b/src/main/java/fr/insee/pearljam/api/web/exception/ApiExceptionComponent.java index 8f86582d..6bfe168d 100644 --- a/src/main/java/fr/insee/pearljam/api/web/exception/ApiExceptionComponent.java +++ b/src/main/java/fr/insee/pearljam/api/web/exception/ApiExceptionComponent.java @@ -3,7 +3,6 @@ import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.WebRequest; @@ -13,7 +12,6 @@ /** * Component used to build APIError objects */ -@Component public class ApiExceptionComponent { private final ErrorAttributes errorAttributes; diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java index a4df7259..d68d0ac8 100644 --- a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java +++ b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java @@ -5,8 +5,8 @@ import fr.insee.pearljam.domain.exception.EntityNotFoundException; import fr.insee.pearljam.infrastructure.mail.exception.SendMailException; import jakarta.validation.ConstraintViolationException; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; @@ -24,11 +24,14 @@ */ @ControllerAdvice @Slf4j -@RequiredArgsConstructor public class ExceptionControllerAdvice { private final ApiExceptionComponent errorComponent; + public ExceptionControllerAdvice(ErrorAttributes errorAttributes) { + this.errorComponent = new ApiExceptionComponent(errorAttributes); + } + private static final String ERROR_OCCURRED_LABEL = "An error has occurred"; public static final String INVALID_PARAMETERS_MESSAGE = "Invalid parameters"; diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java index fe3cd784..7116f3f9 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java @@ -1,13 +1,25 @@ package fr.insee.pearljam.domain.surveyunit.model.communication; +import java.util.ArrayList; import java.util.List; public record CommunicationRequest( Long id, - String messhugahId, - CommunicationRequestType type, + Long communicationTemplateId, CommunicationRequestReason reason, - CommunicationRequestMedium medium, - CommunicationRequestEmiter emiter, + CommunicationRequestEmitter emitter, List status) { + + /** + * Create a communication request for messhugah + * @param communicationTemplateId communication configuration id + * @param creationTimestamp creation date of the communication request + * @param reason reason why the communication request is created + * @return {@link CommunicationRequest} communication request object + */ + public static CommunicationRequest create(Long communicationTemplateId, Long creationTimestamp, CommunicationRequestReason reason) { + List status = new ArrayList<>(); + status.add(CommunicationRequestStatus.create(creationTimestamp)); + return new CommunicationRequest(null, communicationTemplateId, reason, CommunicationRequestEmitter.INTERVIEWER, status); + } } diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestEmiter.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestEmitter.java similarity index 68% rename from src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestEmiter.java rename to src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestEmitter.java index c19f6ff2..28a96a27 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestEmiter.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestEmitter.java @@ -1,5 +1,5 @@ package fr.insee.pearljam.domain.surveyunit.model.communication; -public enum CommunicationRequestEmiter { +public enum CommunicationRequestEmitter { TOOL, INTERVIEWER } diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestStatus.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestStatus.java index 0cbaecd7..6d02ac84 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestStatus.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestStatus.java @@ -4,4 +4,13 @@ public record CommunicationRequestStatus( Long id, Long date, CommunicationStatusType status) { + + /** + * Create a CommunicationRequestStatus + * @param timestamp status creation date + * @return {@link CommunicationRequestStatus} communication request status object + */ + public static CommunicationRequestStatus create(Long timestamp) { + return new CommunicationRequestStatus(null, timestamp, CommunicationStatusType.INITIATED); + } } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/mail/RestMailSender.java b/src/main/java/fr/insee/pearljam/infrastructure/mail/RestMailSender.java index dc99ffb9..68d21e54 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/mail/RestMailSender.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/mail/RestMailSender.java @@ -48,7 +48,7 @@ public void sendMail(String subject, String content) throws SendMailException { String.class); log.info("Response : message # {}", response.getStatusCode()); } catch(RestClientException ex) { - throw new SendMailException(); + throw new SendMailException(ex.getMessage()); } } } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/mail/exception/SendMailException.java b/src/main/java/fr/insee/pearljam/infrastructure/mail/exception/SendMailException.java index 22c70736..9ea3d90c 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/mail/exception/SendMailException.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/mail/exception/SendMailException.java @@ -4,7 +4,7 @@ * Handle exceptions when sending mails */ public class SendMailException extends Exception { - public SendMailException() { - super(); + public SendMailException(String message) { + super(message); } } \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommentDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommentDB.java index f522716c..f5ac00cf 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommentDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommentDB.java @@ -1,6 +1,8 @@ package fr.insee.pearljam.infrastructure.surveyunit.entity; import java.io.Serializable; +import java.util.Set; +import java.util.stream.Collectors; import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.domain.surveyunit.model.Comment; @@ -79,4 +81,15 @@ public static CommentDB fromModel(SurveyUnit surveyUnit, Comment comment) { public static Comment toModel(CommentDB comment) { return new Comment(comment.getType(), comment.getValue(), comment.getSurveyUnit().getId()); } + + /** + * Create model objects from entities + * @param comments entities object + * @return comment models object + */ + public static Set toModel(Set comments) { + return comments.stream() + .map(CommentDB::toModel) + .collect(Collectors.toSet()); + } } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java index 497c7194..9b91e54c 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java @@ -3,6 +3,8 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.domain.surveyunit.model.communication.*; @@ -36,11 +38,7 @@ public class CommunicationRequestDB implements Serializable { private Long id; @Column - private String messhugahId; - - @Enumerated(EnumType.STRING) - @Column - private CommunicationRequestType type; + private Long communicationTemplateId; @Enumerated(EnumType.STRING) @Column @@ -48,11 +46,7 @@ public class CommunicationRequestDB implements Serializable { @Enumerated(EnumType.STRING) @Column - private CommunicationRequestMedium medium; - - @Enumerated(EnumType.STRING) - @Column - private CommunicationRequestEmiter emiter; + private CommunicationRequestEmitter emitter; @ManyToOne(fetch = FetchType.LAZY) private SurveyUnit surveyUnit; @@ -69,8 +63,8 @@ public class CommunicationRequestDB implements Serializable { public static CommunicationRequestDB fromModel(CommunicationRequest request, SurveyUnit surveyUnit) { List status = new ArrayList<>(); - CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(request.id(), request.messhugahId(), request.type(), - request.reason(), request.medium(), request.emiter(), surveyUnit, status); + CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(request.id(), request.communicationTemplateId(), + request.reason(), request.emitter(), surveyUnit, status); if(request.status() != null) { status.addAll(request.status().stream() @@ -93,7 +87,18 @@ public static CommunicationRequest toModel(CommunicationRequestDB request) { .map(CommunicationRequestStatusDB::toModel).toList(); } - return new CommunicationRequest(request.getId(), request.getMesshugahId(), request.getType(), - request.getReason(), request.getMedium(), request.getEmiter(), status); + return new CommunicationRequest(request.getId(), request.getCommunicationTemplateId(), + request.getReason(), request.getEmitter(), status); + } + + /** + * Converts a set of CommunicationRequestDB entities to a set of CommunicationRequest models. + * @param requests set of CommunicationRequestDB entities + * @return set of CommunicationRequest models + */ + public static Set toModel(Set requests) { + return requests.stream() + .map(CommunicationRequestDB::toModel) + .collect(Collectors.toSet()); } } diff --git a/src/main/resources/db/changelog/540_alter_communication_request.xml b/src/main/resources/db/changelog/540_alter_communication_request.xml new file mode 100644 index 00000000..0a737ebc --- /dev/null +++ b/src/main/resources/db/changelog/540_alter_communication_request.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/db/master.xml b/src/main/resources/db/master.xml index 7da280cd..b28a6305 100644 --- a/src/main/resources/db/master.xml +++ b/src/main/resources/db/master.xml @@ -42,4 +42,7 @@ + + + \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/message/controller/dummy/MailFakeSender.java b/src/test/java/fr/insee/pearljam/api/message/controller/dummy/MailFakeSender.java index b7f5a5d2..a8982d74 100644 --- a/src/test/java/fr/insee/pearljam/api/message/controller/dummy/MailFakeSender.java +++ b/src/test/java/fr/insee/pearljam/api/message/controller/dummy/MailFakeSender.java @@ -18,7 +18,7 @@ public class MailFakeSender implements MailSender { @Override public void sendMail(String subject, String content) throws SendMailException { if(throwSendMailException) { - throw new SendMailException(); + throw new SendMailException("error"); } isMailSent = true; } diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java index 0f3ad734..b7e5757c 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java @@ -59,8 +59,12 @@ void updateComment01() throws Exception { } @ParameterizedTest - @ValueSource(strings = {"{\"value\": \"5\"}", "{\"type\": \"INTERVIEWER\"}"}) - @DisplayName("Should return bad request when comment type or value is null") + @ValueSource(strings = { + "{\"value\": \"5\"}", + "{\"type\": \"INTERVIEWER\"}", + "{\"value\": \"5\",\"type\": \"INVALID\"}" + }) + @DisplayName("Should return bad request when comment type or value is invalid") void updateComment02(String invalidComment) throws Exception { mockMvc.perform(put(updatePath) .contentType(MediaType.APPLICATION_JSON) diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java index 555a4a71..ff73c5df 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java @@ -1,10 +1,10 @@ package fr.insee.pearljam.api.surveyunit.controller; import fr.insee.pearljam.api.controller.SurveyUnitController; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDetailDto; import fr.insee.pearljam.api.surveyunit.controller.dummy.SurveyUnitFakeService; import fr.insee.pearljam.api.surveyunit.dto.CommentDto; import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; @@ -16,14 +16,14 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.core.Authentication; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -85,8 +85,8 @@ void updateSurveyUnit01() throws Exception { .content(surveyUnitJson)) .andExpect(status().isOk()); - SurveyUnitDetailDto surveyUnitDetailDto = surveyUnitService.getSurveyUnitUpdated(); - assertThat(surveyUnitDetailDto.getId()).isEqualTo("su-id"); + SurveyUnitUpdateDto surveyUnitUpdated = surveyUnitService.getSurveyUnitUpdated(); + assertThat(surveyUnitUpdated.id()).isEqualTo("su-id"); IdentificationDto identificationExpected = new IdentificationDto(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, @@ -94,14 +94,14 @@ void updateSurveyUnit01() throws Exception { CategoryQuestionValue.OCCASIONAL, OccupantQuestionValue.IDENTIFIED); - assertThat(surveyUnitDetailDto.getIdentification()).isEqualTo(identificationExpected); + assertThat(surveyUnitUpdated.identification()).isEqualTo(identificationExpected); CommentDto commentExpected1 = new CommentDto(CommentType.MANAGEMENT, "5"); CommentDto commentExpected2 = new CommentDto(CommentType.INTERVIEWER, "value"); - assertThat(surveyUnitDetailDto.getComments()) + assertThat(surveyUnitUpdated.comments()) .hasSize(2) .containsExactlyInAnyOrder(commentExpected1, commentExpected2); - assertThat(surveyUnitDetailDto.getIdentification()).isEqualTo(identificationExpected); + assertThat(surveyUnitUpdated.identification()).isEqualTo(identificationExpected); } @Test @@ -126,34 +126,22 @@ void updateSurveyUnit03() throws Exception { assertThat(surveyUnitService.getSurveyUnitUpdated()).isNull(); } - @Test + @ParameterizedTest + @ValueSource(strings = { + "\"comments\": [{\"value\": \"5\"}]", + "\"comments\": [{\"type\": \"INTERVIEWER\"}]", + "\"comments\": [{\"value\": \"5\",\"type\": \"INVALID\"}]" + }) @DisplayName("Should return bad request when comment are invalid") - void updateSurveyUnit04() throws Exception { - List invalidComments = List.of( - """ - "comments": [ - { - "type": "MANAGEMENT" - } - ]""", - """ - "comments": [ - { - "value": "value" - } - ]""" - ); - - for(String invalidComment : invalidComments) { - surveyUnitJson = String.format(surveyUnitTemplate, invalidComment, identification); - System.out.println(surveyUnitJson); - mockMvc.perform(put(updatePath) - .contentType(MediaType.APPLICATION_JSON) - .content(surveyUnitJson)) - .andExpect( - MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, updatePath, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE) - ); - assertThat(surveyUnitService.getSurveyUnitUpdated()).isNull(); - } + void updateSurveyUnit04(String invalidComment) throws Exception { + surveyUnitJson = String.format(surveyUnitTemplate, invalidComment, identification); + System.out.println(surveyUnitJson); + mockMvc.perform(put(updatePath) + .contentType(MediaType.APPLICATION_JSON) + .content(surveyUnitJson)) + .andExpect( + MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, updatePath, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE) + ); + assertThat(surveyUnitService.getSurveyUnitUpdated()).isNull(); } } diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/SurveyUnitFakeService.java b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/SurveyUnitFakeService.java index a8fb2696..f62c48b1 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/SurveyUnitFakeService.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/SurveyUnitFakeService.java @@ -7,6 +7,7 @@ import fr.insee.pearljam.api.exception.NotFoundException; import fr.insee.pearljam.api.exception.SurveyUnitException; import fr.insee.pearljam.api.service.SurveyUnitService; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.domain.exception.PersonNotFoundException; import fr.insee.pearljam.domain.exception.SurveyUnitNotFoundException; import jakarta.servlet.http.HttpServletRequest; @@ -27,7 +28,7 @@ public class SurveyUnitFakeService implements SurveyUnitService { private boolean shouldThrowPersonException = false; @Getter - private SurveyUnitDetailDto surveyUnitUpdated = null; + private SurveyUnitUpdateDto surveyUnitUpdated = null; @Override public SurveyUnitDetailDto getSurveyUnitDetail(String userId, String id) throws SurveyUnitException, NotFoundException { @@ -40,7 +41,7 @@ public List getSurveyUnitDto(String userId, Boolean extended) { } @Override - public SurveyUnitDetailDto updateSurveyUnitDetail(String userId, String id, SurveyUnitDetailDto surveyUnitDetailDto) throws SurveyUnitNotFoundException, PersonNotFoundException { + public SurveyUnitDetailDto updateSurveyUnit(String userId, String id, SurveyUnitUpdateDto surveyUnitUpdateDto) throws SurveyUnitNotFoundException, PersonNotFoundException { if(shouldThrowSurveyUnitException) { throw new SurveyUnitNotFoundException(); } @@ -48,8 +49,8 @@ public SurveyUnitDetailDto updateSurveyUnitDetail(String userId, String id, Surv if(shouldThrowPersonException) { throw new PersonNotFoundException(); } - surveyUnitUpdated = surveyUnitDetailDto; - return surveyUnitDetailDto; + surveyUnitUpdated = surveyUnitUpdateDto; + return null; } @Override diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java index 4932fdc1..0250cdeb 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java @@ -85,12 +85,12 @@ void testCreateCommunicationRequests01() { new CommunicationRequestStatusDB(4L, 123345678912L, CommunicationStatusType.CANCELLED, null) ); - communicationRequestDBs.add(new CommunicationRequestDB(10L, "messhugahid1", CommunicationRequestType.NOTICE, - CommunicationRequestReason.UNREACHABLE, CommunicationRequestMedium.EMAIL, - CommunicationRequestEmiter.INTERVIEWER, surveyUnit, status1)); - communicationRequestDBs.add(new CommunicationRequestDB(11L, "messhugahid2", CommunicationRequestType.REMINDER, - CommunicationRequestReason.REFUSAL, CommunicationRequestMedium.MAIL, - CommunicationRequestEmiter.TOOL, surveyUnit, status2)); + communicationRequestDBs.add(new CommunicationRequestDB(10L, 1L, + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, surveyUnit, status1)); + communicationRequestDBs.add(new CommunicationRequestDB(11L, 2L, + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.TOOL, surveyUnit, status2)); surveyUnit.setCommunicationRequests(communicationRequestDBs); SurveyUnitDetailDto surveyUnitDetailDto = new SurveyUnitDetailDto(surveyUnit); @@ -107,12 +107,12 @@ void testCreateCommunicationRequests01() { assertThat(surveyUnitDetailDto.getCommunicationRequests()) .containsExactlyInAnyOrder( - new CommunicationRequestDto(10L, "messhugahid1", CommunicationRequestType.NOTICE, - CommunicationRequestReason.UNREACHABLE, CommunicationRequestMedium.EMAIL, - CommunicationRequestEmiter.INTERVIEWER, status1Expected), - new CommunicationRequestDto(11L, "messhugahid2", CommunicationRequestType.REMINDER, - CommunicationRequestReason.REFUSAL, CommunicationRequestMedium.MAIL, - CommunicationRequestEmiter.TOOL, status2Expected) + new CommunicationRequestResponseDto(10L, 1L, + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, status1Expected), + new CommunicationRequestResponseDto(11L, 2L, + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.TOOL, status2Expected) ); } } diff --git a/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java b/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java index 21908003..d7bb8fab 100644 --- a/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java +++ b/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java @@ -1,7 +1,6 @@ package fr.insee.pearljam.api.utils; import fr.insee.pearljam.api.utils.matcher.StructureDateMatcher; -import fr.insee.pearljam.api.web.exception.ApiExceptionComponent; import fr.insee.pearljam.api.web.exception.ExceptionControllerAdvice; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.http.HttpStatus; @@ -23,6 +22,6 @@ public static ResultMatcher apiErrorMatches(HttpStatus errorStatus, String path, } public static ExceptionControllerAdvice createExceptionControllerAdvice() { - return new ExceptionControllerAdvice(new ApiExceptionComponent(new DefaultErrorAttributes())); + return new ExceptionControllerAdvice(new DefaultErrorAttributes()); } } \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java new file mode 100644 index 00000000..39ae248d --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java @@ -0,0 +1,31 @@ +package fr.insee.pearljam.domain.surveyunit.model; + +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestEmitter; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestReason; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class CommunicationRequestTest { + + @Test + void testCreateCommunicationRequest() { + // Given + Long configurationId = 1L; + Long creationDate = System.currentTimeMillis(); + CommunicationRequestReason reason = CommunicationRequestReason.REFUSAL; + + // When + CommunicationRequest communicationRequest = CommunicationRequest.create(configurationId, creationDate, reason); + + // Then + assertNotNull(communicationRequest); + assertNull(communicationRequest.id()); + assertEquals(configurationId, communicationRequest.communicationTemplateId()); + assertEquals(reason, communicationRequest.reason()); + assertEquals(CommunicationRequestEmitter.INTERVIEWER, communicationRequest.emitter()); + assertNotNull(communicationRequest.status()); + assertEquals(1, communicationRequest.status().size()); + assertEquals(creationDate, communicationRequest.status().getFirst().date()); + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java index a9b87803..8bc7c8f8 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java @@ -1,12 +1,8 @@ package fr.insee.pearljam.domain.surveyunit.service; import fr.insee.pearljam.api.domain.*; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDetailDto; import fr.insee.pearljam.api.service.impl.SurveyUnitUpdateServiceImpl; -import fr.insee.pearljam.api.surveyunit.dto.CommentDto; -import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestDto; -import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestStatusDto; -import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; +import fr.insee.pearljam.api.surveyunit.dto.*; import fr.insee.pearljam.domain.surveyunit.model.CommentType; import fr.insee.pearljam.domain.surveyunit.model.communication.*; import fr.insee.pearljam.domain.surveyunit.model.question.*; @@ -27,7 +23,7 @@ class SurveyUnitUpdateServiceImplTest { private SurveyUnitUpdateServiceImpl surveyUnitService; private SurveyUnit surveyUnit; - private SurveyUnitDetailDto surveyUnitDto; + private SurveyUnitUpdateDto surveyUnitDto; @BeforeEach void setup() { @@ -35,67 +31,59 @@ void setup() { surveyUnit = new SurveyUnit("id", true, true, null, null, null, null, null, null); Set communicationRequestDBs = new HashSet<>(); - communicationRequestDBs.add(new CommunicationRequestDB(10L, "mid", null, null, null, null, surveyUnit, null)); + communicationRequestDBs.add(new CommunicationRequestDB(10L, 3L, + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.TOOL, + surveyUnit, null)); surveyUnit.setCommunicationRequests(communicationRequestDBs); - - surveyUnitDto = new SurveyUnitDetailDto(); } @Test @DisplayName("Should add communication requests for survey unit") void testUpdateCommunication01() { - List status1 = List.of( - new CommunicationRequestStatusDto(null, 1233456789L, CommunicationStatusType.INITIATED), - new CommunicationRequestStatusDto(2L, 123345678910L, CommunicationStatusType.FAILED) - ); - - List status2 = List.of( - new CommunicationRequestStatusDto(3L, 123345678911L, CommunicationStatusType.READY), - new CommunicationRequestStatusDto(4L, 123345678912L, CommunicationStatusType.CANCELLED) - ); - - List communicationRequests = List.of( - new CommunicationRequestDto(null, "messhugahid1", CommunicationRequestType.NOTICE, - CommunicationRequestReason.UNREACHABLE, CommunicationRequestMedium.EMAIL, - CommunicationRequestEmiter.INTERVIEWER, status1), - new CommunicationRequestDto(null, "messhugahid2", CommunicationRequestType.REMINDER, - CommunicationRequestReason.REFUSAL, CommunicationRequestMedium.MAIL, - CommunicationRequestEmiter.TOOL, status2) + List communicationRequests = List.of( + new CommunicationRequestCreateDto(1L, 12345678910L, + CommunicationRequestReason.UNREACHABLE), + new CommunicationRequestCreateDto(2L, 1234567891011L, + CommunicationRequestReason.REFUSAL) ); - surveyUnitDto.setCommunicationRequests(communicationRequests); + surveyUnitDto = createSurveyUnitDto(null, null, communicationRequests); surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); Set communicationRequestResults = surveyUnit.getCommunicationRequests(); assertThat(communicationRequestResults) .hasSize(3) .extracting(CommunicationRequestDB::getId, - CommunicationRequestDB::getMesshugahId, - CommunicationRequestDB::getType, + CommunicationRequestDB::getCommunicationTemplateId, CommunicationRequestDB::getReason, - CommunicationRequestDB::getMedium, - CommunicationRequestDB::getEmiter, + CommunicationRequestDB::getEmitter, CommunicationRequestDB::getSurveyUnit, communicationRequestDB -> communicationRequestDB.getStatus() == null ? null : communicationRequestDB.getStatus().stream() .map(status -> tuple(status.getId(), status.getDate(), status.getStatus())) .toList() ) .containsExactlyInAnyOrder( - tuple(null, "messhugahid1", CommunicationRequestType.NOTICE, - CommunicationRequestReason.UNREACHABLE, CommunicationRequestMedium.EMAIL, - CommunicationRequestEmiter.INTERVIEWER, surveyUnit, - List.of( - tuple(null, 1233456789L, CommunicationStatusType.INITIATED), - tuple(2L, 123345678910L, CommunicationStatusType.FAILED) - )), - tuple(null, "messhugahid2", CommunicationRequestType.REMINDER, - CommunicationRequestReason.REFUSAL, CommunicationRequestMedium.MAIL, - CommunicationRequestEmiter.TOOL, surveyUnit, - List.of( - tuple(3L, 123345678911L, CommunicationStatusType.READY), - tuple(4L, 123345678912L, CommunicationStatusType.CANCELLED) - )), - tuple(10L, "mid", null, null, null, null, surveyUnit, null) + tuple(null, + 1L, + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, + surveyUnit, + List.of(tuple(null, 12345678910L, CommunicationStatusType.INITIATED)) + ), + tuple(null, + 2L, + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.INTERVIEWER, + surveyUnit, + List.of(tuple(null, 1234567891011L, CommunicationStatusType.INITIATED)) + ), + tuple(10L, + 3L, + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.TOOL, + surveyUnit, + null) ); // Check that CommunicationRequestStatusDB has the correct parent @@ -106,33 +94,6 @@ void testUpdateCommunication01() { }); } - @Test - @DisplayName("Should not add existing requests (with id != null) for survey unit") - void testUpdateCommunication02() { - List status = List.of( - new CommunicationRequestStatusDto(null, 1233456789L, CommunicationStatusType.INITIATED), - new CommunicationRequestStatusDto(2L, 123345678910L, CommunicationStatusType.FAILED) - ); - - List communicationRequests = List.of( - new CommunicationRequestDto(1L, "messhugahid1", CommunicationRequestType.NOTICE, - CommunicationRequestReason.UNREACHABLE, CommunicationRequestMedium.EMAIL, - CommunicationRequestEmiter.INTERVIEWER, status), - new CommunicationRequestDto(null, "messhugahid2", CommunicationRequestType.REMINDER, - CommunicationRequestReason.REFUSAL, CommunicationRequestMedium.MAIL, - CommunicationRequestEmiter.TOOL, null) - ); - - surveyUnitDto.setCommunicationRequests(communicationRequests); - surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); - - Set communicationRequestResults = surveyUnit.getCommunicationRequests(); - assertThat(communicationRequestResults) - .hasSize(2) - .extracting(CommunicationRequestDB::getId) - .containsExactlyInAnyOrder(10L, null); - } - @Test @DisplayName("Should add comments for survey unit") void testUpdateComments01() { @@ -141,7 +102,7 @@ void testUpdateComments01() { new CommentDto(CommentType.MANAGEMENT, "value2") ); - surveyUnitDto.setComments(comments); + surveyUnitDto = createSurveyUnitDto(null, comments, null); surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); assertThat(surveyUnit.getComments()) @@ -169,7 +130,7 @@ void testUpdateComments02() { new CommentDto(CommentType.INTERVIEWER, "value4") ); - surveyUnitDto.setComments(comments); + surveyUnitDto = createSurveyUnitDto(null, comments, null); surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); assertThat(surveyUnit.getComments()) @@ -201,7 +162,7 @@ void testUpdateIdentification01() { SituationQuestionValue.NOORDINARY, CategoryQuestionValue.VACANT, OccupantQuestionValue.UNIDENTIFIED); - surveyUnitDto.setIdentification(identification); + surveyUnitDto = createSurveyUnitDto(identification, null, null); surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); IdentificationDB identificationResult = surveyUnit.getIdentification(); @@ -225,7 +186,7 @@ void testUpdateIdentification02() { OccupantQuestionValue.IDENTIFIED, surveyUnit); surveyUnit.setIdentification(identificationDB); - surveyUnitDto.setIdentification(null); + surveyUnitDto = createSurveyUnitDto(null, null, null); surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); assertThat(surveyUnit.getIdentification()).isEqualTo(identificationDB); } @@ -239,7 +200,7 @@ void testUpdateIdentification03() { SituationQuestionValue.NOORDINARY, CategoryQuestionValue.VACANT, OccupantQuestionValue.UNIDENTIFIED); - surveyUnitDto.setIdentification(identification); + surveyUnitDto = createSurveyUnitDto(identification, null, null); surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); @@ -252,4 +213,9 @@ void testUpdateIdentification03() { assertThat(identificationResult.getOccupant()).isEqualTo(OccupantQuestionValue.UNIDENTIFIED); assertThat(identificationResult.getSurveyUnit()).isEqualTo(surveyUnit); } + + private SurveyUnitUpdateDto createSurveyUnitDto(IdentificationDto identification, List comments, List communicationRequests) { + return new SurveyUnitUpdateDto("su-id", null, null, true, + comments, null, null, null, identification, communicationRequests); + } } diff --git a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java index e09207a5..75102439 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java @@ -28,16 +28,15 @@ void testToModel01() { new CommunicationRequestStatusDB(null, 1233456789L, CommunicationStatusType.INITIATED, null), new CommunicationRequestStatusDB(2L, 123345678910L, CommunicationStatusType.FAILED, null) ); - CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(1L, "messhugahid1", CommunicationRequestType.NOTICE, - CommunicationRequestReason.UNREACHABLE, CommunicationRequestMedium.EMAIL, - CommunicationRequestEmiter.INTERVIEWER, surveyUnit, statusDB); + CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(1L, 2L, + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, + surveyUnit, + statusDB); CommunicationRequest communicationRequest = CommunicationRequestDB.toModel(communicationRequestDB); assertThat(communicationRequest.id()).isEqualTo(communicationRequestDB.getId()); - assertThat(communicationRequest.messhugahId()).isEqualTo(communicationRequestDB.getMesshugahId()); - assertThat(communicationRequest.type()).isEqualTo(communicationRequestDB.getType()); - assertThat(communicationRequest.emiter()).isEqualTo(communicationRequestDB.getEmiter()); - assertThat(communicationRequest.medium()).isEqualTo(communicationRequestDB.getMedium()); + assertThat(communicationRequest.communicationTemplateId()).isEqualTo(communicationRequestDB.getCommunicationTemplateId()); assertThat(communicationRequest.reason()).isEqualTo(communicationRequestDB.getReason()); List status = statusDB.stream() .map(CommunicationRequestStatusDB::toModel) @@ -53,16 +52,15 @@ void testFromModel01() { new CommunicationRequestStatus(2L, 123345678910L, CommunicationStatusType.FAILED) ); - CommunicationRequest communicationRequest = new CommunicationRequest(1L, "messhugahid1", CommunicationRequestType.NOTICE, - CommunicationRequestReason.UNREACHABLE, CommunicationRequestMedium.EMAIL, - CommunicationRequestEmiter.INTERVIEWER, status); + CommunicationRequest communicationRequest = new CommunicationRequest(1L, + 2L, + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, + status); CommunicationRequestDB communicationRequestDB = CommunicationRequestDB.fromModel(communicationRequest, surveyUnit); assertThat(communicationRequestDB.getId()).isEqualTo(communicationRequest.id()); - assertThat(communicationRequestDB.getMesshugahId()).isEqualTo(communicationRequest.messhugahId()); - assertThat(communicationRequestDB.getType()).isEqualTo(communicationRequest.type()); - assertThat(communicationRequestDB.getEmiter()).isEqualTo(communicationRequest.emiter()); - assertThat(communicationRequestDB.getMedium()).isEqualTo(communicationRequest.medium()); + assertThat(communicationRequestDB.getCommunicationTemplateId()).isEqualTo(communicationRequest.communicationTemplateId()); assertThat(communicationRequestDB.getReason()).isEqualTo(communicationRequest.reason()); assertThat(communicationRequestDB.getStatus()) .extracting(CommunicationRequestStatusDB::getId, diff --git a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java index b4c6052f..123111a8 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java @@ -21,9 +21,9 @@ void testToModel01() { @Test @DisplayName("Should return entity object") void testFromModel01() { - CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(null, "messhugahid1", CommunicationRequestType.NOTICE, - CommunicationRequestReason.UNREACHABLE, CommunicationRequestMedium.EMAIL, - CommunicationRequestEmiter.INTERVIEWER, null, null); + CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(null, 1L, + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, null, null); CommunicationRequestStatus communicationRequestStatus = new CommunicationRequestStatus(1L, 123456789L, CommunicationStatusType.INITIATED); CommunicationRequestStatusDB communicationRequestStatusDB = CommunicationRequestStatusDB.fromModel(communicationRequestStatus, communicationRequestDB); From 158b2bcc54e4e9413afb098f93feeac003aa0e1b Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 23 Jul 2024 04:46:36 +0200 Subject: [PATCH 02/48] feat: add communication template - divide campaign dtos - divide visibility dtos - add communication template in db --- pom.xml | 7 + .../dto/CommunicationTemplateResponseDto.java | 25 ++ .../campaign/dto/input/CampaignCreateDto.java | 31 ++ .../campaign/dto/input/CampaignUpdateDto.java | 35 ++ .../input/CommunicationTemplateCreateDto.java | 35 ++ .../VisibilityCampaignCreateDto.java | 56 +++ .../VisibilityCampaignUpdateDto.java | 54 +++ .../input/visibility/VisibilityUpdateDto.java | 36 ++ .../dto/output/CampaignResponseDto.java | 50 +++ .../visibility/VisibilityCampaignDto.java | 30 ++ .../api/controller/CampaignController.java | 175 ++++----- .../insee/pearljam/api/domain/Campaign.java | 3 +- .../pearljam/api/domain/OrganizationUnit.java | 2 +- .../insee/pearljam/api/domain/Visibility.java | 102 ----- .../pearljam/api/domain/VisibilityDB.java | 104 +++++ ...{VisibilityId.java => VisibilityDBId.java} | 2 +- .../api/dto/campaign/CampaignContextDto.java | 101 ----- .../api/dto/campaign/CampaignDto.java | 1 - .../api/dto/referent/ReferentDto.java | 36 +- .../api/dto/surveyunit/SurveyUnitDto.java | 220 +---------- .../dto/visibility/VisibilityContextDto.java | 38 -- .../api/dto/visibility/VisibilityDto.java | 144 ------- .../api/exception/VisibilityException.java | 16 - .../api/repository/CampaignRepository.java | 10 +- .../api/repository/SurveyUnitRepository.java | 4 +- .../api/repository/VisibilityRepository.java | 63 --- .../pearljam/api/service/CampaignService.java | 42 +- .../api/service/impl/CampaignServiceImpl.java | 363 +++++------------- .../impl/ContactOutcomeServiceImpl.java | 4 +- .../service/impl/InterviewerServiceImpl.java | 10 +- .../api/service/impl/StateServiceImpl.java | 4 +- .../service/impl/SurveyUnitServiceImpl.java | 16 +- .../dto/SurveyUnitVisibilityDto.java | 35 ++ .../exception/ExceptionControllerAdvice.java | 12 + .../exception/VisibilityInvalidException.java | 8 + .../campaign/model/CampaignVisibility.java | 20 + .../domain/campaign/model/Visibility.java | 71 ++++ .../communication/CommunicationMedium.java | 5 + .../communication/CommunicationTemplate.java | 18 + .../communication/CommunicationType.java | 5 + .../port/serverside/VisibilityRepository.java | 25 ++ .../CampaignAlreadyExistException.java | 10 + .../exception/CampaignNotFoundException.java | 10 + .../EntityAlreadyExistException.java | 4 +- .../OrganizationalUnitNotFoundException.java | 10 + .../VisibilityNotFoundException.java | 10 + .../CommunicationRequestMedium.java | 5 - .../CommunicationRequestType.java | 5 - .../adapter/VisibilityDaoAdapter.java | 73 ++++ .../entity/CommunicationTemplateDB.java | 71 ++++ .../campaign/jpa/VisibilityJpaRepository.java | 63 +++ .../541_add_communication_template.xml | 40 ++ src/main/resources/db/master.xml | 3 + .../api/authKeycloak/TestAuthKeyCloak.java | 267 +++++-------- .../CampaignControllerCreateTest.java | 286 ++++++++++++++ .../CampaignControllerUpdateTest.java | 354 +++++++++++++++++ .../controller/CampaignControllerTest.java | 37 -- .../service/dummy/CampaignFakeService.java | 87 ++--- .../campaign/model/VisibilitytTest.java | 4 + .../CommunicationTemplateTest.java | 4 + .../adapter/VisibilityDaoAdapter.java | 4 + .../campaign/entity/VisibilityDBTest.java | 4 + src/test/resources/application-auth.yml | 4 +- 63 files changed, 1978 insertions(+), 1395 deletions(-) create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/CommunicationTemplateResponseDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignCreateDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignUpdateDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityUpdateDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/output/visibility/VisibilityCampaignDto.java delete mode 100644 src/main/java/fr/insee/pearljam/api/domain/Visibility.java create mode 100644 src/main/java/fr/insee/pearljam/api/domain/VisibilityDB.java rename src/main/java/fr/insee/pearljam/api/domain/{VisibilityId.java => VisibilityDBId.java} (92%) delete mode 100644 src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignContextDto.java delete mode 100644 src/main/java/fr/insee/pearljam/api/dto/visibility/VisibilityContextDto.java delete mode 100644 src/main/java/fr/insee/pearljam/api/dto/visibility/VisibilityDto.java delete mode 100644 src/main/java/fr/insee/pearljam/api/exception/VisibilityException.java delete mode 100644 src/main/java/fr/insee/pearljam/api/repository/VisibilityRepository.java create mode 100644 src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitVisibilityDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/web/exception/VisibilityInvalidException.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/model/CampaignVisibility.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationMedium.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationType.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java create mode 100644 src/main/java/fr/insee/pearljam/domain/exception/CampaignAlreadyExistException.java create mode 100644 src/main/java/fr/insee/pearljam/domain/exception/CampaignNotFoundException.java rename src/main/java/fr/insee/pearljam/{api/web => domain}/exception/EntityAlreadyExistException.java (63%) create mode 100644 src/main/java/fr/insee/pearljam/domain/exception/OrganizationalUnitNotFoundException.java create mode 100644 src/main/java/fr/insee/pearljam/domain/exception/VisibilityNotFoundException.java delete mode 100644 src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestMedium.java delete mode 100644 src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestType.java create mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java create mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java create mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/VisibilityJpaRepository.java create mode 100644 src/main/resources/db/changelog/541_add_communication_template.xml create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java delete mode 100644 src/test/java/fr/insee/pearljam/api/controller/CampaignControllerTest.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilitytTest.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java create mode 100644 src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java create mode 100644 src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java diff --git a/pom.xml b/pom.xml index 89c0bfd6..409439db 100644 --- a/pom.xml +++ b/pom.xml @@ -104,6 +104,13 @@ test + + org.javatuples + javatuples + 1.2 + test + + com.tngtech.archunit archunit diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/CommunicationTemplateResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/CommunicationTemplateResponseDto.java new file mode 100644 index 00000000..5b7dbb76 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/CommunicationTemplateResponseDto.java @@ -0,0 +1,25 @@ +package fr.insee.pearljam.api.campaign.dto; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; + +import java.util.List; + +public record CommunicationTemplateResponseDto( + Long id, + String messhugahId, + CommunicationMedium medium, + CommunicationType type +) { + public static List fromModel(List communicationTemplates) { + return communicationTemplates.stream() + .map(communicationTemplate -> + new CommunicationTemplateResponseDto( + communicationTemplate.id(), + communicationTemplate.messhugahId(), + communicationTemplate.medium(), + communicationTemplate.type())) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java new file mode 100644 index 00000000..31e03a42 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java @@ -0,0 +1,31 @@ +package fr.insee.pearljam.api.campaign.dto.input; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonInclude; + +import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignCreateDto; +import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; +import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.dto.referent.ReferentDto; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public record CampaignCreateDto ( + @NotBlank + String campaign, + @NotBlank + String campaignLabel, + @NotEmpty + @Valid + List visibilities, + List referents, + String email, + IdentificationConfiguration identificationConfiguration, + ContactOutcomeConfiguration contactOutcomeConfiguration, + ContactAttemptConfiguration contactAttemptConfiguration, + Boolean communicationRequestConfiguration) { +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java new file mode 100644 index 00000000..e53027cf --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java @@ -0,0 +1,35 @@ +package fr.insee.pearljam.api.campaign.dto.input; + +import com.fasterxml.jackson.annotation.JsonInclude; +import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignUpdateDto; +import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; +import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.dto.referent.ReferentDto; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; + +import java.util.List; + +/** + * A Data Transfer Object for updating campaign information. + * + * @param campaignLabel The label of the campaign. + * @param visibilities A list of visibility context DTOs. + * @param referents A list of referent DTOs. + * @param email The email associated with the campaign. + * @param identificationConfiguration The identification configuration of the campaign. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record CampaignUpdateDto( + @NotBlank + String campaignLabel, + @Valid + List visibilities, + List referents, + String email, + IdentificationConfiguration identificationConfiguration, + ContactOutcomeConfiguration contactOutcomeConfiguration, + ContactAttemptConfiguration contactAttemptConfiguration, + Boolean communicationRequestConfiguration +) {} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java new file mode 100644 index 00000000..07d15389 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java @@ -0,0 +1,35 @@ +package fr.insee.pearljam.api.campaign.dto.input; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import jakarta.validation.constraints.NotNull; + +import java.util.List; + +/** + * A class representing the communication template of a visibility. + * + * @param messhugahId The identifier for Messhugah + * @param medium The medium of communication + * @param type The type of communication + */ +public record CommunicationTemplateCreateDto( + @NotNull + String messhugahId, + @NotNull + CommunicationMedium medium, + @NotNull + CommunicationType type +) { + public static List toModel(List communicationTemplates) { + return communicationTemplates.stream() + .map(communicationTemplate -> + new CommunicationTemplate( + null, + communicationTemplate.messhugahId(), + communicationTemplate.medium(), + communicationTemplate.type())) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignCreateDto.java new file mode 100644 index 00000000..b8b77452 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignCreateDto.java @@ -0,0 +1,56 @@ +package fr.insee.pearljam.api.campaign.dto.input.visibility; + +import com.fasterxml.jackson.annotation.JsonInclude; + +import fr.insee.pearljam.api.campaign.dto.input.CommunicationTemplateCreateDto; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import java.util.List; + +/** + * A Data Transfer Object for representing visibility context information. + * + * @param collectionStartDate Collection start date of the visibility + * @param collectionEndDate Collection end date of the visibility + * @param identificationPhaseStartDate Identification phase start date of the visibility + * @param interviewerStartDate Interviewer start date of the visibility + * @param managementStartDate Manager start date of the visibility + * @param endDate End date of the visibility + * @param organizationalUnit Organizational unit of the visibility + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record VisibilityCampaignCreateDto( + @NotNull + Long managementStartDate, + @NotNull + Long interviewerStartDate, + @NotNull + Long identificationPhaseStartDate, + @NotNull + Long collectionStartDate, + @NotNull + Long collectionEndDate, + @NotNull + Long endDate, + @NotBlank + String organizationalUnit, + @Valid + List communicationTemplates +) { + + public static Visibility toModel(VisibilityCampaignCreateDto visibilityDto) { + return new Visibility(null, + visibilityDto.organizationalUnit(), + visibilityDto.managementStartDate(), + visibilityDto.interviewerStartDate(), + visibilityDto.identificationPhaseStartDate(), + visibilityDto.collectionStartDate(), + visibilityDto.collectionEndDate(), + visibilityDto.endDate(), + null + ); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignUpdateDto.java new file mode 100644 index 00000000..22e262d9 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignUpdateDto.java @@ -0,0 +1,54 @@ +package fr.insee.pearljam.api.campaign.dto.input.visibility; + +import com.fasterxml.jackson.annotation.JsonInclude; +import fr.insee.pearljam.api.web.exception.VisibilityInvalidException; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import jakarta.validation.constraints.NotBlank; + +import java.util.List; + +/** + * A Data Transfer Object for representing visibility information. + * + * @param collectionStartDate Collection start date of the visibility + * @param collectionEndDate Collection end date of the visibility + * @param identificationPhaseStartDate Identification phase start date of the visibility + * @param interviewerStartDate Interviewer start date of the visibility + * @param managementStartDate Manager start date of the visibility + * @param endDate End date of the visibility + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record VisibilityCampaignUpdateDto( + Long managementStartDate, + Long interviewerStartDate, + Long identificationPhaseStartDate, + Long collectionStartDate, + Long collectionEndDate, + Long endDate, + @NotBlank + String organizationalUnit +) { + public static final String AT_LEAST_ONE_DATE_REQUIRED_MESSAGE = "At least one date must be provided for a visibility"; + + public VisibilityCampaignUpdateDto { + if (managementStartDate == null && interviewerStartDate == null && identificationPhaseStartDate == null && + collectionStartDate == null && collectionEndDate == null && endDate == null) { + throw new VisibilityInvalidException(AT_LEAST_ONE_DATE_REQUIRED_MESSAGE); + } + } + + public static List toModel(List visibilitiesDto, String campaignId) { + return visibilitiesDto.stream() + .map(visibilityDto -> new Visibility(campaignId, + visibilityDto.organizationalUnit(), + visibilityDto.managementStartDate(), + visibilityDto.interviewerStartDate(), + visibilityDto.identificationPhaseStartDate(), + visibilityDto.collectionStartDate(), + visibilityDto.collectionEndDate(), + visibilityDto.endDate(), + null + )) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityUpdateDto.java new file mode 100644 index 00000000..936b3baf --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityUpdateDto.java @@ -0,0 +1,36 @@ +package fr.insee.pearljam.api.campaign.dto.input.visibility; + +import com.fasterxml.jackson.annotation.JsonInclude; +import fr.insee.pearljam.domain.campaign.model.Visibility; + +/** + * A Data Transfer Object for representing visibility information. + * + * @param collectionStartDate Collection start date of the visibility + * @param collectionEndDate Collection end date of the visibility + * @param identificationPhaseStartDate Identification phase start date of the visibility + * @param interviewerStartDate Interviewer start date of the visibility + * @param managementStartDate Manager start date of the visibility + * @param endDate End date of the visibility + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record VisibilityUpdateDto( + Long managementStartDate, + Long interviewerStartDate, + Long identificationPhaseStartDate, + Long collectionStartDate, + Long collectionEndDate, + Long endDate +) { + + public static Visibility toModel(VisibilityUpdateDto visibilityDto, String campaignId, String ouId) { + return new Visibility(campaignId, ouId, + visibilityDto.managementStartDate(), + visibilityDto.interviewerStartDate(), + visibilityDto.identificationPhaseStartDate(), + visibilityDto.collectionStartDate(), + visibilityDto.collectionEndDate(), + visibilityDto.endDate(), + null); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java new file mode 100644 index 00000000..e0c87f76 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java @@ -0,0 +1,50 @@ +package fr.insee.pearljam.api.campaign.dto.output; + +import com.fasterxml.jackson.annotation.JsonInclude; +import fr.insee.pearljam.api.campaign.dto.output.visibility.VisibilityCampaignDto; +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; +import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.dto.referent.ReferentDto; + +import java.util.List; + +/** + * A Data Transfer Object for representing campaign information. + * + * @param campaign The campaign identifier. + * @param campaignLabel The label of the campaign. + * @param visibilities A list of visibility DTOs. + * @param referents A list of referent DTOs. + * @param email The email associated with the campaign. + * @param identificationConfiguration The identification configuration of the campaign. + * @param contactOutcomeConfiguration The contact outcome configuration of the campaign. + * @param contactAttemptConfiguration The contact attempt configuration of the campaign. + * @param communicationRequestConfiguration The communication request configuration of the campaign. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record CampaignResponseDto( + String campaign, + String campaignLabel, + List visibilities, + List referents, + String email, + IdentificationConfiguration identificationConfiguration, + ContactOutcomeConfiguration contactOutcomeConfiguration, + ContactAttemptConfiguration contactAttemptConfiguration, + Boolean communicationRequestConfiguration +) { + public static CampaignResponseDto fromModel(Campaign campaignDB, List referents, List visibilities) { + return new CampaignResponseDto(campaignDB.getId(), + campaignDB.getLabel(), + visibilities, + referents, + campaignDB.getEmail(), + campaignDB.getIdentificationConfiguration(), + campaignDB.getContactOutcomeConfiguration(), + campaignDB.getContactAttemptConfiguration(), + campaignDB.getCommunicationConfiguration() + ); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/visibility/VisibilityCampaignDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/visibility/VisibilityCampaignDto.java new file mode 100644 index 00000000..5baa969d --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/visibility/VisibilityCampaignDto.java @@ -0,0 +1,30 @@ +package fr.insee.pearljam.api.campaign.dto.output.visibility; + +import fr.insee.pearljam.domain.campaign.model.Visibility; + +import java.util.List; + + +public record VisibilityCampaignDto( + String organizationalUnit, + Long managementStartDate, + Long interviewerStartDate, + Long identificationPhaseStartDate, + Long collectionStartDate, + Long collectionEndDate, + Long endDate) { + + public static List fromModel(List visibilities) { + return visibilities.stream() + .map(visibility -> new VisibilityCampaignDto( + visibility.organizationalUnitId(), + visibility.managementStartDate(), + visibility.interviewerStartDate(), + visibility.identificationPhaseStartDate(), + visibility.collectionStartDate(), + visibility.collectionEndDate(), + visibility.endDate() + )) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java b/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java index 15996f73..da1c5840 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java @@ -3,10 +3,21 @@ import java.util.List; import java.util.Optional; +import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; +import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.output.visibility.VisibilityCampaignDto; +import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityUpdateDto; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; -import org.apache.commons.lang3.StringUtils; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -18,20 +29,14 @@ import fr.insee.pearljam.api.domain.Campaign; import fr.insee.pearljam.api.domain.Interviewer; -import fr.insee.pearljam.api.domain.Response; -import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.api.dto.campaign.CampaignContextDto; +import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; import fr.insee.pearljam.api.dto.campaign.CampaignDto; import fr.insee.pearljam.api.dto.campaign.OngoingDto; import fr.insee.pearljam.api.dto.count.CountDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; import fr.insee.pearljam.api.dto.referent.ReferentDto; -import fr.insee.pearljam.api.dto.state.StateCountCampaignDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityContextDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityDto; -import fr.insee.pearljam.api.exception.NoOrganizationUnitException; import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.api.exception.VisibilityException; +import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; import fr.insee.pearljam.api.service.CampaignService; import fr.insee.pearljam.api.service.ReferentService; import io.swagger.v3.oas.annotations.Operation; @@ -44,35 +49,25 @@ @Tag(name = "01. Campaigns", description = "Endpoints for campaigns") @Slf4j @RequiredArgsConstructor +@Validated public class CampaignController { private final CampaignService campaignService; private final ReferentService referentService; private final AuthenticatedUserService authenticatedUserService; - private static final String NO_USER_ID = "No userId : access denied."; private static final String DEFAULT_FORCE_VALUE = "false"; /** - * This method is used to post the campaign defined in request body - * - * @return List of {@link SurveyUnit} if exist, {@link HttpStatus} NOT_FOUND, or - * {@link HttpStatus} FORBIDDEN + * This method is used to create a campaign + * @param campaignDto campaign to create */ - @Operation(summary = "Post Campaign") + @Operation(summary = "Create a Campaign") @PostMapping(path = Constants.API_CAMPAIGN) - public ResponseEntity postCampaign(@RequestBody CampaignContextDto campaignDto) { - String userId = authenticatedUserService.getCurrentUserId(); - Response response; - try { - response = campaignService.postCampaign(campaignDto); - } catch (NoOrganizationUnitException | VisibilityException e) { - log.error(e.getMessage()); - response = new Response(e.getMessage(), HttpStatus.BAD_REQUEST); - } - log.info("{} : POST /campaign resulting in {} with response [{}]", userId, response.getHttpStatus(), - response.getMessage()); - return new ResponseEntity<>(response.getMessage(), response.getHttpStatus()); + public void createCampaign(@Valid @NotNull @RequestBody CampaignCreateDto campaignDto) + throws CampaignAlreadyExistException, + CampaignNotFoundException, OrganizationalUnitNotFoundException { + campaignService.createCampaign(campaignDto); } /** @@ -133,7 +128,6 @@ public ResponseEntity> getInterviewerCampaigns() { * This method is used to get the list of interviewers associated with the * campaign {id} for current user * - * @param request * @param id * @return List of {@link Interviewer} if exist, {@link HttpStatus} NOT_FOUND, * or {@link HttpStatus} FORBIDDEN @@ -161,38 +155,25 @@ public ResponseEntity> getListInterviewers(@PathVariable(va * This method returns the list of visibilities associated with the * campaign {id} * - * @param request - * @param id - * @return List of {@link VisibilityContextDto} if exist, {@link HttpStatus} - * NOT_FOUND, - * or {@link HttpStatus} FORBIDDEN + * @param campaignId campaign id + * @return List of {@link VisibilityCampaignDto} */ @Operation(summary = "Get campaign visibilities") @GetMapping(path = Constants.API_CAMPAIGN_ID_VISIBILITIES) - public ResponseEntity> getVisibilities(@PathVariable(value = "id") String id) { + public List getVisibilities(@PathVariable(value = "id") String campaignId) throws CampaignNotFoundException { String userId = authenticatedUserService.getCurrentUserId(); - log.info("{} try to get campaign[{}] visibilities ", userId, id); - if (!campaignService.findById(id).isPresent()) { - log.warn("Can't find visibilities : campaign {} is missing", id); - return ResponseEntity.notFound().build(); - } - - List visibilities = campaignService.findAllVisiblitiesByCampaign(id); - - log.info("Get visibilities resulting in 200"); - return new ResponseEntity<>(visibilities, HttpStatus.OK); + log.info("{} try to get campaign[{}] visibilities ", userId, campaignId); + List visibilities = campaignService.findAllVisibilitiesByCampaign(campaignId); + return VisibilityCampaignDto.fromModel(visibilities); } /** * This method is used to count survey units that are abandoned by campaign * Return the sum of survey units states by campaign as a list - * - * @param request + * * @param id - * @param date - * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, - * or {@link HttpStatus} FORBIDDEN + * @return */ @Operation(summary = "Get numberSUAbandoned") @GetMapping(path = Constants.API_CAMPAIGN_ID_SU_ABANDONED) @@ -213,21 +194,18 @@ public ResponseEntity getNbSUAbandoned(@PathVariable(value = "id") Str /** * This method is used to count survey units that are not attributed by campaign - * - * @param request - * @param id - * @param date - * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, - * or {@link HttpStatus} FORBIDDEN + * + * @param campaignId campaign id + * @return */ @Operation(summary = "Get numberSUNotAttributed") @GetMapping(path = Constants.API_CAMPAIGN_ID_SU_NOTATTRIBUTED) - public ResponseEntity getNbSUNotAttributed(@PathVariable(value = "id") String id) { + public ResponseEntity getNbSUNotAttributed(@PathVariable(value = "id") String campaignId) { String userId = authenticatedUserService.getCurrentUserId(); - log.info("{} try to get campaign[{}] not attributed survey-units ", userId, id); + log.info("{} try to get campaign[{}] not attributed survey-units ", userId, campaignId); CountDto nbSUNotAttributed; try { - nbSUNotAttributed = campaignService.getNbSUNotAttributedByCampaign(userId, id); + nbSUNotAttributed = campaignService.getNbSUNotAttributedByCampaign(userId, campaignId); } catch (NotFoundException e) { log.info("Get numberSUAbandoned resulting in 404"); return new ResponseEntity<>(HttpStatus.NOT_FOUND); @@ -239,88 +217,83 @@ public ResponseEntity getNbSUNotAttributed(@PathVariable(value = "id") /** * Update the visibility dates for a given campaign and organizational unit - * - * @param request - * @param idCampaign - * @param idOu + * + * @param visibilityToUpdate the visibility to update + * @param idCampaign campaign identifier + * @param idOu organizational unit id + * @throws VisibilityNotFoundException if the visibility does not exist */ @Operation(summary = "Change visibility of a campaign for an Organizational Unit") @PutMapping(path = Constants.API_CAMPAIGN_ID_OU_ID_VISIBILITY) - public ResponseEntity putVisibilityDate( - @RequestBody VisibilityDto visibilityUpdated, - @PathVariable(value = "idCampaign") String idCampaign, - @PathVariable(value = "idOu") String idOu) { + public void updateVisibility( + @Valid @NotNull @RequestBody VisibilityUpdateDto visibilityToUpdate, + @NotBlank @PathVariable(value = "idCampaign") String idCampaign, + @NotBlank @PathVariable(value = "idOu") String idOu) throws VisibilityNotFoundException { String userId = authenticatedUserService.getCurrentUserId(); log.info("{} try to change OU[{}] visibility on campaign[{}] ", userId, idOu, idCampaign); - HttpStatus returnCode = campaignService.updateVisibility(idCampaign, idOu, visibilityUpdated); - log.info("PUT visibility with CampaignId {} for Organizational Unit {} resulting in {}", idCampaign, - idOu, returnCode.value()); - return new ResponseEntity<>(returnCode); - + campaignService.updateVisibility(VisibilityUpdateDto.toModel(visibilityToUpdate, idCampaign, idOu)); + log.info("Visibility with CampaignId {} for Organizational Unit {} updated", idCampaign, + idOu); } /** * This method deletes a campaign * - * @param campaign the value to delete + * @param campaignId the value to delete * @return {@link HttpStatus} * */ @Operation(summary = "Delete a campaign") @DeleteMapping(path = Constants.API_CAMPAIGN_ID) public ResponseEntity deleteCampaignById( - @PathVariable(value = "id") String id, - @RequestParam(required = false, defaultValue = DEFAULT_FORCE_VALUE) Boolean force) { + @PathVariable(value = "id") String campaignId, + @RequestParam(required = false, defaultValue = DEFAULT_FORCE_VALUE) Boolean force) throws CampaignNotFoundException { String userId = authenticatedUserService.getCurrentUserId(); - log.info("{} try to delete campaign {}", userId, id); + log.info("{} try to delete campaign {}", userId, campaignId); - Optional campaignOptional = campaignService.findById(id); + Optional campaignOptional = campaignService.findById(campaignId); if (!campaignOptional.isPresent()) { - log.error("DELETE campaign with id {} resulting in 404 because it does not exists", id); + log.error("DELETE campaign with id {} resulting in 404 because it does not exists", campaignId); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - if (Boolean.FALSE.equals(force) && campaignService.isCampaignOngoing(id)) { - String errorMessage = String.format("Campaign %s is on-going and can't be deleted", id); + if (Boolean.FALSE.equals(force) && campaignService.isCampaignOngoing(campaignId)) { + String errorMessage = String.format("Campaign %s is on-going and can't be deleted", campaignId); log.info(errorMessage); return ResponseEntity.status(HttpStatus.CONFLICT).body(errorMessage); } campaignService.delete(campaignOptional.get()); - log.info("DELETE campaign with id {} resulting in 200", id); + log.info("DELETE campaign with id {} resulting in 200", campaignId); return ResponseEntity.ok().build(); } /** * Updates the collection start and end dates for a campaign - * - * @body CampaignDto - * @param id - * @return {@link HttpStatus} + * @param id campaign id + * @param campaign campaign to update */ @Operation(summary = "Update campaign (label, email, configurations, visibilities") @PutMapping(path = Constants.API_CAMPAIGN_ID) - public ResponseEntity putCampaign(@PathVariable(value = "id") String id, - @RequestBody CampaignContextDto campaign) { + public void updateCampaign(@NotBlank @PathVariable(value = "id") String id, + @Valid @NotNull @RequestBody CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException { String userId = authenticatedUserService.getCurrentUserId(); log.info("{} try to update campaign {} collection dates", userId, id); - HttpStatus returnCode = campaignService.updateCampaign(id, campaign); - log.info("PUT campaign with id {} resulting in {}", id, returnCode.value()); - return new ResponseEntity<>(returnCode); + campaignService.updateCampaign(id, campaign); + log.info("Campaign with id {} updated", id); } /** * This method returns campaign ongoing status * - * @param request * @param id * @return {@link OngoingDto} , {@link HttpStatus} NOT_FOUND, * or {@link HttpStatus} FORBIDDEN */ @Operation(summary = "Check if campaign is on-going") @GetMapping(path = Constants.API_CAMPAIGNS_ID_ON_GOING) - public ResponseEntity isOngoing(@PathVariable(value = "id") String id) { + public ResponseEntity isOngoing(@PathVariable(value = "id") String id) throws CampaignNotFoundException { String userId = authenticatedUserService.getCurrentUserId(); log.info("{} check if {} is on-going", userId, id); @@ -338,25 +311,15 @@ public ResponseEntity isOngoing(@PathVariable(value = "id") String i /** * This method returns target campaign * - * @param request - * @param id - * @return {@link CampaignContextDto} , {@link HttpStatus} NOT_FOUND, - * or {@link HttpStatus} FORBIDDEN + * @param campaignId campaign id + * @return {@link CampaignResponseDto} the campaign */ @Operation(summary = "Get target campaign") @GetMapping(path = Constants.API_CAMPAIGN_ID) - public ResponseEntity getCampaign(@PathVariable(value = "id") String id) { + public CampaignResponseDto getCampaign(@NotBlank @PathVariable(value = "id") String campaignId) throws CampaignNotFoundException { String userId = authenticatedUserService.getCurrentUserId(); - log.info("{} try to GET {}", userId, id); - - if (!campaignService.findById(id).isPresent()) { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - - CampaignContextDto campaign = campaignService.getCampaignDtoById(id); - - log.info("{} GET campaign {} : {}", userId, id, HttpStatus.OK.toString()); - return new ResponseEntity<>(campaign, HttpStatus.OK); + log.info("{} try to GET {}", userId, campaignId); + return campaignService.getCampaignDtoById(campaignId); } // API for REFERENT entity diff --git a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java index 5731796a..d1695dc1 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java @@ -69,7 +69,7 @@ public class Campaign implements Serializable { * The reference to visibility table */ @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, orphanRemoval = true) - private List visibilities; + private List visibilities; @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, orphanRemoval = true) private List referents; @@ -86,5 +86,4 @@ public Campaign(String id, String label, IdentificationConfiguration identConfig this.email = email; this.communicationConfiguration = Optional.ofNullable(communicationConfiguration).orElse(false); } - } diff --git a/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java b/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java index 5deb9985..f4e9a363 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java +++ b/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java @@ -61,7 +61,7 @@ public class OrganizationUnit implements Serializable { * The visibilites of the OrganizationUnit */ @OneToMany(mappedBy = "organizationUnit", cascade = CascadeType.ALL, orphanRemoval = true) - private List visibilities; + private List visibilities; public OrganizationUnit(String id, String label, OrganizationUnitType type) { super(); diff --git a/src/main/java/fr/insee/pearljam/api/domain/Visibility.java b/src/main/java/fr/insee/pearljam/api/domain/Visibility.java deleted file mode 100644 index 939ec852..00000000 --- a/src/main/java/fr/insee/pearljam/api/domain/Visibility.java +++ /dev/null @@ -1,102 +0,0 @@ -package fr.insee.pearljam.api.domain; - -import java.io.Serializable; - -import fr.insee.pearljam.api.dto.visibility.VisibilityDto; -import jakarta.persistence.EmbeddedId; -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.Table; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -/** - * Entity Visibility : represent the entity table in DB - * - * @author Corcaud Samuel - * - */ -@Entity -@Table -@NoArgsConstructor -@Getter -@Setter -public class Visibility implements Serializable { - - private static final long serialVersionUID = 1L; - - @EmbeddedId - private VisibilityId visibilityId; - /** - * The organizationUnit associated to Visibility - */ - @ManyToOne(fetch = FetchType.LAZY) - // @MapsId("organization_unit_id") - @JoinColumn(name = "organization_unit_id", referencedColumnName = "id", insertable = false, updatable = false) - private OrganizationUnit organizationUnit; - - /** - * The Campaign associated to Visibility - */ - - @ManyToOne(fetch = FetchType.LAZY) - // @MapsId("campaign_id") - @JoinColumn(name = "campaign_id", referencedColumnName = "id", insertable = false, updatable = false) - private Campaign campaign; - - /** - * The start date of Visibility of management - */ - private Long managementStartDate; - - /** - * The start date of Visibility of interviewer - */ - private Long interviewerStartDate; - - /** - * The start date of identification phase - */ - private Long identificationPhaseStartDate; - - /** - * The start date of collection - */ - private Long collectionStartDate; - - /** - * The end date of collection - */ - private Long collectionEndDate; - - /** - * The end date - */ - private Long endDate; - - public Visibility(VisibilityDto vis) { - super(); - this.collectionEndDate = vis.getCollectionEndDate(); - this.collectionStartDate = vis.getCollectionStartDate(); - this.endDate = vis.getEndDate(); - this.identificationPhaseStartDate = vis.getIdentificationPhaseStartDate(); - this.interviewerStartDate = vis.getInterviewerStartDate(); - this.managementStartDate = vis.getManagementStartDate(); - } - - public Visibility(Long managerStartDate, Long interviewerStartDate, Long identificationPhaseStartDate, - Long collectionstartDate, Long collectionEndDate, Long endDate, Campaign campaign, OrganizationUnit ou) { - this.collectionStartDate = collectionstartDate; - this.collectionEndDate = collectionEndDate; - this.identificationPhaseStartDate = identificationPhaseStartDate; - this.interviewerStartDate = interviewerStartDate; - this.managementStartDate = managerStartDate; - this.endDate = endDate; - this.campaign = campaign; - this.organizationUnit = ou; - this.visibilityId = new VisibilityId(ou.getId(), campaign.getId()); - } -} diff --git a/src/main/java/fr/insee/pearljam/api/domain/VisibilityDB.java b/src/main/java/fr/insee/pearljam/api/domain/VisibilityDB.java new file mode 100644 index 00000000..9db8a9ef --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/domain/VisibilityDB.java @@ -0,0 +1,104 @@ +package fr.insee.pearljam.api.domain; + +import java.io.Serializable; +import java.util.List; + +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + +@Entity(name = "visibility") +@Table +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@Slf4j +public class VisibilityDB implements Serializable { + + private static final long serialVersionUID = 1L; + + @EmbeddedId + private VisibilityDBId visibilityId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "organization_unit_id", insertable = false, updatable = false) + private OrganizationUnit organizationUnit; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "campaign_id", insertable = false, updatable = false) + private Campaign campaign; + + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "visibility", cascade = CascadeType.ALL, orphanRemoval = true) + private List communicationTemplates; + + private Long managementStartDate; + private Long interviewerStartDate; + private Long identificationPhaseStartDate; + private Long collectionStartDate; + private Long collectionEndDate; + private Long endDate; + + public void updateDates(Visibility visibilityToUpdate) { + String ouId = visibilityToUpdate.organizationalUnitId(); + String campaignId = visibilityToUpdate.campaignId(); + if (visibilityToUpdate.managementStartDate() != null) { + log.info("Updating management start date for campaign {} and Organizational Unit {}", campaignId, ouId); + this.setManagementStartDate(visibilityToUpdate.managementStartDate()); + } + if (visibilityToUpdate.interviewerStartDate() != null) { + log.info("Updating interviewer start date for campaign {} and Organizational Unit {}", campaignId, ouId); + this.setInterviewerStartDate(visibilityToUpdate.interviewerStartDate()); + } + if (visibilityToUpdate.identificationPhaseStartDate() != null) { + log.info("Updating identification phase start date for campaign {} and Organizational Unit {}", campaignId, ouId); + this.setIdentificationPhaseStartDate(visibilityToUpdate.identificationPhaseStartDate()); + } + if (visibilityToUpdate.collectionStartDate() != null) { + log.info("Updating collection start date for campaign {} and Organizational Unit {}", campaignId, ouId); + this.setCollectionStartDate(visibilityToUpdate.collectionStartDate()); + } + if (visibilityToUpdate.collectionEndDate() != null) { + log.info("Updating collection end date for campaign {} and Organizational Unit {}", campaignId, ouId); + this.setCollectionEndDate(visibilityToUpdate.collectionEndDate()); + } + if (visibilityToUpdate.endDate() != null) { + log.info("Updating end date for campaign {} and Organizational Unit {}", campaignId, ouId); + this.setEndDate(visibilityToUpdate.endDate()); + } + } + + public static VisibilityDB fromModel(Visibility visibility, Campaign campaign, OrganizationUnit organizationUnit) { + VisibilityDBId id = new VisibilityDBId(organizationUnit.getId(), campaign.getId()); + return new VisibilityDB(id, + organizationUnit, campaign, + CommunicationTemplateDB.fromModel(visibility.communicationTemplates()), + visibility.managementStartDate(), visibility.interviewerStartDate(), visibility.identificationPhaseStartDate(), + visibility.collectionStartDate(), visibility.collectionEndDate(), visibility.endDate()); + } + + public static Visibility toModel(VisibilityDB visibilityDB) { + return new Visibility( + visibilityDB.getVisibilityId().getCampaignId(), + visibilityDB.getVisibilityId().getOrganizationUnitId(), + visibilityDB.getManagementStartDate(), + visibilityDB.getInterviewerStartDate(), + visibilityDB.getIdentificationPhaseStartDate(), + visibilityDB.getCollectionStartDate(), + visibilityDB.getCollectionEndDate(), + visibilityDB.getEndDate(), + CommunicationTemplateDB.toModel(visibilityDB.getCommunicationTemplates())); + } + + public static List toModel(List visibilityDBs) { + return visibilityDBs.stream() + .map(VisibilityDB::toModel) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/domain/VisibilityId.java b/src/main/java/fr/insee/pearljam/api/domain/VisibilityDBId.java similarity index 92% rename from src/main/java/fr/insee/pearljam/api/domain/VisibilityId.java rename to src/main/java/fr/insee/pearljam/api/domain/VisibilityDBId.java index 9e6661c6..e8a1189f 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/VisibilityId.java +++ b/src/main/java/fr/insee/pearljam/api/domain/VisibilityDBId.java @@ -20,7 +20,7 @@ @AllArgsConstructor @Getter @Setter -public class VisibilityId implements Serializable { +public class VisibilityDBId implements Serializable { private static final long serialVersionUID = 1L; diff --git a/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignContextDto.java b/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignContextDto.java deleted file mode 100644 index 22c75443..00000000 --- a/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignContextDto.java +++ /dev/null @@ -1,101 +0,0 @@ -package fr.insee.pearljam.api.dto.campaign; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonInclude; - -import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; -import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; -import fr.insee.pearljam.api.domain.IdentificationConfiguration; -import fr.insee.pearljam.api.dto.referent.ReferentDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityContextDto; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class CampaignContextDto { - private String campaign; - private String campaignLabel; - private List visibilities; - private List referents; - private String email; - private IdentificationConfiguration identificationConfiguration; - private ContactOutcomeConfiguration contactOutcomeConfiguration; - private ContactAttemptConfiguration contactAttemptConfiguration; - private Boolean communicationRequestConfiguration; - - public CampaignContextDto() { - super(); - } - - public String getCampaign() { - return campaign; - } - - public void setCampaign(String campaign) { - this.campaign = campaign; - } - - public String getCampaignLabel() { - return campaignLabel; - } - - public void setCampaignLabel(String campaignLabel) { - this.campaignLabel = campaignLabel; - } - - public List getVisibilities() { - return visibilities; - } - - public void setVisibilities(List visibilities) { - this.visibilities = visibilities; - } - - public IdentificationConfiguration getIdentificationConfiguration() { - return this.identificationConfiguration; - } - - public void setIdentificationConfiguration(IdentificationConfiguration identificationConfiguration) { - this.identificationConfiguration = identificationConfiguration; - } - - public ContactOutcomeConfiguration getContactOutcomeConfiguration() { - return this.contactOutcomeConfiguration; - } - - public void setContactOutcomeConfiguration(ContactOutcomeConfiguration contactOutcomeConfiguration) { - this.contactOutcomeConfiguration = contactOutcomeConfiguration; - } - - public ContactAttemptConfiguration getContactAttemptConfiguration() { - return this.contactAttemptConfiguration; - } - - public void setContactAttemptConfiguration(ContactAttemptConfiguration contactAttemptConfiguration) { - this.contactAttemptConfiguration = contactAttemptConfiguration; - } - - public List getReferents() { - return this.referents; - } - - public void setReferents(List referents) { - this.referents = referents; - } - - public String getEmail() { - return this.email; - } - - public void setEmail(String email) { - this.email = email; - } - - public Boolean getCommunicationRequestConfiguration() { - return communicationRequestConfiguration; - } - - public void setCommunicationRequestConfiguration(Boolean communicationRequestConfiguration) { - this.communicationRequestConfiguration = communicationRequestConfiguration; - } - -} diff --git a/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java b/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java index 77caeca4..6b82ea40 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java @@ -84,5 +84,4 @@ public void setCampaignStats(List obj) { this.toFollowUp = 0L; } } - } diff --git a/src/main/java/fr/insee/pearljam/api/dto/referent/ReferentDto.java b/src/main/java/fr/insee/pearljam/api/dto/referent/ReferentDto.java index 79a185ac..23f45131 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/referent/ReferentDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/referent/ReferentDto.java @@ -1,11 +1,12 @@ package fr.insee.pearljam.api.dto.referent; import fr.insee.pearljam.api.domain.Referent; +import lombok.Data; /** * ReferentDto */ - +@Data public class ReferentDto { private String firstName; @@ -32,37 +33,4 @@ public ReferentDto(Referent ref) { this.phoneNumber = ref.getPhoneNumber(); this.role = ref.getRole(); } - - public String getFirstName() { - return this.firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return this.lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getPhoneNumber() { - return this.phoneNumber; - } - - public void setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - } - - public String getRole() { - return this.role; - } - - public void setRole(String role) { - this.role = role; - } - } \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java index 345cc41c..60569f8b 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java @@ -2,7 +2,6 @@ import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonInclude; @@ -13,9 +12,13 @@ import fr.insee.pearljam.api.dto.address.AddressDto; import fr.insee.pearljam.api.dto.campaign.CampaignDto; import fr.insee.pearljam.api.dto.person.PersonDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityDto; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitVisibilityDto; +import lombok.Getter; +import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) +@Getter +@Setter public class SurveyUnitDto { /** * Id of the SurveyUnit @@ -74,16 +77,16 @@ public class SurveyUnitDto { public SurveyUnitDto() { } - public SurveyUnitDto(SurveyUnit su, VisibilityDto visibility, Boolean extended) { + public SurveyUnitDto(SurveyUnit su, SurveyUnitVisibilityDto visibility, Boolean extended) { this.id = su.getId(); this.campaign = su.getCampaign().getId(); this.campaignLabel = su.getCampaign().getLabel(); - this.managementStartDate = visibility.getManagementStartDate(); - this.interviewerStartDate = visibility.getInterviewerStartDate(); - this.identificationPhaseStartDate = visibility.getIdentificationPhaseStartDate(); - this.collectionStartDate = visibility.getCollectionStartDate(); - this.collectionEndDate = visibility.getCollectionEndDate(); - this.endDate = visibility.getEndDate(); + this.managementStartDate = visibility.managementStartDate(); + this.interviewerStartDate = visibility.interviewerStartDate(); + this.identificationPhaseStartDate = visibility.identificationPhaseStartDate(); + this.collectionStartDate = visibility.collectionStartDate(); + this.collectionEndDate = visibility.collectionEndDate(); + this.endDate = visibility.endDate(); this.identificationConfiguration = su.getCampaign().getIdentificationConfiguration(); this.contactAttemptConfiguration = su.getCampaign().getContactAttemptConfiguration(); this.contactOutcomeConfiguration = su.getCampaign().getContactOutcomeConfiguration(); @@ -91,207 +94,26 @@ public SurveyUnitDto(SurveyUnit su, VisibilityDto visibility, Boolean extended) .orElse(false); if (Boolean.TRUE.equals(extended)) { this.persons = su.getPersons().stream() - .map(person -> new PersonDto(person)) - .collect(Collectors.toList()); + .map(PersonDto::new) + .toList(); this.address = new AddressDto(su.getAddress()); } } - public SurveyUnitDto(String idSurveyUnit, CampaignDto campaign, VisibilityDto visibility) { + public SurveyUnitDto(String idSurveyUnit, CampaignDto campaign, SurveyUnitVisibilityDto visibility) { this.id = idSurveyUnit; this.campaign = campaign.getId(); this.campaignLabel = campaign.getLabel(); - this.managementStartDate = visibility.getManagementStartDate(); - this.interviewerStartDate = visibility.getInterviewerStartDate(); - this.identificationPhaseStartDate = visibility.getIdentificationPhaseStartDate(); - this.collectionStartDate = visibility.getCollectionStartDate(); - this.collectionEndDate = visibility.getCollectionEndDate(); - this.endDate = visibility.getEndDate(); + this.managementStartDate = visibility.managementStartDate(); + this.interviewerStartDate = visibility.interviewerStartDate(); + this.identificationPhaseStartDate = visibility.identificationPhaseStartDate(); + this.collectionStartDate = visibility.collectionStartDate(); + this.collectionEndDate = visibility.collectionEndDate(); + this.endDate = visibility.endDate(); this.identificationConfiguration = campaign.getIdentificationConfiguration(); this.contactAttemptConfiguration = campaign.getContactAttemptConfiguration(); this.contactOutcomeConfiguration = campaign.getContactOutcomeConfiguration(); this.communicationRequestConfiguration = Optional.of(campaign.getCommunicationRequestConfiguration()) .orElse(false); } - - /** - * @return the id - */ - public String getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } - - /** - * @return the idCampaign - */ - public String getCampaign() { - return campaign; - } - - /** - * @param idCampaign the idCampaign to set - */ - public void setCampaign(String campaign) { - this.campaign = campaign; - } - - /** - * @return the labelCampaign - */ - public String getCampaignLabel() { - return campaignLabel; - } - - /** - * @param labelCampaign the labelCampaign to set - */ - public void setCampaignLabel(String campaignLabel) { - this.campaignLabel = campaignLabel; - } - - /** - * @return the managementStartDate - */ - public Long getManagementStartDate() { - return managementStartDate; - } - - /** - * @param managementStartDate the managementStartDate to set - */ - public void setManagementStartDate(Long managementStartDate) { - this.managementStartDate = managementStartDate; - } - - /** - * @return the interviewerStartDate - */ - public Long getInterviewerStartDate() { - return interviewerStartDate; - } - - /** - * @param interviewerStartDate the interviewerStartDate to set - */ - public void setInterviewerStartDate(Long interviewerStartDate) { - this.interviewerStartDate = interviewerStartDate; - } - - /** - * @return the identificationPhaseStartDate - */ - public Long getIdentificationPhaseStartDate() { - return identificationPhaseStartDate; - } - - /** - * @param identificationPhaseStartDate the identificationPhaseStartDate to set - */ - public void setIdentificationPhaseStartDate(Long identificationPhaseStartDate) { - this.identificationPhaseStartDate = identificationPhaseStartDate; - } - - /** - * @return the collectionStartDate - */ - public Long getCollectionStartDate() { - return collectionStartDate; - } - - /** - * @param collectionStartDate the collectionStartDate to set - */ - public void setCollectionStartDate(Long collectionStartDate) { - this.collectionStartDate = collectionStartDate; - } - - /** - * @return the collectionEndDate - */ - public Long getCollectionEndDate() { - return collectionEndDate; - } - - /** - * @param collectionEndDate the collectionEndDate to set - */ - public void setCollectionEndDate(Long collectionEndDate) { - this.collectionEndDate = collectionEndDate; - } - - /** - * @return the endDate - */ - public Long getEndDate() { - return endDate; - } - - /** - * @param endDate the endDate to set - */ - public void setEndDate(Long endDate) { - this.endDate = endDate; - } - - public List getPersons() { - return persons; - } - - public void setPersons(List persons) { - this.persons = persons; - } - - /** - * @return the address - */ - public AddressDto getAddress() { - return address; - } - - /** - * @param address the address to set - */ - public void setAddress(AddressDto address) { - this.address = address; - } - - public IdentificationConfiguration getIdentificationConfiguration() { - return this.identificationConfiguration; - } - - public void setIdentificationConfiguration(IdentificationConfiguration identificationConfiguration) { - this.identificationConfiguration = identificationConfiguration; - } - - public ContactOutcomeConfiguration getContactOutcomeConfiguration() { - return this.contactOutcomeConfiguration; - } - - public void setContactOutcomeConfiguration(ContactOutcomeConfiguration contactOutcomeConfiguration) { - this.contactOutcomeConfiguration = contactOutcomeConfiguration; - } - - public ContactAttemptConfiguration getContactAttemptConfiguration() { - return this.contactAttemptConfiguration; - } - - public void setContactAttemptConfiguration(ContactAttemptConfiguration contactAttemptConfiguration) { - this.contactAttemptConfiguration = contactAttemptConfiguration; - } - - public boolean isCommunicationRequestConfiguration() { - return communicationRequestConfiguration; - } - - public void setCommunicationRequestConfiguration(boolean communicationRequestConfiguration) { - this.communicationRequestConfiguration = communicationRequestConfiguration; - } - } diff --git a/src/main/java/fr/insee/pearljam/api/dto/visibility/VisibilityContextDto.java b/src/main/java/fr/insee/pearljam/api/dto/visibility/VisibilityContextDto.java deleted file mode 100644 index fe91d6c7..00000000 --- a/src/main/java/fr/insee/pearljam/api/dto/visibility/VisibilityContextDto.java +++ /dev/null @@ -1,38 +0,0 @@ -package fr.insee.pearljam.api.dto.visibility; - -import com.fasterxml.jackson.annotation.JsonInclude; - -import fr.insee.pearljam.api.domain.Visibility; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class VisibilityContextDto extends VisibilityDto { - - /** - * Organizational unit of the visibility - */ - private String organizationalUnit; - - public VisibilityContextDto() { - super(); - } - - public VisibilityContextDto(Visibility visibility) { - super(); - setManagementStartDate(visibility.getManagementStartDate()); - setInterviewerStartDate(visibility.getInterviewerStartDate()); - setIdentificationPhaseStartDate(visibility.getIdentificationPhaseStartDate()); - setCollectionStartDate(visibility.getCollectionStartDate()); - setCollectionEndDate(visibility.getCollectionEndDate()); - setEndDate(visibility.getEndDate()); - setOrganizationalUnit(visibility.getOrganizationUnit().getId()); - } - - public String getOrganizationalUnit() { - return organizationalUnit; - } - - public void setOrganizationalUnit(String organizationalUnit) { - this.organizationalUnit = organizationalUnit; - } - -} diff --git a/src/main/java/fr/insee/pearljam/api/dto/visibility/VisibilityDto.java b/src/main/java/fr/insee/pearljam/api/dto/visibility/VisibilityDto.java deleted file mode 100644 index fb731106..00000000 --- a/src/main/java/fr/insee/pearljam/api/dto/visibility/VisibilityDto.java +++ /dev/null @@ -1,144 +0,0 @@ -package fr.insee.pearljam.api.dto.visibility; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class VisibilityDto { - - /** - * Collection start date of the visibility - */ - private Long collectionStartDate; - - /** - * Collection end date of the visibility - */ - private Long collectionEndDate; - - /** - * Identification phase start date of the visibility - */ - private Long identificationPhaseStartDate; - - /** - * interviewer start date of the visibility - */ - private Long interviewerStartDate; - - /** - * Manager start date of the visibility - */ - private Long managementStartDate; - - /** - * End date of the visibility - */ - private Long endDate; - - public VisibilityDto(Long managerStartDate, Long interviewerStartDate, Long identificationPhaseStartDate, - Long collectionstartDate, Long collectionEndDate, Long endDate) { - super(); - this.collectionStartDate = collectionstartDate; - this.collectionEndDate = collectionEndDate; - this.identificationPhaseStartDate = identificationPhaseStartDate; - this.interviewerStartDate = interviewerStartDate; - this.managementStartDate = managerStartDate; - this.endDate = endDate; - } - - public VisibilityDto() { - super(); - } - - /** - * @return the collectionstartDate - */ - public Long getCollectionStartDate() { - return collectionStartDate; - } - - /** - * @param collectionstartDate the collectionstartDate to set - */ - public void setCollectionStartDate(Long collectionstartDate) { - this.collectionStartDate = collectionstartDate; - } - - /** - * @return the collectionEndDate - */ - public Long getCollectionEndDate() { - return collectionEndDate; - } - - /** - * @param collectionEndDate the collectionEndDate to set - */ - public void setCollectionEndDate(Long collectionEndDate) { - this.collectionEndDate = collectionEndDate; - } - - /** - * @return the identificationPhaseStartDate - */ - public Long getIdentificationPhaseStartDate() { - return identificationPhaseStartDate; - } - - /** - * @param identificationPhaseStartDate the identificationPhaseStartDate to set - */ - public void setIdentificationPhaseStartDate(Long identificationPhaseStartDate) { - this.identificationPhaseStartDate = identificationPhaseStartDate; - } - - /** - * @return the interviewerStartDate - */ - public Long getInterviewerStartDate() { - return interviewerStartDate; - } - - /** - * @param interviewerStartDate the interviewerStartDate to set - */ - public void setInterviewerStartDate(Long interviewerStartDate) { - this.interviewerStartDate = interviewerStartDate; - } - - /** - * @return the managerStartDate - */ - public Long getManagementStartDate() { - return managementStartDate; - } - - /** - * @param managementStartDate the managerStartDate to set - */ - public void setManagementStartDate(Long managementStartDate) { - this.managementStartDate = managementStartDate; - } - - /** - * @return the endDate - */ - public Long getEndDate() { - return endDate; - } - - /** - * @param endDate the endDate to set - */ - public void setEndDate(Long endDate) { - this.endDate = endDate; - } - - @JsonIgnore - public boolean isOneDateFilled() { - return collectionStartDate != null || collectionEndDate != null || identificationPhaseStartDate != null - || interviewerStartDate != null || managementStartDate != null || endDate != null; - } - -} diff --git a/src/main/java/fr/insee/pearljam/api/exception/VisibilityException.java b/src/main/java/fr/insee/pearljam/api/exception/VisibilityException.java deleted file mode 100644 index fdec9da4..00000000 --- a/src/main/java/fr/insee/pearljam/api/exception/VisibilityException.java +++ /dev/null @@ -1,16 +0,0 @@ -package fr.insee.pearljam.api.exception; - -public class VisibilityException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 1586775327256406489L; - - public VisibilityException(String message) { - super(message); - } - - - -} diff --git a/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java b/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java index be0ead38..741bce07 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java @@ -80,7 +80,7 @@ public interface CampaignRepository extends JpaRepository { @Query("SELECT new fr.insee.pearljam.api.dto.message.VerifyNameResponseDto(camp.id, 'campaign', camp.label) " + "FROM Campaign camp " - + "INNER JOIN Visibility vi ON vi.campaign.id = camp.id " + + "JOIN camp.visibilities vi " + "WHERE (" + "vi.organizationUnit.id in (:ouIds) " + "OR 'GUEST' in (:ouIds) " @@ -96,12 +96,4 @@ public interface CampaignRepository extends JpaRepository { + "GROUP BY camp.id ") List findMatchingCampaigns(@Param("text") String text, @Param("ouIds") List ouIds, @Param("date") Long date, Pageable pageable); - - @Query("SELECT new fr.insee.pearljam.api.dto.message.VerifyNameResponseDto(camp.id, 'campaign', camp.label) " - + "FROM Campaign camp " - + "INNER JOIN Visibility vi ON vi.campaign.id = camp.id " - + "WHERE vi.organizationUnit.id in (:ouIds) OR 'GUEST' in (:ouIds) " - + "GROUP BY camp.id ") - List findMatchingCampaignsByOuForAll(@Param("ouIds") List ouIds); - } diff --git a/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java b/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java index c1899be8..882beeef 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java @@ -69,7 +69,7 @@ public interface SurveyUnitRepository extends JpaRepository @Query(value="SELECT su FROM SurveyUnit su " + - "WHERE EXISTS (SELECT vi FROM Visibility vi " + + "WHERE EXISTS (SELECT vi FROM VisibilityDB vi " + "WHERE vi.campaign.id = su.campaign.id " + "AND vi.organizationUnit.id = su.organizationUnit.id " + "AND vi.collectionEndDate < ?1 " + @@ -86,7 +86,7 @@ public interface SurveyUnitRepository extends JpaRepository // in campaign with expected IdentificationConfiguration "AND su.campaign.identificationConfiguration = :config " + // in processing phase - "AND EXISTS (SELECT vi FROM Visibility vi " + + "AND EXISTS (SELECT vi FROM VisibilityDB vi " + "WHERE vi.campaign.id = su.campaign.id " + "AND vi.organizationUnit.id = su.organizationUnit.id " + "AND vi.collectionEndDate < :date " + diff --git a/src/main/java/fr/insee/pearljam/api/repository/VisibilityRepository.java b/src/main/java/fr/insee/pearljam/api/repository/VisibilityRepository.java deleted file mode 100644 index 03271c2e..00000000 --- a/src/main/java/fr/insee/pearljam/api/repository/VisibilityRepository.java +++ /dev/null @@ -1,63 +0,0 @@ -package fr.insee.pearljam.api.repository; - -import java.util.List; -import java.util.Optional; - -import org.springframework.data.repository.query.Param; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; - -import fr.insee.pearljam.api.domain.Visibility; -import fr.insee.pearljam.api.domain.VisibilityId; -import fr.insee.pearljam.api.dto.visibility.VisibilityDto; - -public interface VisibilityRepository extends JpaRepository { - - @Query(value = "SELECT * " - + "FROM visibility " - + "WHERE campaign_id=?1 AND organization_unit_id=?2", nativeQuery = true) - Optional findVisibilityByCampaignIdAndOuId(String campaignId, String organizationalUnitId); - - @Query(value = "SELECT * " - + "FROM visibility " - + "WHERE campaign_id=?1 AND organization_unit_id=?2 " - + "AND management_start_date<=?3 " - + "AND collection_start_date<=?3 " - + "AND collection_end_date>?3", nativeQuery = true) - Optional findVisibilityInCollectionPeriod(String campaignId, String organizationalUnitId, Long date); - - @Query(value = "SELECT * " - + "FROM visibility " - + "WHERE campaign_id=:campaignId AND organization_unit_id IN (:ouIds) " - + "AND management_start_date<=:date " - + "AND collection_start_date<=:date " - + "AND collection_end_date>:date", nativeQuery = true) - List findVisibilityInCollectionPeriodForOUs(@Param("campaignId") String campaignId, - @Param("ouIds") List ouIds, - @Param("date") Long date); - - @Query(value = "SELECT new fr.insee.pearljam.api.dto.visibility.VisibilityDto(vi.managementStartDate, vi.interviewerStartDate, vi.identificationPhaseStartDate, vi.collectionStartDate, vi.collectionEndDate, vi.endDate) " - + "FROM Visibility vi " - + "INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id " - + "WHERE su.id=?1 AND su.organizationUnit.id = vi.organizationUnit.id") - VisibilityDto findVisibilityBySurveyUnitId(String surveyUnitId); - - @Query(value = "SELECT vi " - + "FROM Visibility vi " - + "INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id " - + "WHERE su.organizationUnit.id = vi.organizationUnit.id " - + "AND su.id IN (:SUids)") - List findAllVisibilityBySurveyUnitIds(@Param("SUids") List surveyUnitIds); - - @Query(value = "SELECT new fr.insee.pearljam.api.dto.visibility.VisibilityDto(MIN(vi.managementStartDate), MIN(vi.interviewerStartDate), MIN(vi.identificationPhaseStartDate), MIN(vi.collectionStartDate), MAX(vi.collectionEndDate), MAX(vi.endDate)) " - + "FROM Visibility vi " - + "INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id " - + "WHERE vi.campaign.id=:campaignId AND (vi.organizationUnit.id IN (:OUids) OR 'GUEST' IN (:OUids))") - VisibilityDto findVisibilityByCampaignId(@Param("campaignId") String campaignId, - @Param("OUids") List organizationalUnitIds); - - List findByCampaignId(String campaignId); - - Optional findByCampaignIdIgnoreCaseAndOrganizationUnitIdIgnoreCase(String campaignId, - String organizationalUnitId); -} diff --git a/src/main/java/fr/insee/pearljam/api/service/CampaignService.java b/src/main/java/fr/insee/pearljam/api/service/CampaignService.java index 8ec3ae79..a3fdf403 100644 --- a/src/main/java/fr/insee/pearljam/api/service/CampaignService.java +++ b/src/main/java/fr/insee/pearljam/api/service/CampaignService.java @@ -3,19 +3,20 @@ import java.util.List; import java.util.Optional; -import org.springframework.http.HttpStatus; +import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; +import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.api.domain.Response; -import fr.insee.pearljam.api.dto.campaign.CampaignContextDto; +import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; import fr.insee.pearljam.api.dto.campaign.CampaignDto; import fr.insee.pearljam.api.dto.count.CountDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityContextDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityDto; -import fr.insee.pearljam.api.exception.NoOrganizationUnitException; import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.api.exception.VisibilityException; +import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; /** * Service for the Campaign entity @@ -55,32 +56,19 @@ public interface CampaignService { CountDto getNbSUNotAttributedByCampaign(String userId, String campaignId) throws NotFoundException; - /** - * Update the visibility for a given campaign and a Organizational Unit - * - * @param idCampaign - * @param idOu - * @param updatedVisibility - * @return - */ - HttpStatus updateVisibility(String idCampaign, String idOu, VisibilityDto updatedVisibility); - - Response postCampaign(CampaignContextDto campaignDto) throws NoOrganizationUnitException, VisibilityException; + void createCampaign(CampaignCreateDto campaignDto) throws CampaignAlreadyExistException, CampaignNotFoundException, OrganizationalUnitNotFoundException; - Optional findById(String id); + Optional findById(String campaignId); void delete(Campaign campaign); - HttpStatus updateCampaign(String id, CampaignContextDto campaign); - - boolean isCampaignOngoing(String id); - - List findAllVisiblitiesByCampaign(String campaignId); + void updateCampaign(String id, CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException; - void persistReferents(CampaignContextDto campaignDto, Campaign campaign); + boolean isCampaignOngoing(String id) throws CampaignNotFoundException; - CampaignContextDto getCampaignDtoById(String id); + List findAllVisibilitiesByCampaign(String campaignId) throws CampaignNotFoundException; - boolean existsAny(); + CampaignResponseDto getCampaignDtoById(String id) throws CampaignNotFoundException; + void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNotFoundException; } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index 82b3fff5..916b63e1 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -8,37 +8,39 @@ import java.util.Optional; import java.util.stream.Collectors; +import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; +import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.output.visibility.VisibilityCampaignDto; +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.api.domain.OrganizationUnit; import fr.insee.pearljam.api.domain.Referent; -import fr.insee.pearljam.api.domain.Response; import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.api.domain.Visibility; -import fr.insee.pearljam.api.domain.VisibilityId; -import fr.insee.pearljam.api.dto.campaign.CampaignContextDto; +import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; import fr.insee.pearljam.api.dto.campaign.CampaignDto; import fr.insee.pearljam.api.dto.count.CountDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; import fr.insee.pearljam.api.dto.referent.ReferentDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityContextDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityDto; -import fr.insee.pearljam.api.exception.NoOrganizationUnitException; +import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignCreateDto; import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.api.exception.VisibilityException; +import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; import fr.insee.pearljam.api.repository.CampaignRepository; import fr.insee.pearljam.api.repository.MessageRepository; import fr.insee.pearljam.api.repository.OrganizationUnitRepository; import fr.insee.pearljam.api.repository.ReferentRepository; import fr.insee.pearljam.api.repository.SurveyUnitRepository; import fr.insee.pearljam.api.repository.UserRepository; -import fr.insee.pearljam.api.repository.VisibilityRepository; import fr.insee.pearljam.api.service.CampaignService; import fr.insee.pearljam.api.service.PreferenceService; import fr.insee.pearljam.api.service.ReferentService; @@ -56,7 +58,7 @@ */ @Service @RequiredArgsConstructor -@Transactional +@Transactional(rollbackFor = Exception.class) @Slf4j public class CampaignServiceImpl implements CampaignService { @@ -84,21 +86,21 @@ public List getListCampaign(String userId) { .map(OrganizationUnitDto::getId) .flatMap(ouId -> campaignRepository.findIdsByOuId(ouId).stream()) .distinct() - .collect(Collectors.toList()); + .toList(); List lstOuId = (userId.equals(Constants.GUEST)) ? Collections.singletonList(Constants.GUEST) - : organizationUnits.stream().map(OrganizationUnitDto::getId).collect(Collectors.toList()); + : organizationUnits.stream().map(OrganizationUnitDto::getId).toList(); List campaignDtoReturned = new ArrayList<>(); for (String idCampaign : campaignDtoIds) { CampaignDto campaign = campaignRepository.findDtoById(idCampaign); - VisibilityDto visibility = visibilityRepository.findVisibilityByCampaignId(idCampaign, lstOuId); - campaign.setManagementStartDate(visibility.getManagementStartDate()); - campaign.setInterviewerStartDate(visibility.getInterviewerStartDate()); - campaign.setIdentificationPhaseStartDate(visibility.getIdentificationPhaseStartDate()); - campaign.setCollectionStartDate(visibility.getCollectionStartDate()); - campaign.setCollectionEndDate(visibility.getCollectionEndDate()); - campaign.setEndDate(visibility.getEndDate()); + CampaignVisibility visibility = visibilityRepository.findCampaignVisibility(idCampaign, lstOuId); + campaign.setManagementStartDate(visibility.managementStartDate()); + campaign.setInterviewerStartDate(visibility.interviewerStartDate()); + campaign.setIdentificationPhaseStartDate(visibility.identificationPhaseStartDate()); + campaign.setCollectionStartDate(visibility.collectionStartDate()); + campaign.setCollectionEndDate(visibility.collectionEndDate()); + campaign.setEndDate(visibility.endDate()); campaign.setCampaignStats(surveyUnitRepository.getCampaignStats(idCampaign, lstOuId)); campaign.setPreference(isUserPreference(userId, idCampaign)); campaign.setReferents(referentService.findByCampaignId(idCampaign)); @@ -116,7 +118,7 @@ public List getListInterviewers(String userId, String campaignId List organizationUnits = userService.getUserOUs(userId, false); List userOrgUnitIds = organizationUnits.stream().map(OrganizationUnitDto::getId) - .collect(Collectors.toList()); + .toList(); for (String orgId : campaignRepository.findAllOrganistionUnitIdByCampaignId(campaignId)) { if (userOrgUnitIds.contains(orgId)) { @@ -131,93 +133,12 @@ public List getListInterviewers(String userId, String campaignId } @Override - public HttpStatus updateVisibility(String idCampaign, String idOu, VisibilityDto updatedVisibility) { - if (idCampaign == null || idOu == null || !updatedVisibility.isOneDateFilled()) { - log.error("Required fields missing in input body"); - return HttpStatus.BAD_REQUEST; - } - Optional visibility = visibilityRepository.findVisibilityByCampaignIdAndOuId(idCampaign, idOu); - if (!visibility.isPresent()) { - String errorMessage = String.format("No visibility found for campaign %s", idCampaign); - log.error(errorMessage); - return HttpStatus.NOT_FOUND; - } - VisibilityDto expectedVisibility = mergeVisibilities(visibility.get(), updatedVisibility); - if (!checkDateConsistency(expectedVisibility)) { - log.warn("Invalid Visibility dates : should be strictly increasing"); - return HttpStatus.CONFLICT; - } - setVisibilityDates(visibility.get(), updatedVisibility, idOu, idCampaign); - return HttpStatus.OK; - } - - private VisibilityDto mergeVisibilities(Visibility initialVisibility, VisibilityDto updatedVisibility) { - VisibilityDto expectedVisibility = new VisibilityDto(initialVisibility.getManagementStartDate(), - initialVisibility.getInterviewerStartDate(), - initialVisibility.getIdentificationPhaseStartDate(), - initialVisibility.getCollectionStartDate(), - initialVisibility.getCollectionEndDate(), - initialVisibility.getEndDate()); - - if (updatedVisibility.getManagementStartDate() != null) { - expectedVisibility.setManagementStartDate(updatedVisibility.getManagementStartDate()); - } - if (updatedVisibility.getInterviewerStartDate() != null) { - expectedVisibility.setInterviewerStartDate(updatedVisibility.getInterviewerStartDate()); - } - if (updatedVisibility.getIdentificationPhaseStartDate() != null) { - expectedVisibility.setIdentificationPhaseStartDate(updatedVisibility.getIdentificationPhaseStartDate()); - } - if (updatedVisibility.getCollectionStartDate() != null) { - expectedVisibility.setCollectionStartDate(updatedVisibility.getCollectionStartDate()); - } - if (updatedVisibility.getCollectionEndDate() != null) { - expectedVisibility.setCollectionEndDate(updatedVisibility.getCollectionEndDate()); - } - if (updatedVisibility.getEndDate() != null) { - expectedVisibility.setEndDate(updatedVisibility.getEndDate()); - } - return expectedVisibility; - } - - private boolean checkDateConsistency(VisibilityDto visibility) { - return visibility.getManagementStartDate() < visibility.getInterviewerStartDate() - && visibility.getInterviewerStartDate() < visibility.getIdentificationPhaseStartDate() - && visibility.getIdentificationPhaseStartDate() < visibility.getCollectionStartDate() - && visibility.getCollectionStartDate() < visibility.getCollectionEndDate() - && visibility.getCollectionEndDate() < visibility.getEndDate(); - } - - private void setVisibilityDates(Visibility visibility, VisibilityDto updatedVisibility, String idOu, - String idCampaign) { - if (updatedVisibility.getManagementStartDate() != null) { - log.info("Updating management start date for campaign {} and Organizational Unit {}", idCampaign, - idOu); - visibility.setManagementStartDate(updatedVisibility.getManagementStartDate()); - } - if (updatedVisibility.getInterviewerStartDate() != null) { - log.info("Updating interviewer start date for campaign {} and Organizational Unit {}", - idCampaign, idOu); - visibility.setInterviewerStartDate(updatedVisibility.getInterviewerStartDate()); - } - if (updatedVisibility.getIdentificationPhaseStartDate() != null) { - log.info("Updating identification phase start date for campaign {} and Organizational Unit {}", - idCampaign, idOu); - visibility.setIdentificationPhaseStartDate(updatedVisibility.getIdentificationPhaseStartDate()); - } - if (updatedVisibility.getCollectionStartDate() != null) { - log.info("Updating collection start date for campaign {} and Organizational Unit {}", idCampaign, idOu); - visibility.setCollectionStartDate(updatedVisibility.getCollectionStartDate()); - } - if (updatedVisibility.getCollectionEndDate() != null) { - log.info("Updating collection end date for campaign {} and Organizational Unit {}", idCampaign, - idOu); - visibility.setCollectionEndDate(updatedVisibility.getCollectionEndDate()); - } - if (updatedVisibility.getEndDate() != null) { - log.info("Updating end date for campaign {} and Organizational Unit {}", idCampaign, idOu); - visibility.setEndDate(updatedVisibility.getEndDate()); - } + public void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNotFoundException { + Visibility currentVisibility = visibilityRepository + .findVisibility(visibilityToUpdate.campaignId(), visibilityToUpdate.organizationalUnitId()) + .orElseThrow(VisibilityNotFoundException::new); + Visibility mergedVisibility = Visibility.merge(currentVisibility, visibilityToUpdate); + visibilityRepository.update(mergedVisibility); } @Override @@ -244,80 +165,43 @@ public CountDto getNbSUNotAttributedByCampaign(String userId, String campaignId) } @Override - @Transactional(rollbackFor = Exception.class) - public Response postCampaign(CampaignContextDto campaignDto) - throws NoOrganizationUnitException, VisibilityException { - if (campaignDto.getCampaign() == null) { - return new Response("Campaign id is missing in request", HttpStatus.BAD_REQUEST); - } - if (campaignDto.getCampaignLabel() == null) { - return new Response("Campaign label is missing in request", HttpStatus.BAD_REQUEST); - } - if (campaignDto.getVisibilities() == null) { - return new Response("Campaign visibilities are missing in request", HttpStatus.BAD_REQUEST); - } - String campaignId = campaignDto.getCampaign().toUpperCase(); + public void createCampaign(CampaignCreateDto campaignDto) + throws CampaignAlreadyExistException, CampaignNotFoundException, OrganizationalUnitNotFoundException { + + String campaignId = campaignDto.campaign().toUpperCase(); Optional campOpt = campaignRepository.findById(campaignId); if (campOpt.isPresent()) { - return new Response(String.format("Campaign with id '%s' already exists", campaignId), - HttpStatus.BAD_REQUEST); + throw new CampaignAlreadyExistException(); } - // Creating campaign - Campaign campaign = new Campaign(campaignId, campaignDto.getCampaignLabel(), - campaignDto.getIdentificationConfiguration(), campaignDto.getContactOutcomeConfiguration(), - campaignDto.getContactAttemptConfiguration(), campaignDto.getEmail(), - campaignDto.getCommunicationRequestConfiguration()); + // Creating campaign + Campaign campaign = new Campaign(campaignId, campaignDto.campaignLabel(), + campaignDto.identificationConfiguration(), + campaignDto.contactOutcomeConfiguration(), + campaignDto.contactAttemptConfiguration(), + campaignDto.email(), + campaignDto.communicationRequestConfiguration()); campaignRepository.save(campaign); - for (VisibilityContextDto dto : campaignDto.getVisibilities()) { - if (!verifyVisibilityContextDto(dto)) { - - throw new VisibilityException("Some of the fields of a visibility are missing"); - } - Optional ouOpt = organizationUnitRepository.findById(dto.getOrganizationalUnit()); - if (ouOpt.isPresent()) { - Visibility visi = new Visibility(); - visi.setVisibilityId(new VisibilityId(dto.getOrganizationalUnit(), campaign.getId())); - visi.setCampaign(campaign); - visi.setOrganizationUnit(ouOpt.get()); - visi.setCollectionStartDate(dto.getCollectionStartDate()); - visi.setCollectionEndDate(dto.getCollectionEndDate()); - visi.setIdentificationPhaseStartDate(dto.getIdentificationPhaseStartDate()); - visi.setInterviewerStartDate(dto.getInterviewerStartDate()); - visi.setManagementStartDate(dto.getManagementStartDate()); - visi.setEndDate(dto.getEndDate()); - - visibilityRepository.save(visi); - } else { - throw new NoOrganizationUnitException( - String.format("Organizational unit '%s' does not exist", dto.getOrganizationalUnit())); - } + for (VisibilityCampaignCreateDto visibilityDto : campaignDto.visibilities()) { + Visibility visibilityToCreate = VisibilityCampaignCreateDto.toModel(visibilityDto); + visibilityRepository.create(visibilityToCreate); } - persistReferents(campaignDto, campaign); - - return new Response("", HttpStatus.OK); - } - - public boolean verifyVisibilityContextDto(VisibilityContextDto dto) { - return dto.getOrganizationalUnit() != null && dto.getCollectionStartDate() != null - && dto.getCollectionEndDate() != null && dto.getIdentificationPhaseStartDate() != null - && dto.getInterviewerStartDate() != null && dto.getManagementStartDate() != null - && dto.getEndDate() != null; + persistReferents(campaignDto.referents(), campaign); } @Override - public Optional findById(String id) { - return campaignRepository.findById(id); + public Optional findById(String campaignId) { + return campaignRepository.findById(campaignId); } @Override public void delete(Campaign campaign) { surveyUnitRepository.findByCampaignId(campaign.getId()).stream().forEach(surveyUnitService::delete); - userRepository.findAll().stream() + userRepository.findAll() .forEach(user -> { List lstCampaignId = user.getCampaigns().stream().map(Campaign::getId) - .collect(Collectors.toList()); + .toList(); if (lstCampaignId.contains(campaign.getId())) { lstCampaignId.remove(lstCampaignId.indexOf(campaign.getId())); preferenceService.setPreferences(lstCampaignId, user.getId()); @@ -328,77 +212,44 @@ public void delete(Campaign campaign) { } @Override - public HttpStatus updateCampaign(String id, CampaignContextDto campaign) { - Optional camp = campaignRepository.findByIdIgnoreCase(id); - if (!camp.isPresent()) { - log.error("Campaign {} does not exist in db", id); - return HttpStatus.NOT_FOUND; - } + public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate) throws CampaignNotFoundException, VisibilityNotFoundException { + Campaign currentCampaign = campaignRepository.findByIdIgnoreCase(campaignId) + .orElseThrow(CampaignNotFoundException::new); - if (campaign.getCampaignLabel() == null || campaign.getCampaignLabel().isEmpty() - || campaign.getCampaignLabel().isBlank() - || !campaign.getVisibilities().stream().allMatch(VisibilityDto::isOneDateFilled)) { - log.warn("Can't update campaign {} : invalid input", id); - return HttpStatus.BAD_REQUEST; + List visibilitiesToUpdate = VisibilityCampaignUpdateDto.toModel(campaignToUpdate.visibilities(), campaignId); + for(Visibility visibilityToUpdate : visibilitiesToUpdate) { + updateVisibility(visibilityToUpdate); } - boolean visibilitiesArePresent = campaign.getVisibilities().stream() - .map(VisibilityContextDto::getOrganizationalUnit) - .allMatch(ouId -> visibilityRepository - .findByCampaignIdIgnoreCaseAndOrganizationUnitIdIgnoreCase(id, ouId).isPresent()); - if (!visibilitiesArePresent) { - log.warn("Can't update missing visibility for campaign {}", id); - return HttpStatus.NOT_FOUND; + currentCampaign.setLabel(campaignToUpdate.campaignLabel()); + if (!StringUtils.isBlank(campaignToUpdate.email())) { + currentCampaign.setEmail(campaignToUpdate.email()); } - boolean visibilitiesAreValid = campaign.getVisibilities().stream().allMatch(this::checkDateConsistency); - if (!visibilitiesAreValid) { - log.warn("Invalid Visibility dates : should be strictly increasing"); - return HttpStatus.CONFLICT; - } - - Campaign currentCampaign = camp.get(); - currentCampaign.setLabel(campaign.getCampaignLabel()); - if (!StringUtils.isBlank(campaign.getEmail())) { - currentCampaign.setEmail(campaign.getEmail()); - } - - updateConfiguration(currentCampaign, campaign); - updateReferents(currentCampaign, campaign); - - campaign.getVisibilities().stream().forEach(v -> this.updateVisibility( - id, - v.getOrganizationalUnit(), - new VisibilityDto( - v.getManagementStartDate(), - v.getInterviewerStartDate(), - v.getIdentificationPhaseStartDate(), - v.getCollectionStartDate(), - v.getCollectionEndDate(), - v.getEndDate()))); - return HttpStatus.OK; + updateConfiguration(currentCampaign, campaignToUpdate); + updateReferents(currentCampaign, campaignToUpdate); } - private void updateReferents(Campaign currentCampaign, CampaignContextDto campDto) { - if (campDto.getReferents() != null) { + private void updateReferents(Campaign currentCampaign, CampaignUpdateDto campDto) { + if (campDto.referents() != null) { referentRepository.deleteAll(currentCampaign.getReferents()); - persistReferents(campDto, currentCampaign); + persistReferents(campDto.referents(), currentCampaign); } } - private void updateConfiguration(Campaign currentCampaign, CampaignContextDto campDto) { + private void updateConfiguration(Campaign currentCampaign, CampaignUpdateDto campDto) { - if (campDto.getIdentificationConfiguration() != null) { - currentCampaign.setIdentificationConfiguration(campDto.getIdentificationConfiguration()); + if (campDto.identificationConfiguration() != null) { + currentCampaign.setIdentificationConfiguration(campDto.identificationConfiguration()); } - if (campDto.getContactOutcomeConfiguration() != null) { - currentCampaign.setContactOutcomeConfiguration(campDto.getContactOutcomeConfiguration()); + if (campDto.contactOutcomeConfiguration() != null) { + currentCampaign.setContactOutcomeConfiguration(campDto.contactOutcomeConfiguration()); } - if (campDto.getContactAttemptConfiguration() != null) { - currentCampaign.setContactAttemptConfiguration(campDto.getContactAttemptConfiguration()); + if (campDto.contactAttemptConfiguration() != null) { + currentCampaign.setContactAttemptConfiguration(campDto.contactAttemptConfiguration()); } - if (campDto.getCommunicationRequestConfiguration() != null) { - currentCampaign.setCommunicationConfiguration(campDto.getCommunicationRequestConfiguration()); + if (campDto.communicationRequestConfiguration() != null) { + currentCampaign.setCommunicationConfiguration(campDto.communicationRequestConfiguration()); } } @@ -408,7 +259,7 @@ public List getAllCampaigns() { return campaignRepository.findAllDto().stream().map(camp -> { camp.setCampaignStats(surveyUnitRepository.getCampaignStats(camp.getId(), lstOuId)); return camp; - }).collect(Collectors.toList()); + }).toList(); } @Override @@ -424,32 +275,24 @@ public List getInterviewerCampaigns(String userId) { } @Override - public boolean isCampaignOngoing(String campaignId) { - List visibilities = visibilityRepository.findByCampaignId(campaignId); - return visibilities.stream().anyMatch(visibility -> visibility.getEndDate() > Instant.now().toEpochMilli()); + public boolean isCampaignOngoing(String campaignId) throws CampaignNotFoundException { + findById(campaignId) + .orElseThrow(CampaignNotFoundException::new); + List visibilities = visibilityRepository.findVisibilities(campaignId); + return visibilities.stream() + .anyMatch(visibility -> visibility.endDate() > Instant.now().toEpochMilli()); } @Override - public List findAllVisiblitiesByCampaign(String campaignId) { - return visibilityRepository.findByCampaignId(campaignId).stream().map(v -> { - VisibilityContextDto vcd = new VisibilityContextDto(); - vcd.setCollectionEndDate(v.getCollectionEndDate()); - vcd.setCollectionStartDate(v.getCollectionStartDate()); - vcd.setEndDate(v.getEndDate()); - vcd.setInterviewerStartDate(v.getInterviewerStartDate()); - vcd.setIdentificationPhaseStartDate(v.getIdentificationPhaseStartDate()); - vcd.setManagementStartDate(v.getManagementStartDate()); - vcd.setOrganizationalUnit(v.getOrganizationUnit().getId()); - - return vcd; - }).collect(Collectors.toList()); + public List findAllVisibilitiesByCampaign(String campaignId) throws CampaignNotFoundException { + findById(campaignId) + .orElseThrow(CampaignNotFoundException::new); + return visibilityRepository.findVisibilities(campaignId); } - @Override - - public void persistReferents(CampaignContextDto campaignDto, Campaign campaign) { + private void persistReferents(List referents, Campaign campaign) { - campaignDto.getReferents().stream().forEach(refDto -> { + referents.forEach(refDto -> { Referent ref = new Referent(); ref.setCampaign(campaign); ref.setFirstName(refDto.getFirstName()); @@ -461,31 +304,13 @@ public void persistReferents(CampaignContextDto campaignDto, Campaign campaign) } @Override - public CampaignContextDto getCampaignDtoById(String id) { - CampaignContextDto campaign = new CampaignContextDto(); - CampaignDto campdto = campaignRepository.findDtoById(id); - campaign.setCampaign(campdto.getId()); - campaign.setCampaignLabel(campdto.getLabel()); - campaign.setEmail(campdto.getEmail()); - campaign.setContactAttemptConfiguration(campdto.getContactAttemptConfiguration()); - campaign.setContactOutcomeConfiguration(campdto.getContactOutcomeConfiguration()); - campaign.setIdentificationConfiguration(campdto.getIdentificationConfiguration()); - campaign.setCommunicationRequestConfiguration( - Optional.ofNullable(campdto.getCommunicationRequestConfiguration()).orElse(false)); - List visibilities = visibilityRepository.findByCampaignId(id).stream() - .map(VisibilityContextDto::new).collect(Collectors.toList()); - campaign.setVisibilities(visibilities); - - List referents = referentService.findByCampaignId(id); - campaign.setReferents(referents); - - return campaign; + public CampaignResponseDto getCampaignDtoById(String campaignId) throws CampaignNotFoundException { + Campaign campaignDB = campaignRepository.findById(campaignId) + .orElseThrow(CampaignNotFoundException::new); + List referents = referentService.findByCampaignId(campaignId); + List visibilities = VisibilityCampaignDto.fromModel( + visibilityRepository.findVisibilities(campaignId) + ); + return CampaignResponseDto.fromModel(campaignDB, referents, visibilities); } - - @Override - public boolean existsAny() { - - return !campaignRepository.findAllIds().isEmpty(); - } - } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/ContactOutcomeServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/ContactOutcomeServiceImpl.java index f7267a61..3b59a494 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/ContactOutcomeServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/ContactOutcomeServiceImpl.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.stream.Collectors; +import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -16,7 +17,6 @@ import fr.insee.pearljam.api.repository.ContactOutcomeRepository; import fr.insee.pearljam.api.repository.InterviewerRepository; import fr.insee.pearljam.api.repository.OrganizationUnitRepository; -import fr.insee.pearljam.api.repository.VisibilityRepository; import fr.insee.pearljam.api.service.ContactOutcomeService; import fr.insee.pearljam.api.service.UserService; import fr.insee.pearljam.api.service.UtilsService; @@ -62,7 +62,7 @@ public ContactOutcomeTypeCountCampaignDto getContactOutcomeCountTypeByCampaign(S } for (String id : organizationUnitRepository.findAllId()) { if (organizationUnitRepository.findChildren(id).isEmpty() - && visibilityRepository.findVisibilityByCampaignIdAndOuId(campaignId, id).isPresent()) { + && visibilityRepository.findVisibility(campaignId, id).isPresent()) { stateCountList.add(new ContactOutcomeTypeCountDto(id, organizationUnitRepository.findLabel(id), contactOutcomeRepository.getContactOutcomeTypeCountByCampaignAndOU(campaignId, id, dateToUse))); } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java index 4bef0779..eef143db 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java @@ -16,13 +16,13 @@ import fr.insee.pearljam.api.domain.Interviewer; import fr.insee.pearljam.api.domain.Response; import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.api.domain.Visibility; +import fr.insee.pearljam.api.domain.VisibilityDB; import fr.insee.pearljam.api.dto.campaign.CampaignDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerContextDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; import fr.insee.pearljam.api.repository.InterviewerRepository; -import fr.insee.pearljam.api.repository.VisibilityRepository; +import fr.insee.pearljam.infrastructure.campaign.jpa.VisibilityJpaRepository; import fr.insee.pearljam.api.service.InterviewerService; import fr.insee.pearljam.api.service.SurveyUnitService; import fr.insee.pearljam.api.service.UserService; @@ -42,7 +42,7 @@ public class InterviewerServiceImpl implements InterviewerService { private final InterviewerRepository interviewerRepository; - private final VisibilityRepository visibilityRepository; + private final VisibilityJpaRepository visibilityRepository; private final UserService userService; private final SurveyUnitService surveyUnitService; @@ -53,9 +53,9 @@ public Optional> findCampaignsOfInterviewer(String interviewer } Interviewer intw = intwOpt.get(); List suIds = intw.getSurveyUnits().stream().map(SurveyUnit::getId).collect(Collectors.toList()); - List visibilities = visibilityRepository.findAllVisibilityBySurveyUnitIds(suIds); + List visibilities = visibilityRepository.findAllVisibilityBySurveyUnitIds(suIds); List dtos = new ArrayList<>(); - for (Visibility vi : visibilities) { + for (VisibilityDB vi : visibilities) { Optional dtoOpt = dtos.stream() .filter(dto -> dto.getId().equals(vi.getCampaign().getId())) .findFirst(); diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/StateServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/StateServiceImpl.java index 3f8cc400..c40b6927 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/StateServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/StateServiceImpl.java @@ -5,6 +5,7 @@ import java.util.Set; import java.util.stream.Collectors; +import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -19,7 +20,6 @@ import fr.insee.pearljam.api.repository.InterviewerRepository; import fr.insee.pearljam.api.repository.OrganizationUnitRepository; import fr.insee.pearljam.api.repository.StateRepository; -import fr.insee.pearljam.api.repository.VisibilityRepository; import fr.insee.pearljam.api.service.StateService; import fr.insee.pearljam.api.service.UserService; import fr.insee.pearljam.api.service.UtilsService; @@ -99,7 +99,7 @@ public StateCountCampaignDto getStateCountByCampaign(String userId, String campa } for (String id : organizationUnitRepository.findAllId()) { if (organizationUnitRepository.findChildren(id).isEmpty() - && visibilityRepository.findVisibilityByCampaignIdAndOuId(campaignId, id).isPresent()) { + && visibilityRepository.findVisibility(campaignId, id).isPresent()) { StateCountDto dto = new StateCountDto(id, organizationUnitRepository.findLabel(id), stateRepository.getStateCountByCampaignAndOU(campaignId, id, dateToUse)); dto.addClosingCauseCount( diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java index 07781571..6875c72b 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java @@ -13,6 +13,9 @@ import fr.insee.pearljam.api.dto.surveyunit.*; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitVisibilityDto; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; import fr.insee.pearljam.domain.exception.PersonNotFoundException; import fr.insee.pearljam.domain.exception.SurveyUnitNotFoundException; import fr.insee.pearljam.domain.surveyunit.model.IdentificationState; @@ -122,8 +125,13 @@ public List getSurveyUnitDto(String userId, Boolean extended) { } if (userId.equals(GUEST)) { return surveyUnitDtoIds.stream() - .map(idSurveyUnit -> new SurveyUnitDto(surveyUnitRepository.findById(idSurveyUnit).get(), - visibilityRepository.findVisibilityBySurveyUnitId(idSurveyUnit), extended)) + .map(idSurveyUnit -> { + Visibility visibility = visibilityRepository.getVisibilityBySurveyUnitId(idSurveyUnit); + return new SurveyUnitDto( + surveyUnitRepository.findById(idSurveyUnit).get(), + SurveyUnitVisibilityDto.fromModel(visibility), + extended); + }) .toList(); } surveyUnitDtoIds = surveyUnitDtoIds.stream().filter(this::canBeSeenByInterviewer) @@ -132,8 +140,8 @@ public List getSurveyUnitDto(String userId, Boolean extended) { return surveyUnitDtoIds.stream() .map(idSurveyUnit -> new SurveyUnitDto(idSurveyUnit, campaignRepository.findDtoBySurveyUnitId(idSurveyUnit), - visibilityRepository.findVisibilityBySurveyUnitId(idSurveyUnit))) - + SurveyUnitVisibilityDto.fromModel( + visibilityRepository.getVisibilityBySurveyUnitId(idSurveyUnit)))) .toList(); } diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitVisibilityDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitVisibilityDto.java new file mode 100644 index 00000000..5e1f6a7f --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitVisibilityDto.java @@ -0,0 +1,35 @@ +package fr.insee.pearljam.api.surveyunit.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; +import fr.insee.pearljam.domain.campaign.model.Visibility; + +/** + * A Data Transfer Object for representing visibility information. + * + * @param collectionStartDate Collection start date of the visibility + * @param collectionEndDate Collection end date of the visibility + * @param identificationPhaseStartDate Identification phase start date of the visibility + * @param interviewerStartDate Interviewer start date of the visibility + * @param managementStartDate Manager start date of the visibility + * @param endDate End date of the visibility + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record SurveyUnitVisibilityDto( + Long managementStartDate, + Long interviewerStartDate, + Long identificationPhaseStartDate, + Long collectionStartDate, + Long collectionEndDate, + Long endDate +) { + + public static SurveyUnitVisibilityDto fromModel(Visibility visibility) { + return new SurveyUnitVisibilityDto( + visibility.managementStartDate(), + visibility.interviewerStartDate(), + visibility.identificationPhaseStartDate(), + visibility.collectionStartDate(), + visibility.collectionEndDate(), + visibility.endDate()); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java index d68d0ac8..a0f49c76 100644 --- a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java +++ b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java @@ -2,6 +2,8 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; +import fr.insee.pearljam.api.exception.NoOrganizationUnitException; +import fr.insee.pearljam.domain.exception.EntityAlreadyExistException; import fr.insee.pearljam.domain.exception.EntityNotFoundException; import fr.insee.pearljam.infrastructure.mail.exception.SendMailException; import jakarta.validation.ConstraintViolationException; @@ -119,6 +121,16 @@ public ResponseEntity entityAlreadyExistException(EntityAlreadyExistEx return generateResponseError(e, HttpStatus.BAD_REQUEST, request); } + @ExceptionHandler(NoOrganizationUnitException.class) + public ResponseEntity exceptions(NoOrganizationUnitException e, WebRequest request) { + return generateResponseError(e, HttpStatus.BAD_REQUEST, request); + } + + @ExceptionHandler(VisibilityInvalidException.class) + public ResponseEntity exceptions(VisibilityInvalidException e, WebRequest request) { + return generateResponseError(e, HttpStatus.BAD_REQUEST, request); + } + @ExceptionHandler(HttpClientErrorException.class) public ResponseEntity exceptions(HttpClientErrorException e, WebRequest request) { return generateResponseError(e, HttpStatus.valueOf(e.getStatusCode().value()), request, ERROR_OCCURRED_LABEL); diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/VisibilityInvalidException.java b/src/main/java/fr/insee/pearljam/api/web/exception/VisibilityInvalidException.java new file mode 100644 index 00000000..e90075c5 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/web/exception/VisibilityInvalidException.java @@ -0,0 +1,8 @@ +package fr.insee.pearljam.api.web.exception; + +public class VisibilityInvalidException extends RuntimeException { + + public VisibilityInvalidException(String message) { + super(message); + } +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/CampaignVisibility.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/CampaignVisibility.java new file mode 100644 index 00000000..2be4797e --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/CampaignVisibility.java @@ -0,0 +1,20 @@ +package fr.insee.pearljam.domain.campaign.model; + +/** + * A class representing the visibility of a campaign for an organizational unit + * + * @param managementStartDate The start date of Visibility of management + * @param interviewerStartDate The start date of Visibility of interviewer + * @param identificationPhaseStartDate The start date of identification phase + * @param collectionStartDate The start date of collection + * @param collectionEndDate The end date of collection + * @param endDate The end date of visibility + */ +public record CampaignVisibility( + Long managementStartDate, + Long interviewerStartDate, + Long identificationPhaseStartDate, + Long collectionStartDate, + Long collectionEndDate, + Long endDate) { +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java new file mode 100644 index 00000000..aeab87aa --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java @@ -0,0 +1,71 @@ +package fr.insee.pearljam.domain.campaign.model; + +import fr.insee.pearljam.api.web.exception.VisibilityInvalidException; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; + +import java.util.List; + +/** + * A class representing the visibility of a campaign for an organizational unit + * + * @param managementStartDate The start date of Visibility of management + * @param interviewerStartDate The start date of Visibility of interviewer + * @param identificationPhaseStartDate The start date of identification phase + * @param collectionStartDate The start date of collection + * @param collectionEndDate The end date of collection + * @param endDate The end date of visibility + * @param communicationTemplates List of communication templates associated with the visibility + */ +public record Visibility( + String campaignId, + String organizationalUnitId, + Long managementStartDate, + Long interviewerStartDate, + Long identificationPhaseStartDate, + Long collectionStartDate, + Long collectionEndDate, + Long endDate, + List communicationTemplates +) { + public static final String DATE_SHOULD_BE_INCREASING = "Invalid Visibility dates : should be strictly increasing"; + + public static Visibility merge(Visibility currentVisibility, Visibility visibilityToUpdate) { + Long managementStartDate = visibilityToUpdate.managementStartDate() != null ? + visibilityToUpdate.managementStartDate() : currentVisibility.managementStartDate(); + Long interviewerStartDate = visibilityToUpdate.interviewerStartDate() != null ? + visibilityToUpdate.interviewerStartDate() : currentVisibility.interviewerStartDate(); + Long identificationPhaseStartDate = visibilityToUpdate.identificationPhaseStartDate() != null ? + visibilityToUpdate.identificationPhaseStartDate() : currentVisibility.identificationPhaseStartDate(); + Long collectionStartDate = visibilityToUpdate.collectionStartDate() != null ? + visibilityToUpdate.collectionStartDate() : currentVisibility.collectionStartDate(); + Long collectionEndDate = visibilityToUpdate.collectionEndDate() != null ? + visibilityToUpdate.collectionEndDate() : currentVisibility.collectionEndDate(); + Long endDate = visibilityToUpdate.endDate() != null ? + visibilityToUpdate.endDate() : currentVisibility.endDate(); + + Visibility updatedVisibility = new Visibility( + currentVisibility.campaignId(), + currentVisibility.organizationalUnitId(), + managementStartDate, + interviewerStartDate, + identificationPhaseStartDate, + collectionStartDate, + collectionEndDate, + endDate, + null); + + if(isValid(updatedVisibility)) { + return updatedVisibility; + } + + throw new VisibilityInvalidException(DATE_SHOULD_BE_INCREASING); + } + + private static boolean isValid(Visibility visibility) { + return visibility.managementStartDate() < visibility.interviewerStartDate() + && visibility.interviewerStartDate() < visibility.identificationPhaseStartDate() + && visibility.identificationPhaseStartDate() < visibility.collectionStartDate() + && visibility.collectionStartDate() < visibility.collectionEndDate() + && visibility.collectionEndDate() < visibility.endDate(); + } +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationMedium.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationMedium.java new file mode 100644 index 00000000..c79534f4 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationMedium.java @@ -0,0 +1,5 @@ +package fr.insee.pearljam.domain.campaign.model.communication; + +public enum CommunicationMedium { + MAIL, EMAIL +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java new file mode 100644 index 00000000..75d5b24d --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java @@ -0,0 +1,18 @@ +package fr.insee.pearljam.domain.campaign.model.communication; + + +/** + * A class representing the communication template of a visibility. + * + * @param id The unique identifier of the communication template + * @param messhugahId The identifier for Messhugah + * @param medium The medium of communication + * @param type The type of communication + */ +public record CommunicationTemplate( + Long id, + String messhugahId, + CommunicationMedium medium, + CommunicationType type +) { +} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationType.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationType.java new file mode 100644 index 00000000..c9692b65 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationType.java @@ -0,0 +1,5 @@ +package fr.insee.pearljam.domain.campaign.model.communication; + +public enum CommunicationType { + REMINDER, NOTICE +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java new file mode 100644 index 00000000..858b3e90 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java @@ -0,0 +1,25 @@ +package fr.insee.pearljam.domain.campaign.port.serverside; + +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; + +import java.util.List; +import java.util.Optional; + +public interface VisibilityRepository { + + CampaignVisibility findCampaignVisibility(String idCampaign, List lstOuId); + + Optional findVisibility(String campaignId, String organizationalUnitId); + + List findVisibilities(String campaignId); + + void create(Visibility visibilityToCreate) throws CampaignNotFoundException, OrganizationalUnitNotFoundException; + + void update(Visibility visibilityToUpdate) throws VisibilityNotFoundException; + + Visibility getVisibilityBySurveyUnitId(String surveyUnitId); +} diff --git a/src/main/java/fr/insee/pearljam/domain/exception/CampaignAlreadyExistException.java b/src/main/java/fr/insee/pearljam/domain/exception/CampaignAlreadyExistException.java new file mode 100644 index 00000000..a2074c08 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/exception/CampaignAlreadyExistException.java @@ -0,0 +1,10 @@ +package fr.insee.pearljam.domain.exception; + +public class CampaignAlreadyExistException extends EntityAlreadyExistException { + + public static final String MESSAGE = "Campaign already exists"; + + public CampaignAlreadyExistException() { + super(MESSAGE); + } +} diff --git a/src/main/java/fr/insee/pearljam/domain/exception/CampaignNotFoundException.java b/src/main/java/fr/insee/pearljam/domain/exception/CampaignNotFoundException.java new file mode 100644 index 00000000..950ea354 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/exception/CampaignNotFoundException.java @@ -0,0 +1,10 @@ +package fr.insee.pearljam.domain.exception; + +public class CampaignNotFoundException extends EntityNotFoundException { + + public static final String MESSAGE = "Campaign not found"; + + public CampaignNotFoundException() { + super(MESSAGE); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/EntityAlreadyExistException.java b/src/main/java/fr/insee/pearljam/domain/exception/EntityAlreadyExistException.java similarity index 63% rename from src/main/java/fr/insee/pearljam/api/web/exception/EntityAlreadyExistException.java rename to src/main/java/fr/insee/pearljam/domain/exception/EntityAlreadyExistException.java index a3bc894a..8dc4b345 100644 --- a/src/main/java/fr/insee/pearljam/api/web/exception/EntityAlreadyExistException.java +++ b/src/main/java/fr/insee/pearljam/domain/exception/EntityAlreadyExistException.java @@ -1,8 +1,8 @@ -package fr.insee.pearljam.api.web.exception; +package fr.insee.pearljam.domain.exception; import java.io.Serial; -public class EntityAlreadyExistException extends RuntimeException { +public class EntityAlreadyExistException extends Exception { @Serial private static final long serialVersionUID = -478002885484590045L; diff --git a/src/main/java/fr/insee/pearljam/domain/exception/OrganizationalUnitNotFoundException.java b/src/main/java/fr/insee/pearljam/domain/exception/OrganizationalUnitNotFoundException.java new file mode 100644 index 00000000..949c9343 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/exception/OrganizationalUnitNotFoundException.java @@ -0,0 +1,10 @@ +package fr.insee.pearljam.domain.exception; + +public class OrganizationalUnitNotFoundException extends EntityNotFoundException { + + public static final String MESSAGE = "Organizational unit not found"; + + public OrganizationalUnitNotFoundException() { + super(MESSAGE); + } +} diff --git a/src/main/java/fr/insee/pearljam/domain/exception/VisibilityNotFoundException.java b/src/main/java/fr/insee/pearljam/domain/exception/VisibilityNotFoundException.java new file mode 100644 index 00000000..bbbb7285 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/exception/VisibilityNotFoundException.java @@ -0,0 +1,10 @@ +package fr.insee.pearljam.domain.exception; + +public class VisibilityNotFoundException extends EntityNotFoundException { + + public static final String MESSAGE = "Visibility not found"; + + public VisibilityNotFoundException() { + super(MESSAGE); + } +} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestMedium.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestMedium.java deleted file mode 100644 index 69d78dff..00000000 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestMedium.java +++ /dev/null @@ -1,5 +0,0 @@ -package fr.insee.pearljam.domain.surveyunit.model.communication; - -public enum CommunicationRequestMedium { - MAIL, EMAIL -} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestType.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestType.java deleted file mode 100644 index 16c40407..00000000 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestType.java +++ /dev/null @@ -1,5 +0,0 @@ -package fr.insee.pearljam.domain.surveyunit.model.communication; - -public enum CommunicationRequestType { - REMINDER, NOTICE -} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java new file mode 100644 index 00000000..1e0000da --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java @@ -0,0 +1,73 @@ +package fr.insee.pearljam.infrastructure.campaign.adapter; + +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.api.domain.OrganizationUnit; +import fr.insee.pearljam.api.repository.CampaignRepository; +import fr.insee.pearljam.api.repository.OrganizationUnitRepository; +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import fr.insee.pearljam.api.domain.VisibilityDB; +import fr.insee.pearljam.infrastructure.campaign.jpa.VisibilityJpaRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +@RequiredArgsConstructor +public class VisibilityDaoAdapter implements VisibilityRepository { + private final VisibilityJpaRepository crudRepository; + private final CampaignRepository campaignRepository; + private final OrganizationUnitRepository organizationUnitRepository; + + @Override + public CampaignVisibility findCampaignVisibility(String campaignId, List ouIds) { + return crudRepository.findVisibilityByCampaignId(campaignId, ouIds); + } + + @Override + public Optional findVisibility(String campaignId, String organizationalUnitId) { + return crudRepository + .findVisibilityByCampaignIdAndOuId(campaignId, organizationalUnitId) + .map(VisibilityDB::toModel); + } + + @Override + public List findVisibilities(String campaignId) { + return VisibilityDB.toModel( + crudRepository.findByCampaignId(campaignId) + ); + } + + @Override + public void create(Visibility visibilityToCreate) throws CampaignNotFoundException, OrganizationalUnitNotFoundException { + Campaign campaign = campaignRepository.findById(visibilityToCreate.campaignId()) + .orElseThrow(CampaignNotFoundException::new); + OrganizationUnit organizationUnit = organizationUnitRepository.findById(visibilityToCreate.organizationalUnitId()) + .orElseThrow(OrganizationalUnitNotFoundException::new); + + VisibilityDB visibilityDB = VisibilityDB.fromModel(visibilityToCreate, campaign, organizationUnit); + crudRepository.save(visibilityDB); + } + + @Override + public void update(Visibility visibilityToUpdate) throws VisibilityNotFoundException { + VisibilityDB visibilityDB = crudRepository.findVisibilityByCampaignIdAndOuId( + visibilityToUpdate.campaignId(), visibilityToUpdate.organizationalUnitId()) + .orElseThrow(VisibilityNotFoundException::new); + + visibilityDB.updateDates(visibilityToUpdate); + crudRepository.save(visibilityDB); + } + + @Override + public Visibility getVisibilityBySurveyUnitId(String surveyUnitId) { + return VisibilityDB.toModel(crudRepository + .getVisibilityBySurveyUnitId(surveyUnitId)); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java new file mode 100644 index 00000000..d56d832e --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java @@ -0,0 +1,71 @@ +package fr.insee.pearljam.infrastructure.campaign.entity; + +import fr.insee.pearljam.api.domain.VisibilityDB; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.io.Serializable; +import java.util.List; + +@Entity(name = "communication_template") +@Table(uniqueConstraints = { + @UniqueConstraint(columnNames = {"type", "medium", "campaign_id", "organization_unit_id"}) +}) +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class CommunicationTemplateDB implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column + private String messhugahId; + + @Column + @Enumerated(EnumType.STRING) + private CommunicationMedium medium; + + @Column + @Enumerated(EnumType.STRING) + private CommunicationType type; + + /** + * The reference to visibility table + */ + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "organization_unit_id", referencedColumnName = "organization_unit_id", insertable = false, updatable = false) + @JoinColumn(name = "campaign_id", referencedColumnName = "campaign_id", insertable = false, updatable = false) + private VisibilityDB visibility; + + public static List toModel(List communicationTemplatesDB) { + return communicationTemplatesDB.stream() + .map(communicationTemplateDB -> new CommunicationTemplate( + communicationTemplateDB.getId(), + communicationTemplateDB.getMesshugahId(), + communicationTemplateDB.getMedium(), + communicationTemplateDB.getType())) + .toList(); + } + + public static List fromModel(List communicationTemplates) { + return communicationTemplates.stream() + .map(communicationTemplate -> new CommunicationTemplateDB(null, + communicationTemplate.messhugahId(), + communicationTemplate.medium(), + communicationTemplate.type(), + null)) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/VisibilityJpaRepository.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/VisibilityJpaRepository.java new file mode 100644 index 00000000..5549838d --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/VisibilityJpaRepository.java @@ -0,0 +1,63 @@ +package fr.insee.pearljam.infrastructure.campaign.jpa; + +import java.util.List; +import java.util.Optional; + +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import org.springframework.data.repository.query.Param; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import fr.insee.pearljam.api.domain.VisibilityDB; +import fr.insee.pearljam.api.domain.VisibilityDBId; + +public interface VisibilityJpaRepository extends JpaRepository { + + @Query(value = "SELECT * " + + "FROM visibility " + + "WHERE campaign_id=?1 AND organization_unit_id=?2", nativeQuery = true) + Optional findVisibilityByCampaignIdAndOuId(String campaignId, String organizationalUnitId); + + @Query(value = "SELECT * " + + "FROM visibility " + + "WHERE campaign_id=?1 AND organization_unit_id=?2 " + + "AND management_start_date<=?3 " + + "AND collection_start_date<=?3 " + + "AND collection_end_date>?3", nativeQuery = true) + Optional findVisibilityInCollectionPeriod(String campaignId, String organizationalUnitId, Long date); + + @Query(value = "SELECT * " + + "FROM visibility " + + "WHERE campaign_id=:campaignId AND organization_unit_id IN (:ouIds) " + + "AND management_start_date<=:date " + + "AND collection_start_date<=:date " + + "AND collection_end_date>:date", nativeQuery = true) + List findVisibilityInCollectionPeriodForOUs(@Param("campaignId") String campaignId, + @Param("ouIds") List ouIds, + @Param("date") Long date); + + @Query(value = "SELECT vi " + + "FROM VisibilityDB vi " + + "INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id " + + "WHERE su.id=?1 AND su.organizationUnit.id = vi.organizationUnit.id") + VisibilityDB getVisibilityBySurveyUnitId(String surveyUnitId); + + @Query(value = "SELECT vi " + + "FROM VisibilityDB vi " + + "INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id " + + "WHERE su.organizationUnit.id = vi.organizationUnit.id " + + "AND su.id IN (:SUids)") + List findAllVisibilityBySurveyUnitIds(@Param("SUids") List surveyUnitIds); + + @Query(value = "SELECT new fr.insee.pearljam.domain.campaign.model.CampaignVisibility(MIN(vi.managementStartDate), MIN(vi.interviewerStartDate), MIN(vi.identificationPhaseStartDate), MIN(vi.collectionStartDate), MAX(vi.collectionEndDate), MAX(vi.endDate)) " + + "FROM VisibilityDB vi " + + "INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id " + + "WHERE vi.campaign.id=:campaignId AND vi.organizationUnit.id IN (:OUids)") + CampaignVisibility findVisibilityByCampaignId(@Param("campaignId") String campaignId, + @Param("OUids") List organizationalUnitIds); + + List findByCampaignId(String campaignId); + + Optional findByCampaignIdIgnoreCaseAndOrganizationUnitIdIgnoreCase(String campaignId, + String organizationalUnitId); +} diff --git a/src/main/resources/db/changelog/541_add_communication_template.xml b/src/main/resources/db/changelog/541_add_communication_template.xml new file mode 100644 index 00000000..97aebf69 --- /dev/null +++ b/src/main/resources/db/changelog/541_add_communication_template.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/db/master.xml b/src/main/resources/db/master.xml index b28a6305..384bd09a 100644 --- a/src/main/resources/db/master.xml +++ b/src/main/resources/db/master.xml @@ -45,4 +45,7 @@ + + + \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java index 6efd3bb3..e018b10b 100644 --- a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java +++ b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java @@ -27,6 +27,7 @@ import java.util.List; import java.util.Optional; +import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignUpdateDto; import fr.insee.pearljam.api.service.*; import org.json.JSONException; import org.junit.jupiter.api.BeforeEach; @@ -77,10 +78,9 @@ import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.api.domain.Title; import fr.insee.pearljam.api.domain.User; -import fr.insee.pearljam.api.domain.Visibility; +import fr.insee.pearljam.api.domain.VisibilityDB; import fr.insee.pearljam.api.dto.address.AddressDto; -import fr.insee.pearljam.api.dto.campaign.CampaignContextDto; -import fr.insee.pearljam.api.dto.campaign.CampaignDto; +import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; import fr.insee.pearljam.api.surveyunit.dto.CommentDto; import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; @@ -98,8 +98,8 @@ import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitInterviewerLinkDto; import fr.insee.pearljam.api.dto.user.UserContextDto; import fr.insee.pearljam.api.dto.user.UserDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityContextDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityDto; +import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignCreateDto; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitVisibilityDto; import fr.insee.pearljam.api.exception.NotFoundException; import fr.insee.pearljam.api.repository.CampaignRepository; import fr.insee.pearljam.api.repository.ClosingCauseRepository; @@ -109,7 +109,7 @@ import fr.insee.pearljam.api.repository.StateRepository; import fr.insee.pearljam.api.repository.SurveyUnitRepository; import fr.insee.pearljam.api.repository.UserRepository; -import fr.insee.pearljam.api.repository.VisibilityRepository; +import fr.insee.pearljam.infrastructure.campaign.jpa.VisibilityJpaRepository; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import lombok.RequiredArgsConstructor; @@ -129,7 +129,7 @@ class TestAuthKeyCloak { private final UserRepository userRepository; private final SurveyUnitRepository surveyUnitRepository; private final CampaignRepository campaignRepository; - private final VisibilityRepository visibilityRepository; + private final VisibilityJpaRepository visibilityRepository; private final MessageRepository messageRepository; private final OrganizationUnitRepository organizationUnitRepository; private final InterviewerRepository interviewerRepository; @@ -956,7 +956,7 @@ void testPutVisibilityModifyAllDates() throws Exception { .content(campaignInput)) .andExpect(status().isOk()); - Optional visi = visibilityRepository.findVisibilityByCampaignIdAndOuId("SIMPSONS2020X00", + Optional visi = visibilityRepository.findVisibilityByCampaignIdAndOuId("SIMPSONS2020X00", "OU-NORTH"); assertEquals(true, visi.isPresent()); assertEquals(1575937000000L, visi.get().getManagementStartDate()); @@ -991,7 +991,7 @@ void testPutVisibilityModifyCollectionStartDate() status().isOk(), expectValidCollectionStartDate()); - Optional visi = visibilityRepository.findVisibilityByCampaignIdAndOuId("SIMPSONS2020X00", + Optional visi = visibilityRepository.findVisibilityByCampaignIdAndOuId("SIMPSONS2020X00", "OU-NORTH"); assertEquals(true, visi.isPresent()); assertEquals(now, visi.get().getCollectionStartDate()); @@ -1018,7 +1018,7 @@ void testPutVisibilityModifyCollectionEndDate() .contentType(MediaType.APPLICATION_JSON) .content(jsonContent)) .andExpect(status().isOk()); - Optional visi = visibilityRepository.findVisibilityByCampaignIdAndOuId("SIMPSONS2020X00", + Optional visi = visibilityRepository.findVisibilityByCampaignIdAndOuId("SIMPSONS2020X00", "OU-NORTH"); assertEquals(true, visi.isPresent()); assertEquals(now, visi.get().getCollectionEndDate()); @@ -1343,12 +1343,12 @@ void testGetSUClosable() throws Exception { .contentType(MediaType.APPLICATION_JSON) .body(expectedBody)); - Optional visiOpt = visibilityRepository.findVisibilityByCampaignIdAndOuId("VQS2021X00", "OU-NORTH"); + Optional visiOpt = visibilityRepository.findVisibilityByCampaignIdAndOuId("VQS2021X00", "OU-NORTH"); if (visiOpt.isEmpty()) { fail("No visibility found for VQS2021X00 and OU-NORTH"); } - Visibility visi = visiOpt.get(); + VisibilityDB visi = visiOpt.get(); Long collectionEndDate = visi.getCollectionEndDate(); Long endDate = visi.getEndDate(); @@ -1571,18 +1571,20 @@ void testGetOrganizationUnits() throws Exception { @Test @Order(100) void testPostCampaignContext() throws Exception { - CampaignContextDto campDto = new CampaignContextDto(); - campDto.setCampaign("campId"); - campDto.setCampaignLabel("An other campaign"); - campDto.setReferents(List.of(new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"))); - campDto.setIdentificationConfiguration(IdentificationConfiguration.IASCO); - campDto.setContactOutcomeConfiguration(ContactOutcomeConfiguration.F2F); - campDto.setContactAttemptConfiguration(ContactAttemptConfiguration.F2F); - - VisibilityContextDto visi1 = generateDumbVisibilityContextDto("OU-NORTH"); - VisibilityContextDto visi2 = generateDumbVisibilityContextDto("OU-SOUTH"); - - campDto.setVisibilities(List.of(visi1, visi2)); + VisibilityCampaignCreateDto visi1 = generateDumbVisibilityCampaignCreateDto("OU-NORTH"); + VisibilityCampaignCreateDto visi2 = generateDumbVisibilityCampaignCreateDto("OU-SOUTH"); + + CampaignCreateDto campDto = new CampaignCreateDto( + "campId", + "An other campaign", + List.of(visi1, visi2), + List.of(new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY")), + null, + IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + null + ); mockMvc.perform(post(Constants.API_CAMPAIGN) .with(authentication(ADMIN)) @@ -1594,13 +1596,13 @@ void testPostCampaignContext() throws Exception { assertTrue(campOpt.isPresent()); assertEquals("An other campaign", campOpt.get().getLabel()); - Optional visi1Opt = visibilityRepository.findVisibilityByCampaignIdAndOuId("CAMPID", "OU-NORTH"); - Optional visi2Opt = visibilityRepository.findVisibilityByCampaignIdAndOuId("CAMPID", "OU-SOUTH"); + Optional visi1Opt = visibilityRepository.findVisibilityByCampaignIdAndOuId("CAMPID", "OU-NORTH"); + Optional visi2Opt = visibilityRepository.findVisibilityByCampaignIdAndOuId("CAMPID", "OU-SOUTH"); assertTrue(visi1Opt.isPresent()); assertTrue(visi2Opt.isPresent()); - Visibility visi = visi1Opt.get(); + VisibilityDB visi = visi1Opt.get(); assertEquals(1111L, visi.getCollectionStartDate()); assertEquals(2222L, visi.getCollectionEndDate()); assertEquals(3333L, visi.getIdentificationPhaseStartDate()); @@ -1632,14 +1634,20 @@ void testPostCampaignContext() throws Exception { @Test @Order(101) void testPostCampaignContextNoLabel() throws Exception { - CampaignContextDto campDto = new CampaignContextDto(); - campDto.setCampaign("campId2"); - // Campaign label unset - - VisibilityContextDto visi1 = generateDumbVisibilityContextDto("OU-NORTH"); - VisibilityContextDto visi2 = generateDumbVisibilityContextDto("OU-SOUTH"); - - campDto.setVisibilities(List.of(visi1, visi2)); + VisibilityCampaignCreateDto visi1 = generateDumbVisibilityCampaignCreateDto("OU-NORTH"); + VisibilityCampaignCreateDto visi2 = generateDumbVisibilityCampaignCreateDto("OU-SOUTH"); + + CampaignCreateDto campDto = new CampaignCreateDto( + "campId2", + null, + List.of(visi1, visi2), + null, + null, + null, + null, + null, + null + ); mockMvc.perform(post(Constants.API_CAMPAIGN) .with(authentication(ADMIN)) @@ -1650,7 +1658,6 @@ void testPostCampaignContextNoLabel() throws Exception { // Campaign should not have been created Optional campOpt = campaignRepository.findById("campId2"); assertTrue(!campOpt.isPresent()); - } /** @@ -1664,13 +1671,20 @@ void testPostCampaignContextNoLabel() throws Exception { @Order(102) void testPostCampaignContextMissingOU() throws Exception { - CampaignContextDto campDto = new CampaignContextDto(); - campDto.setCampaign("campId3"); - // Campaign label unset - - VisibilityContextDto visi1 = generateDumbVisibilityContextDto("OU-NORTH"); - VisibilityContextDto visi2 = generateDumbVisibilityContextDto("AN-OU-THAT-DOESNT-EXIST"); - campDto.setVisibilities(List.of(visi1, visi2)); + VisibilityCampaignCreateDto visi1 = generateDumbVisibilityCampaignCreateDto("OU-NORTH"); + VisibilityCampaignCreateDto visi2 = generateDumbVisibilityCampaignCreateDto("AN-OU-THAT-DOESNT-EXIST"); + + CampaignCreateDto campDto = new CampaignCreateDto( + "campId3", + null, + List.of(visi1, visi2), + null, + null, + null, + null, + null, + null + ); mockMvc.perform(post(Constants.API_CAMPAIGN) .with(authentication(ADMIN)) @@ -2485,115 +2499,14 @@ void testOngoingNotFound() throws Exception { .andExpect(status().isNotFound()); } - @Test - @Order(220) - void testPutCampaign() throws Exception { - CampaignContextDto campaignContext = new CampaignContextDto(); - campaignContext.setCampaign("ZCLOSEDX00"); - campaignContext.setCampaignLabel("Everyday life and health survey 2021"); - - VisibilityContextDto wvcd = generateVisibilityContextDto("OU-WEST", "ZCLOSEDX00"); - wvcd.setOrganizationalUnit("OU-WEST"); - wvcd.setEndDate(wvcd.getEndDate() + 1); - - VisibilityContextDto svcd = generateVisibilityContextDto("OU-SOUTH", "ZCLOSEDX00"); - svcd.setOrganizationalUnit("OU-SOUTH"); - - VisibilityContextDto emptyVcd = new VisibilityContextDto(); - emptyVcd.setOrganizationalUnit("OU-WEST"); - - VisibilityContextDto missingVcd = generateVisibilityContextDto("OU-SOUTH", "ZCLOSEDX00"); - missingVcd.setOrganizationalUnit("OU-TEAPOT"); - - VisibilityContextDto invalidVcd = generateVisibilityContextDto("OU-WEST", "ZCLOSEDX00"); - invalidVcd.setOrganizationalUnit("OU-WEST"); - invalidVcd.setInterviewerStartDate(invalidVcd.getIdentificationPhaseStartDate()); - - // path variable campaignId not found in DB - mockMvc.perform(put("/api/campaign/MISSING") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignContext))) - .andExpect(status().isNotFound()); - - // BAD REQUESTS - campaignContext.setCampaignLabel(null); - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignContext))) - .andExpect(status().isBadRequest()); - - campaignContext.setCampaignLabel(" "); - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignContext))) - .andExpect(status().isBadRequest()); - - campaignContext.setCampaignLabel(""); - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignContext))) - .andExpect(status().isBadRequest()); - - campaignContext.setCampaignLabel("Everyday life and health survey 2021"); - campaignContext.setVisibilities(List.of(emptyVcd)); - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignContext))) - .andExpect(status().isBadRequest()); - - // NOT FOUND VISIBILITY - campaignContext.setVisibilities(List.of(missingVcd)); - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignContext))) - .andExpect(status().isNotFound()); - - // CONFLICT due to visibilities - campaignContext.setVisibilities(List.of(invalidVcd)); - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignContext))) - .andExpect(status().isConflict()); - - // 200 - campaignContext.setVisibilities(List.of(wvcd, svcd)); - campaignContext.setEmail("updated.email@test.com"); - campaignContext.setContactAttemptConfiguration(ContactAttemptConfiguration.TEL); - campaignContext.setContactOutcomeConfiguration(ContactOutcomeConfiguration.TEL); - campaignContext.setIdentificationConfiguration(IdentificationConfiguration.NOIDENT); - - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignContext))) - .andExpect(status().isOk()); - - assertEquals(wvcd.getEndDate(), - visibilityRepository.findVisibilityByCampaignIdAndOuId("ZCLOSEDX00", "OU-WEST").get().getEndDate()); - CampaignDto updatedCampaign = campaignRepository.findDtoById("ZCLOSEDX00"); - assertEquals("updated.email@test.com", updatedCampaign.getEmail()); - assertEquals(ContactAttemptConfiguration.TEL, updatedCampaign.getContactAttemptConfiguration()); - assertEquals(ContactOutcomeConfiguration.TEL, updatedCampaign.getContactOutcomeConfiguration()); - assertEquals(IdentificationConfiguration.NOIDENT, updatedCampaign.getIdentificationConfiguration()); - } - @Test @Order(221) void testUpdateVisibilityByOu() throws Exception { - VisibilityDto visibility = generateVisibilityContextDto("OU-WEST", "ZCLOSEDX00"); - visibility.setEndDate(visibility.getEndDate() + 1); - VisibilityDto invalidVcd = generateVisibilityContextDto("OU-WEST", "ZCLOSEDX00"); - invalidVcd.setInterviewerStartDate(invalidVcd.getIdentificationPhaseStartDate()); + SurveyUnitVisibilityDto visibility = generateSurveyUnitVisibilityDto("OU-WEST", "ZCLOSEDX00", false); + SurveyUnitVisibilityDto invalidVcd = generateSurveyUnitVisibilityDto("OU-WEST", "ZCLOSEDX00", true); String visibilityJson = asJsonString(visibility); - String emptyVisibilityJson = asJsonString(new VisibilityDto()); + String emptyVisibilityJson = "{}"; String invalidVisibilityJson = asJsonString(invalidVcd); // BAD REQUEST @@ -2607,7 +2520,7 @@ void testUpdateVisibilityByOu() throws Exception { // OK updateVisibility("ZCLOSEDX00", "OU-WEST", visibilityJson).andExpect(status().isOk()); - assertEquals(visibility.getEndDate(), + assertEquals(visibility.endDate(), visibilityRepository.findVisibilityByCampaignIdAndOuId("ZCLOSEDX00", "OU-WEST").get().getEndDate()); } @@ -2680,29 +2593,41 @@ private InterviewerContextDto generateInterviewerBContextDto(String id) { Title.MISS); } - private VisibilityContextDto generateDumbVisibilityContextDto(String ouId) { - VisibilityContextDto vcd = new VisibilityContextDto(); - vcd.setOrganizationalUnit(ouId); - vcd.setCollectionStartDate(1111L); - vcd.setCollectionEndDate(2222L); - vcd.setIdentificationPhaseStartDate(3333L); - vcd.setInterviewerStartDate(4444L); - vcd.setManagementStartDate(5555L); - vcd.setEndDate(6666L); - return vcd; - } - - private VisibilityContextDto generateVisibilityContextDto(String OuId, String campaignId) { - Visibility vis = visibilityRepository.findVisibilityByCampaignIdAndOuId(campaignId, OuId).get(); - VisibilityContextDto vcd = new VisibilityContextDto(); - vcd.setOrganizationalUnit(vis.getOrganizationUnit().getId()); - vcd.setCollectionEndDate(vis.getCollectionEndDate()); - vcd.setCollectionStartDate(vis.getCollectionStartDate()); - vcd.setEndDate(vis.getEndDate()); - vcd.setIdentificationPhaseStartDate(vis.getIdentificationPhaseStartDate()); - vcd.setInterviewerStartDate(vis.getInterviewerStartDate()); - vcd.setManagementStartDate(vis.getManagementStartDate()); - return vcd; + private VisibilityCampaignCreateDto generateDumbVisibilityCampaignCreateDto(String ouId) { + return new VisibilityCampaignCreateDto(5555L, 4444L, + 3333L, 1111L, + 2222L, 6666L, ouId, null); + } + + private VisibilityCampaignCreateDto generateVisibilityCampaignCreateDto(String OuId, String campaignId) { + VisibilityDB vis = visibilityRepository.findVisibilityByCampaignIdAndOuId(campaignId, OuId).get(); + return new VisibilityCampaignCreateDto(vis.getManagementStartDate(), vis.getInterviewerStartDate(), + vis.getIdentificationPhaseStartDate(), vis.getCollectionStartDate(), + vis.getCollectionEndDate(), vis.getEndDate(), vis.getOrganizationUnit().getId(), null); + } + + private VisibilityCampaignUpdateDto generateVisibilityCampaignUpdateDto(String OuId, String campaignId, boolean isInvalid) { + VisibilityDB vis = visibilityRepository.findVisibilityByCampaignIdAndOuId(campaignId, OuId).get(); + Long interviewerStartDate = vis.getInterviewerStartDate(); + if(isInvalid) { + interviewerStartDate = vis.getIdentificationPhaseStartDate(); + } + return new VisibilityCampaignUpdateDto(vis.getManagementStartDate(), interviewerStartDate, + vis.getIdentificationPhaseStartDate(), vis.getCollectionStartDate(), + vis.getCollectionEndDate(), vis.getEndDate(), vis.getOrganizationUnit().getId()); + } + + private SurveyUnitVisibilityDto generateSurveyUnitVisibilityDto(String ouId, String campaignId, + boolean isInvalid) { + VisibilityDB vis = visibilityRepository.findVisibilityByCampaignIdAndOuId(campaignId, ouId).get(); + + Long interviewerStartDate = vis.getInterviewerStartDate(); + if(isInvalid) { + interviewerStartDate = vis.getIdentificationPhaseStartDate(); + } + return new SurveyUnitVisibilityDto(vis.getManagementStartDate(), interviewerStartDate, + vis.getIdentificationPhaseStartDate(), vis.getCollectionStartDate(), + vis.getCollectionEndDate(), vis.getEndDate()); } private UserDto generateValidUser() { diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java new file mode 100644 index 00000000..fa3af95a --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java @@ -0,0 +1,286 @@ +package fr.insee.pearljam.api.campaign.controller; + +import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; +import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignCreateDto; +import fr.insee.pearljam.api.constants.Constants; +import fr.insee.pearljam.api.controller.CampaignController; +import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; +import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.dto.referent.ReferentDto; +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.MockMvcTestUtils; +import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; +import fr.insee.pearljam.api.web.exception.ExceptionControllerAdvice; +import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; +import org.javatuples.Pair; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import fr.insee.pearljam.api.service.dummy.CampaignFakeService; +import fr.insee.pearljam.api.service.dummy.ReferentFakeService; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class CampaignControllerCreateTest { + private CampaignFakeService campaignService; + private MockMvc mockMvc; + + @BeforeEach + void setup() { + campaignService = new CampaignFakeService(); + ReferentFakeService referentService = new ReferentFakeService(); + AuthenticationUserFakeService authenticatedUserService = new AuthenticationUserFakeService(AuthenticatedUserTestHelper.AUTH_ADMIN); + CampaignController campaignController = new CampaignController(campaignService, referentService, authenticatedUserService); + mockMvc = MockMvcBuilders + .standaloneSetup(campaignController) + .setControllerAdvice(MockMvcTestUtils.createExceptionControllerAdvice()) + .build(); + } + + @Test + @DisplayName("Should create campaign") + void testCreateCampaign01() throws Exception { + Pair firstVisibility = generateVisibility("OU-NORTH", 1721683250L, + 1721683251L, + 1721683252L, + 1721683253L, + 1721683254L, + 1721683255L); + Pair secondVisibility = generateVisibility("OU-SOUTH", 1721683260L, + 1721683261L, + 1721683262L, + 1721683263L, + 1721683264L, + 1721683265L); + Pair firstReferent = generateReferent("Bob", "Marley", "0123456789", "PRIMARY"); + Pair secondReferent = generateReferent("Dupont", "Jean", "1234567890", "PRIMARY"); + Pair campaign = generateCampaign("campId", "An other campaign", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(firstVisibility, secondVisibility), + List.of(firstReferent, secondReferent)); + + mockMvc.perform(post(Constants.API_CAMPAIGN) + .contentType(MediaType.APPLICATION_JSON) + .content(campaign.getValue0())) + .andExpect(status().isOk()); + + CampaignCreateDto campaignCreated = campaignService.getCampaignCreated(); + assertThat(campaignCreated).isEqualTo(campaign.getValue1()); + } + + @Test + @DisplayName("Should return bad request when campaign already exists") + void testCreateCampaign02() throws Exception { + campaignService.setShouldThrowCampaignAlreadyExistException(true); + Pair visibility = generateVisibility("OU-SOUTH", 1721683260L, + 1721683261L, + 1721683262L, + 1721683263L, + 1721683264L, + 1721683265L); + Pair campaign = generateCampaign("campId", "An other campaign", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(visibility), + List.of()); + + mockMvc.perform(post(Constants.API_CAMPAIGN) + .contentType(MediaType.APPLICATION_JSON) + .content(campaign.getValue0())) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, CampaignAlreadyExistException.MESSAGE)); + } + + @Test + @DisplayName("Should return bad request when invalid campaign input") + void testCreateCampaign03() throws Exception { + + Pair visibility = generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L); + Pair campaign1 = generateCampaign(" ", "An other campaign", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(visibility), + List.of()); + Pair campaign2 = generateCampaign("campId", " ", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(visibility), + List.of()); + List> campaigns = List.of(campaign1, campaign2); + for(Pair campaign : campaigns) { + mockMvc.perform(post(Constants.API_CAMPAIGN) + .contentType(MediaType.APPLICATION_JSON) + .content(campaign.getValue0())) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); + + CampaignCreateDto campaignCreated = campaignService.getCampaignCreated(); + + assertThat(campaignCreated).isNull(); + } + } + + @Test + @DisplayName("Should return bad request when invalid visibility") + void testCreateCampaign04() throws Exception { + List> invalidVisibilities = new ArrayList<>(Arrays.asList( + generateVisibility(" ", 1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L), + generateVisibility("OU-NORTH", null, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L), + generateVisibility("OU-NORTH", 1721683250L, null, 1721683252L, + 1721683253L, 1721683254L, 1721683255L), + generateVisibility("OU-NORTH", 1721683250L, 1721683251L, null, + 1721683253L, 1721683254L, 1721683255L), + generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, + null, 1721683254L, 1721683255L), + generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, + 1721683253L, null, 1721683255L), + generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, null) + )); + invalidVisibilities.add(null); + + for(Pair invalidVisibility : invalidVisibilities) { + List> invalidCampaignVisibilities = List.of(); + if(invalidVisibility != null) { + invalidCampaignVisibilities = List.of(invalidVisibility); + } + Pair campaign = generateCampaign("campId", "campaignLabel", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + invalidCampaignVisibilities, + List.of()); + mockMvc.perform(post(Constants.API_CAMPAIGN) + .contentType(MediaType.APPLICATION_JSON) + .content(campaign.getValue0())) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); + + CampaignCreateDto campaignCreated = campaignService.getCampaignCreated(); + + assertThat(campaignCreated).isNull(); + } + + } + + private Pair generateCampaign(String campaignId, String campaignLabel, + String email, IdentificationConfiguration identificationConfiguration, + ContactOutcomeConfiguration contactOutcomeConfiguration, + ContactAttemptConfiguration contactAttemptConfiguration, + Boolean communicationRequestConfiguration, + List> visibilities, + List> referents) { + StringBuilder visibilitiesJson = new StringBuilder("\"visibilities\": ["); + for(Pair visibility : visibilities) { + visibilitiesJson.append(visibility.getValue0()); + if(!visibility.getValue0().equals(visibilities.getLast().getValue0())) { + visibilitiesJson.append(", "); + } + } + visibilitiesJson.append("], "); + + StringBuilder referentsJson = new StringBuilder("\"referents\": ["); + for(Pair referent : referents) { + referentsJson.append(referent.getValue0()); + if(!referent.getValue0().equals(referents.getLast().getValue0())) { + referentsJson.append(", "); + } + } + referentsJson.append("], "); + + String campaignTemplate = """ + {""" + visibilitiesJson + referentsJson + """ + "campaign": "%s", + "campaignLabel": "%s", + "email": "%s", + "identificationConfiguration": "%s", + "contactOutcomeConfiguration": "%s", + "contactAttemptConfiguration": "%s", + "communicationRequestConfiguration": %b + } + """; + String campaignJson = String.format(campaignTemplate, campaignId, campaignLabel, email, identificationConfiguration, + contactOutcomeConfiguration, contactAttemptConfiguration, communicationRequestConfiguration); + + CampaignCreateDto campaignCreateDto = new CampaignCreateDto(campaignId, + campaignLabel, + visibilities.stream() + .map(Pair::getValue1) + .toList(), + referents.stream() + .map(Pair::getValue1) + .toList(), + email, + IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + communicationRequestConfiguration + ); + + return Pair.with(campaignJson, campaignCreateDto); + } + + /** + * Generate a pair of visibility json string and visbility create dto + * @param organizationalUnit + * @param managementDate + * @param interviewerDate + * @param identificationDate + * @param collectionStartDate + * @param collectionEndDate + * @param endDate + * @return + */ + private Pair generateVisibility(String organizationalUnit, + Long managementDate, Long interviewerDate, + Long identificationDate, Long collectionStartDate, + Long collectionEndDate, Long endDate) { + String visibilityPlaceHolder = """ + { + "organizationalUnit": "%s", + "managementStartDate": %d, + "interviewerStartDate": %d, + "identificationPhaseStartDate": %d, + "collectionStartDate": %d, + "collectionEndDate": %d, + "endDate": %d + }"""; + String visibilityJson = String.format(String.format(visibilityPlaceHolder, organizationalUnit, + managementDate, interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate)); + + VisibilityCampaignCreateDto visibilityCampaignCreateDto = new VisibilityCampaignCreateDto(managementDate, + interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit, null); + return Pair.with(visibilityJson, visibilityCampaignCreateDto); + } + + private Pair generateReferent(String firstName, String lastName, String phoneNumber, String role) { + String referentPlaceHolder = """ + { + "firstName": "%s", + "lastName": "%s", + "phoneNumber": "%s", + "role": "%s" + }"""; + String referentJson = String.format(referentPlaceHolder, firstName, lastName, phoneNumber, role); + + ReferentDto referentDto = new ReferentDto(firstName, lastName, phoneNumber, role); + return Pair.with(referentJson, referentDto); + } +} diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java new file mode 100644 index 00000000..e3ac6ade --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java @@ -0,0 +1,354 @@ +package fr.insee.pearljam.api.campaign.controller; + +import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignUpdateDto; +import fr.insee.pearljam.api.constants.Constants; +import fr.insee.pearljam.api.controller.CampaignController; +import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; +import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.dto.referent.ReferentDto; +import fr.insee.pearljam.api.service.dummy.CampaignFakeService; +import fr.insee.pearljam.api.service.dummy.ReferentFakeService; +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.MockMvcTestUtils; +import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; +import fr.insee.pearljam.api.web.exception.ExceptionControllerAdvice; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import org.javatuples.Pair; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class CampaignControllerUpdateTest { + + private CampaignFakeService campaignService; + private final String updatePath = "/api/campaign/11"; + private MockMvc mockMvc; + + @BeforeEach + void setup() { + campaignService = new CampaignFakeService(); + ReferentFakeService referentService = new ReferentFakeService(); + AuthenticationUserFakeService authenticatedUserService = new AuthenticationUserFakeService(AuthenticatedUserTestHelper.AUTH_ADMIN); + CampaignController campaignController = new CampaignController(campaignService, referentService, authenticatedUserService); + mockMvc = MockMvcBuilders + .standaloneSetup(campaignController) + .setControllerAdvice(MockMvcTestUtils.createExceptionControllerAdvice()) + .build(); + } + + @Test + @DisplayName("Should update campaign") + void testUpdateCampaign01() throws Exception { + Pair firstVisibility = generateVisibility("OU-NORTH", 1721683250L, + 1721683251L, + 1721683252L, + 1721683253L, + 1721683254L, + 1721683255L); + Pair secondVisibility = generateVisibility("OU-SOUTH", 1721683260L, + 1721683261L, + 1721683262L, + 1721683263L, + 1721683264L, + 1721683265L); + Pair firstReferent = generateReferent("Bob", "Marley", "0123456789", "PRIMARY"); + Pair secondReferent = generateReferent("Dupont", "Jean", "1234567890", "PRIMARY"); + Pair campaign = generateCampaign("An other campaign", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(firstVisibility, secondVisibility), + List.of(firstReferent, secondReferent)); + + mockMvc.perform(put(updatePath) + .contentType(MediaType.APPLICATION_JSON) + .content(campaign.getValue0())) + .andExpect(status().isOk()); + + CampaignUpdateDto campaignUpdated = campaignService.getCampaignUpdated(); + assertThat(campaignUpdated).isEqualTo(campaign.getValue1()); + } + + @Test + @DisplayName("Should return not found when campaign does not exists") + void testUpdateCampaign02() throws Exception { + campaignService.setShouldThrowCampaignNotFoundException(true); + Pair visibility = generateVisibility("OU-SOUTH", 1721683260L, + 1721683261L, + 1721683262L, + 1721683263L, + 1721683264L, + 1721683265L); + Pair campaign = generateCampaign("An other campaign", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(visibility), + List.of()); + + mockMvc.perform(put(updatePath) + .contentType(MediaType.APPLICATION_JSON) + .content(campaign.getValue0())) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updatePath, CampaignNotFoundException.MESSAGE)); + } + + @Test + @DisplayName("Should return not found when visibility does not exist") + void testUpdateCampaign03() throws Exception { + campaignService.setShouldThrowVisibilityNotFoundException(true); + Pair visibility = generateVisibility("OU-SOUTH", 1721683260L, + 1721683261L, + 1721683262L, + 1721683263L, + 1721683264L, + 1721683265L); + Pair campaign = generateCampaign("An other campaign", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(visibility), + List.of()); + + mockMvc.perform(put(updatePath) + .contentType(MediaType.APPLICATION_JSON) + .content(campaign.getValue0())) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updatePath, VisibilityNotFoundException.MESSAGE)); + } + + @Test + @DisplayName("Should return bad request when invalid campaign input") + void testUpdateCampaign04() throws Exception { + Pair campaign = generateCampaign(" ", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(), + List.of()); + mockMvc.perform(put(updatePath) + .contentType(MediaType.APPLICATION_JSON) + .content(campaign.getValue0())) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); + + CampaignUpdateDto campaignUpdated = campaignService.getCampaignUpdated(); + + assertThat(campaignUpdated).isNull(); + } + + @Test + @DisplayName("Should return bad request when invalid visibility") + void testUpdateCampaign05() throws Exception { + Pair visibility = generateVisibility(" ", 1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L); + Pair campaign = generateCampaign("campaignLabel", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(visibility), + List.of()); + mockMvc.perform(put(updatePath) + .contentType(MediaType.APPLICATION_JSON) + .content(campaign.getValue0())) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); + + CampaignUpdateDto campaignUpdated = campaignService.getCampaignUpdated(); + + assertThat(campaignUpdated).isNull(); + } + + private Pair generateCampaign(String campaignLabel, + String email, IdentificationConfiguration identificationConfiguration, + ContactOutcomeConfiguration contactOutcomeConfiguration, + ContactAttemptConfiguration contactAttemptConfiguration, + Boolean communicationRequestConfiguration, + List> visibilities, + List> referents) { + StringBuilder visibilitiesJson = new StringBuilder("\"visibilities\": ["); + for(Pair visibility : visibilities) { + visibilitiesJson.append(visibility.getValue0()); + if(!visibility.getValue0().equals(visibilities.getLast().getValue0())) { + visibilitiesJson.append(", "); + } + } + visibilitiesJson.append("], "); + + StringBuilder referentsJson = new StringBuilder("\"referents\": ["); + for(Pair referent : referents) { + referentsJson.append(referent.getValue0()); + if(!referent.getValue0().equals(referents.getLast().getValue0())) { + referentsJson.append(", "); + } + } + referentsJson.append("], "); + + String campaignTemplate = """ + {""" + visibilitiesJson + referentsJson + """ + "campaignLabel": "%s", + "email": "%s", + "identificationConfiguration": "%s", + "contactOutcomeConfiguration": "%s", + "contactAttemptConfiguration": "%s", + "communicationRequestConfiguration": %b + } + """; + String campaignJson = String.format(campaignTemplate, campaignLabel, email, identificationConfiguration, + contactOutcomeConfiguration, contactAttemptConfiguration, communicationRequestConfiguration); + + CampaignUpdateDto campaignUpdateDto = new CampaignUpdateDto( + campaignLabel, + visibilities.stream() + .map(Pair::getValue1) + .toList(), + referents.stream() + .map(Pair::getValue1) + .toList(), + email, + IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + communicationRequestConfiguration + ); + + return Pair.with(campaignJson, campaignUpdateDto); + } + + /** + * Generate a pair of visibility json string and visbility create dto + * @param organizationalUnit + * @param managementDate + * @param interviewerDate + * @param identificationDate + * @param collectionStartDate + * @param collectionEndDate + * @param endDate + * @return + */ + private Pair generateVisibility(String organizationalUnit, + Long managementDate, Long interviewerDate, + Long identificationDate, Long collectionStartDate, + Long collectionEndDate, Long endDate) { + String visibilityPlaceHolder = """ + { + "organizationalUnit": "%s", + "managementStartDate": %d, + "interviewerStartDate": %d, + "identificationPhaseStartDate": %d, + "collectionStartDate": %d, + "collectionEndDate": %d, + "endDate": %d + }"""; + String visibilityJson = String.format(String.format(visibilityPlaceHolder, organizationalUnit, + managementDate, interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate)); + + VisibilityCampaignUpdateDto VisibilityCampaignUpdateDto = new VisibilityCampaignUpdateDto(managementDate, + interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit); + return Pair.with(visibilityJson, VisibilityCampaignUpdateDto); + } + + private Pair generateReferent(String firstName, String lastName, String phoneNumber, String role) { + String referentPlaceHolder = """ + { + "firstName": "%s", + "lastName": "%s", + "phoneNumber": "%s", + "role": "%s" + }"""; + String referentJson = String.format(referentPlaceHolder, firstName, lastName, phoneNumber, role); + + ReferentDto referentDto = new ReferentDto(firstName, lastName, phoneNumber, role); + return Pair.with(referentJson, referentDto); + } + + /* + @Test + @Order(220) + void testPutCampaign() throws Exception { + CampaignUpdateDto campaignUpdateDto = new CampaignUpdateDto( + "Everyday life and health survey 2021", + List.of(visi1, visi2), + List.of(new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY")), + null, + IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + null + ); + + VisibilityCampaignUpdateDto wvcd = generateVisibilityCampaignUpdateDto("OU-WEST", "ZCLOSEDX00", false); + + VisibilityCampaignUpdateDto svcd = generateVisibilityCampaignUpdateDto("OU-SOUTH", "ZCLOSEDX00", false); + + VisibilityCampaignUpdateDto emptyVcd = new VisibilityCampaignUpdateDto(null, null, + null, null, null, + null, "OU-WEST"); + + VisibilityCampaignUpdateDto missingVcd = generateVisibilityCampaignUpdateDto("OU-SOUTH", "ZCLOSEDX00", false); + missingVcd.setOrganizationalUnit("OU-TEAPOT"); + + VisibilityCampaignUpdateDto invalidVcd = generateVisibilityCampaignUpdateDto("OU-WEST", "ZCLOSEDX00", true); + + // path variable campaignId not found in DB + mockMvc.perform(put("/api/campaign/MISSING") + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(campaignUpdateDto))) + .andExpect(status().isNotFound()); + + campaignUpdateDto.setCampaignLabel("Everyday life and health survey 2021"); + campaignUpdateDto.setVisibilities(List.of(emptyVcd)); + mockMvc.perform(put("/api/campaign/ZCLOSEDX00") + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(campaignUpdateDto))) + .andExpect(status().isBadRequest()); + + // NOT FOUND VISIBILITY + campaignUpdateDto.setVisibilities(List.of(missingVcd)); + mockMvc.perform(put("/api/campaign/ZCLOSEDX00") + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(campaignUpdateDto))) + .andExpect(status().isNotFound()); + + // CONFLICT due to visibilities + campaignUpdateDto.setVisibilities(List.of(invalidVcd)); + mockMvc.perform(put("/api/campaign/ZCLOSEDX00") + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(campaignUpdateDto))) + .andExpect(status().isConflict()); + + // 200 + campaignUpdateDto.setVisibilities(List.of(wvcd, svcd)); + campaignUpdateDto.setEmail("updated.email@test.com"); + campaignUpdateDto.setContactAttemptConfiguration(ContactAttemptConfiguration.TEL); + campaignUpdateDto.setContactOutcomeConfiguration(ContactOutcomeConfiguration.TEL); + campaignUpdateDto.setIdentificationConfiguration(IdentificationConfiguration.NOIDENT); + + mockMvc.perform(put("/api/campaign/ZCLOSEDX00") + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(campaignUpdateDto))) + .andExpect(status().isOk()); + + assertEquals(wvcd.endDate(), + visibilityRepository.findVisibilityByCampaignIdAndOuId("ZCLOSEDX00", "OU-WEST").get().getEndDate()); + CampaignDto updatedCampaign = campaignRepository.findDtoById("ZCLOSEDX00"); + assertEquals("updated.email@test.com", updatedCampaign.getEmail()); + assertEquals(ContactAttemptConfiguration.TEL, updatedCampaign.getContactAttemptConfiguration()); + assertEquals(ContactOutcomeConfiguration.TEL, updatedCampaign.getContactOutcomeConfiguration()); + assertEquals(IdentificationConfiguration.NOIDENT, updatedCampaign.getIdentificationConfiguration()); + }*/ +} diff --git a/src/test/java/fr/insee/pearljam/api/controller/CampaignControllerTest.java b/src/test/java/fr/insee/pearljam/api/controller/CampaignControllerTest.java deleted file mode 100644 index 95b7c3b3..00000000 --- a/src/test/java/fr/insee/pearljam/api/controller/CampaignControllerTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package fr.insee.pearljam.api.controller; - -import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; -import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import fr.insee.pearljam.api.service.dummy.CampaignFakeService; -import fr.insee.pearljam.api.service.dummy.ReferentFakeService; - -import static org.assertj.core.api.Assertions.assertThat; - -class CampaignControllerTest { - - private CampaignController campaignController; - private CampaignFakeService campaignService; - private ReferentFakeService referentService; - private AuthenticationUserFakeService authenticatedUserService; - - @BeforeEach - public void init() { - Campaign campaign = new Campaign(); - campaignService = new CampaignFakeService(campaign); - referentService = new ReferentFakeService(); - authenticatedUserService = new AuthenticationUserFakeService(AuthenticatedUserTestHelper.AUTH_ADMIN); - campaignController = new CampaignController(campaignService, referentService, authenticatedUserService); - } - - @Test - @DisplayName("On deletion, when force is true, deletion is done") - void testDeletion() { - campaignController.deleteCampaignById( "test", true); - assertThat(campaignService.isDeleted()).isTrue(); - } -} diff --git a/src/test/java/fr/insee/pearljam/api/service/dummy/CampaignFakeService.java b/src/test/java/fr/insee/pearljam/api/service/dummy/CampaignFakeService.java index 338ea549..40a0a492 100644 --- a/src/test/java/fr/insee/pearljam/api/service/dummy/CampaignFakeService.java +++ b/src/test/java/fr/insee/pearljam/api/service/dummy/CampaignFakeService.java @@ -3,22 +3,23 @@ import java.util.List; import java.util.Optional; +import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpStatus; import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.api.domain.Response; -import fr.insee.pearljam.api.dto.campaign.CampaignContextDto; +import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; import fr.insee.pearljam.api.dto.campaign.CampaignDto; import fr.insee.pearljam.api.dto.count.CountDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityContextDto; -import fr.insee.pearljam.api.dto.visibility.VisibilityDto; -import fr.insee.pearljam.api.exception.NoOrganizationUnitException; import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.api.exception.VisibilityException; +import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; import fr.insee.pearljam.api.service.CampaignService; import lombok.Getter; +import lombok.Setter; @RequiredArgsConstructor public class CampaignFakeService implements CampaignService { @@ -26,66 +27,68 @@ public class CampaignFakeService implements CampaignService { @Getter private boolean deleted = false; - private final Campaign campaign; + @Setter + private boolean shouldThrowCampaignAlreadyExistException = false; + + @Setter + private boolean shouldThrowCampaignNotFoundException = false; + + @Setter + private boolean shouldThrowVisibilityNotFoundException = false; + + @Getter + private CampaignCreateDto campaignCreated = null; + + @Getter + private CampaignUpdateDto campaignUpdated = null; @Override public List getListCampaign(String userId) { - // TODO Auto-generated method stub throw new UnsupportedOperationException("Unimplemented method 'getListCampaign'"); } @Override public List getAllCampaigns() { - // TODO Auto-generated method stub throw new UnsupportedOperationException("Unimplemented method 'getAllCampaigns'"); } @Override public List getInterviewerCampaigns(String userId) { - // TODO Auto-generated method stub throw new UnsupportedOperationException("Unimplemented method 'getInterviewerCampaigns'"); } @Override public List getListInterviewers(String userId, String campaignId) throws NotFoundException { - // TODO Auto-generated method stub throw new UnsupportedOperationException("Unimplemented method 'getListInterviewers'"); } @Override public boolean isUserPreference(String userId, String campaignId) { - // TODO Auto-generated method stub throw new UnsupportedOperationException("Unimplemented method 'isUserPreference'"); } @Override public CountDto getNbSUAbandonedByCampaign(String userId, String campaignId) throws NotFoundException { - // TODO Auto-generated method stub throw new UnsupportedOperationException("Unimplemented method 'getNbSUAbandonedByCampaign'"); } @Override public CountDto getNbSUNotAttributedByCampaign(String userId, String campaignId) throws NotFoundException { - // TODO Auto-generated method stub throw new UnsupportedOperationException("Unimplemented method 'getNbSUNotAttributedByCampaign'"); } @Override - public HttpStatus updateVisibility(String idCampaign, String idOu, VisibilityDto updatedVisibility) { - // TODO Auto-generated method stub - throw new UnsupportedOperationException("Unimplemented method 'updateVisibility'"); + public void createCampaign(CampaignCreateDto campaignDto) + throws CampaignAlreadyExistException { + if(shouldThrowCampaignAlreadyExistException) { + throw new CampaignAlreadyExistException(); + } + campaignCreated = campaignDto; } @Override - public Response postCampaign(CampaignContextDto campaignDto) - throws NoOrganizationUnitException, VisibilityException { - // TODO Auto-generated method stub - throw new UnsupportedOperationException("Unimplemented method 'postCampaign'"); - } - - @Override - public Optional findById(String id) { - return Optional.of(campaign); + public Optional findById(String campaignId) { + throw new UnsupportedOperationException("Unimplemented method 'findById'"); } @Override @@ -94,39 +97,33 @@ public void delete(Campaign campaign) { } @Override - public HttpStatus updateCampaign(String id, CampaignContextDto campaign) { - // TODO Auto-generated method stub - throw new UnsupportedOperationException("Unimplemented method 'updateCampaign'"); + public void updateCampaign(String id, CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException{ + if(shouldThrowCampaignNotFoundException) { + throw new CampaignNotFoundException(); + } + if(shouldThrowVisibilityNotFoundException) { + throw new VisibilityNotFoundException(); + } + campaignUpdated = campaign; } @Override public boolean isCampaignOngoing(String id) { - // TODO Auto-generated method stub throw new UnsupportedOperationException("Unimplemented method 'isCampaignOngoing'"); } @Override - public List findAllVisiblitiesByCampaign(String campaignId) { - // TODO Auto-generated method stub + public List findAllVisibilitiesByCampaign(String campaignId) { throw new UnsupportedOperationException("Unimplemented method 'findAllVisiblitiesByCampaign'"); } @Override - public void persistReferents(CampaignContextDto campaignDto, Campaign campaign) { - // TODO Auto-generated method stub - throw new UnsupportedOperationException("Unimplemented method 'persistReferents'"); - } - - @Override - public CampaignContextDto getCampaignDtoById(String id) { - // TODO Auto-generated method stub + public CampaignResponseDto getCampaignDtoById(String id) { throw new UnsupportedOperationException("Unimplemented method 'getCampaignDtoById'"); } @Override - public boolean existsAny() { - // TODO Auto-generated method stub - throw new UnsupportedOperationException("Unimplemented method 'existsAny'"); + public void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNotFoundException { + throw new UnsupportedOperationException("Unimplemented method 'updateVisibility'"); } - } diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilitytTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilitytTest.java new file mode 100644 index 00000000..2024819d --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilitytTest.java @@ -0,0 +1,4 @@ +package fr.insee.pearljam.domain.campaign.model; + +public class VisibilitytTest { +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java new file mode 100644 index 00000000..9b67c662 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java @@ -0,0 +1,4 @@ +package fr.insee.pearljam.domain.campaign.model.communication; + +public class CommunicationTemplateTest { +} diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java new file mode 100644 index 00000000..19f32344 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java @@ -0,0 +1,4 @@ +package fr.insee.pearljam.infrastructure.campaign.adapter; + +public class VisibilityDaoAdapter { +} diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java new file mode 100644 index 00000000..d12110cd --- /dev/null +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java @@ -0,0 +1,4 @@ +package fr.insee.pearljam.infrastructure.campaign.entity; + +public class VisibilityDBTest { +} diff --git a/src/test/resources/application-auth.yml b/src/test/resources/application-auth.yml index c12bd417..ab1a5902 100644 --- a/src/test/resources/application-auth.yml +++ b/src/test/resources/application-auth.yml @@ -22,8 +22,8 @@ spring: password: password logging: level: - root: INFO - liquibase: WARN + root: DEBUG + liquibase: INFO feature: oidc: From a111694bce30641ca30def0c526166824ae61efc Mon Sep 17 00:00:00 2001 From: davdarras Date: Thu, 25 Jul 2024 01:42:46 +0200 Subject: [PATCH 03/48] refactor: renew visibility architecture --- pom.xml | 9 +- .../controller/VisibilityController.java | 75 ++++ .../campaign/dto/input/CampaignCreateDto.java | 1 - .../campaign/dto/input/CampaignUpdateDto.java | 1 - .../VisibilityCampaignCreateDto.java | 30 +- .../VisibilityCampaignUpdateDto.java | 17 +- .../{visibility => }/VisibilityUpdateDto.java | 12 +- .../dto/output/CampaignResponseDto.java | 1 - .../CommunicationTemplateResponseDto.java | 2 +- .../VisibilityCampaignDto.java | 2 +- .../api/controller/CampaignController.java | 77 +--- .../insee/pearljam/api/domain/Campaign.java | 1 + .../pearljam/api/domain/OrganizationUnit.java | 1 + .../pearljam/api/service/CampaignService.java | 16 +- .../api/service/impl/CampaignServiceImpl.java | 118 +++--- .../service/impl/InterviewerServiceImpl.java | 2 +- .../service/impl/SurveyUnitServiceImpl.java | 21 +- ...astOneDateCampaignVisibilityValidator.java | 13 + .../web/annotation/AtLeastOneDateValid.java | 17 + .../AtLeastOneDateVisibilityValidator.java | 13 + .../exception/ExceptionControllerAdvice.java | 15 +- .../exception/VisibilityInvalidException.java | 8 - .../campaign/model/CampaignVisibility.java | 1 + .../domain/campaign/model/Visibility.java | 20 +- .../port/serverside/CampaignRepository.java | 4 + .../port/serverside/VisibilityRepository.java | 39 +- .../port/userside/VisibilityService.java | 38 ++ .../service/VisibilityServiceImpl.java | 43 ++ .../exception/CampaignOnGoingException.java | 10 + .../VisibilityHasInvalidDatesException.java | 10 + .../adapter/VisibilityDaoAdapter.java | 32 +- .../entity/CommunicationTemplateDB.java | 13 +- .../campaign/entity}/VisibilityDB.java | 17 +- .../campaign/entity}/VisibilityDBId.java | 2 +- .../campaign/jpa/VisibilityJpaRepository.java | 75 ++-- .../541_add_communication_template.xml | 16 +- .../resources/db/dataset/init-demo-data.sql | 121 ++++-- .../resources/db/dataset/reinit-test-data.sql | 77 +--- .../api/authKeycloak/TestAuthKeyCloak.java | 367 +----------------- .../CampaignControllerCreateTest.java | 239 +++++------- .../controller/CampaignControllerTest.java | 117 ++++++ .../CampaignControllerUpdateTest.java | 346 +++++------------ .../controller/VisibilityControllerTest.java | 152 ++++++++ .../dummy/CampaignFakeService.java | 61 ++- .../dummy/ReferentFakeService.java | 2 +- .../dummy/VisibilityFakeService.java | 56 +++ .../CommunicationTemplateCreateDtoTest.java | 41 ++ .../VisibilityCampaignCreateDtoTest.java | 45 +++ .../VisibilityCampaignUpdateDtoTest.java | 48 +++ .../dto/input/VisibilityUpdateDtoTest.java | 41 ++ .../CommunicationTemplateResponseDtoTest.java | 41 ++ .../dto/output/VisibilityCampaignDtoTest.java | 43 ++ .../controller/MessageControllerTest.java | 2 +- .../insee/pearljam/api/noAuth/TestNoAuth.java | 6 +- .../controller/CommentControllerTest.java | 3 +- .../controller/SurveyUnitControllerTest.java | 3 +- .../pearljam/api/utils/JsonTestHelper.java | 16 + .../pearljam/api/utils/MockMvcTestUtils.java | 19 +- .../config/ArchunitApplicationTests.java | 3 +- .../domain/campaign/model/VisibilityTest.java | 51 +++ .../campaign/model/VisibilitytTest.java | 4 - .../CommunicationTemplateTest.java | 3 +- .../campaign/service/CampaignServiceTest.java | 5 + .../service/VisibilityServiceTest.java | 5 + .../dummy/VisibilityFakeRepository.java | 36 ++ .../adapter/VisibilityDaoAdapter.java | 4 - .../adapter/VisibilityDaoAdapterTest.java | 211 ++++++++++ .../entity/CommunicationTemplateDBTest.java | 64 +++ .../campaign/entity/VisibilityDBTest.java | 190 ++++++++- .../integration/campaign/CampaignIT.java | 319 +++++++++++++++ .../integration/campaign/VisibilityIT.java | 113 ++++++ .../integration/surveyunit/SurveyUnitIT.java | 11 + src/test/resources/application-auth.yml | 5 +- 73 files changed, 2407 insertions(+), 1235 deletions(-) create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/controller/VisibilityController.java rename src/main/java/fr/insee/pearljam/api/campaign/dto/input/{visibility => }/VisibilityCampaignCreateDto.java (63%) rename src/main/java/fr/insee/pearljam/api/campaign/dto/input/{visibility => }/VisibilityCampaignUpdateDto.java (71%) rename src/main/java/fr/insee/pearljam/api/campaign/dto/input/{visibility => }/VisibilityUpdateDto.java (75%) rename src/main/java/fr/insee/pearljam/api/campaign/dto/{ => output}/CommunicationTemplateResponseDto.java (95%) rename src/main/java/fr/insee/pearljam/api/campaign/dto/output/{visibility => }/VisibilityCampaignDto.java (94%) create mode 100644 src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateCampaignVisibilityValidator.java create mode 100644 src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateValid.java create mode 100644 src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateVisibilityValidator.java delete mode 100644 src/main/java/fr/insee/pearljam/api/web/exception/VisibilityInvalidException.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CampaignRepository.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/port/userside/VisibilityService.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java create mode 100644 src/main/java/fr/insee/pearljam/domain/exception/CampaignOnGoingException.java create mode 100644 src/main/java/fr/insee/pearljam/domain/exception/VisibilityHasInvalidDatesException.java rename src/main/java/fr/insee/pearljam/{api/domain => infrastructure/campaign/entity}/VisibilityDB.java (87%) rename src/main/java/fr/insee/pearljam/{api/domain => infrastructure/campaign/entity}/VisibilityDBId.java (92%) create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java rename src/test/java/fr/insee/pearljam/api/{service => campaign/controller}/dummy/CampaignFakeService.java (68%) rename src/test/java/fr/insee/pearljam/api/{service => campaign/controller}/dummy/ReferentFakeService.java (87%) create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java create mode 100644 src/test/java/fr/insee/pearljam/api/utils/JsonTestHelper.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java delete mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilitytTest.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceTest.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceTest.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java delete mode 100644 src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java create mode 100644 src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java create mode 100644 src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java create mode 100644 src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java create mode 100644 src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java create mode 100644 src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java diff --git a/pom.xml b/pom.xml index 409439db..3d43d39f 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 3.3.1 + 3.3.2 @@ -104,13 +104,6 @@ test - - org.javatuples - javatuples - 1.2 - test - - com.tngtech.archunit archunit diff --git a/src/main/java/fr/insee/pearljam/api/campaign/controller/VisibilityController.java b/src/main/java/fr/insee/pearljam/api/campaign/controller/VisibilityController.java new file mode 100644 index 00000000..847a0b94 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/controller/VisibilityController.java @@ -0,0 +1,75 @@ +package fr.insee.pearljam.api.campaign.controller; + +import java.util.List; + +import fr.insee.pearljam.api.campaign.dto.output.VisibilityCampaignDto; +import fr.insee.pearljam.api.campaign.dto.input.VisibilityUpdateDto; +import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import fr.insee.pearljam.api.constants.Constants; + +@RestController +@Tag(name = "01. Campaigns", description = "Endpoints for campaigns") +@Slf4j +@RequiredArgsConstructor +@Validated +public class VisibilityController { + private final VisibilityService visibilityService; + private final AuthenticatedUserService authenticatedUserService; + + /** + * This method returns the list of visibilities associated with the + * campaign {id} + * + * @param campaignId campaign id + * @return List of {@link VisibilityCampaignDto} + */ + @Operation(summary = "Get campaign visibilities") + @GetMapping(path = Constants.API_CAMPAIGN_ID_VISIBILITIES) + public List getVisibilities(@NotBlank @PathVariable(value = "id") String campaignId) throws CampaignNotFoundException { + String userId = authenticatedUserService.getCurrentUserId(); + log.info("{} try to get campaign[{}] visibilities ", userId, campaignId); + + List visibilities = visibilityService.findVisibilities(campaignId); + return VisibilityCampaignDto.fromModel(visibilities); + } + + /** + * Update the visibility dates for a given campaign and organizational unit + * + * @param visibilityToUpdate the visibility to update + * @param idCampaign campaign identifier + * @param idOu organizational unit id + * @throws VisibilityNotFoundException if the visibility does not exist + */ + @Operation(summary = "Update the visibility of a campaign for an organizational unit") + @PutMapping(path = Constants.API_CAMPAIGN_ID_OU_ID_VISIBILITY) + public void updateVisibility( + @Valid @NotNull @RequestBody VisibilityUpdateDto visibilityToUpdate, + @NotBlank @PathVariable(value = "idCampaign") String idCampaign, + @NotBlank @PathVariable(value = "idOu") String idOu) throws VisibilityNotFoundException, VisibilityHasInvalidDatesException { + String userId = authenticatedUserService.getCurrentUserId(); + log.info("{} try to change OU[{}] visibility on campaign[{}] ", userId, idOu, idCampaign); + visibilityService.updateVisibility(VisibilityUpdateDto.toModel(visibilityToUpdate, idCampaign, idOu)); + log.info("Visibility with CampaignId {} for Organizational Unit {} updated", idCampaign, + idOu); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java index 31e03a42..4049e257 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonInclude; -import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignCreateDto; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; import fr.insee.pearljam.api.domain.IdentificationConfiguration; diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java index e53027cf..6adfbed5 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java @@ -1,7 +1,6 @@ package fr.insee.pearljam.api.campaign.dto.input; import com.fasterxml.jackson.annotation.JsonInclude; -import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignUpdateDto; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; import fr.insee.pearljam.api.domain.IdentificationConfiguration; diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java similarity index 63% rename from src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignCreateDto.java rename to src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java index b8b77452..458f7a60 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java @@ -1,10 +1,8 @@ -package fr.insee.pearljam.api.campaign.dto.input.visibility; +package fr.insee.pearljam.api.campaign.dto.input; import com.fasterxml.jackson.annotation.JsonInclude; -import fr.insee.pearljam.api.campaign.dto.input.CommunicationTemplateCreateDto; import fr.insee.pearljam.domain.campaign.model.Visibility; -import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; @@ -36,21 +34,19 @@ public record VisibilityCampaignCreateDto( @NotNull Long endDate, @NotBlank - String organizationalUnit, - @Valid - List communicationTemplates + String organizationalUnit ) { - public static Visibility toModel(VisibilityCampaignCreateDto visibilityDto) { - return new Visibility(null, - visibilityDto.organizationalUnit(), - visibilityDto.managementStartDate(), - visibilityDto.interviewerStartDate(), - visibilityDto.identificationPhaseStartDate(), - visibilityDto.collectionStartDate(), - visibilityDto.collectionEndDate(), - visibilityDto.endDate(), - null - ); + public static List toModel(List visibilities, String campaignId) { + return visibilities.stream() + .map(visibility -> new Visibility(campaignId, + visibility.organizationalUnit(), + visibility.managementStartDate(), + visibility.interviewerStartDate(), + visibility.identificationPhaseStartDate(), + visibility.collectionStartDate(), + visibility.collectionEndDate(), + visibility.endDate())) + .toList(); } } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java similarity index 71% rename from src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignUpdateDto.java rename to src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java index 22e262d9..db6ca486 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityCampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java @@ -1,7 +1,7 @@ -package fr.insee.pearljam.api.campaign.dto.input.visibility; +package fr.insee.pearljam.api.campaign.dto.input; import com.fasterxml.jackson.annotation.JsonInclude; -import fr.insee.pearljam.api.web.exception.VisibilityInvalidException; +import fr.insee.pearljam.api.web.annotation.AtLeastOneDateValid; import fr.insee.pearljam.domain.campaign.model.Visibility; import jakarta.validation.constraints.NotBlank; @@ -18,6 +18,7 @@ * @param endDate End date of the visibility */ @JsonInclude(JsonInclude.Include.NON_NULL) +@AtLeastOneDateValid public record VisibilityCampaignUpdateDto( Long managementStartDate, Long interviewerStartDate, @@ -28,15 +29,6 @@ public record VisibilityCampaignUpdateDto( @NotBlank String organizationalUnit ) { - public static final String AT_LEAST_ONE_DATE_REQUIRED_MESSAGE = "At least one date must be provided for a visibility"; - - public VisibilityCampaignUpdateDto { - if (managementStartDate == null && interviewerStartDate == null && identificationPhaseStartDate == null && - collectionStartDate == null && collectionEndDate == null && endDate == null) { - throw new VisibilityInvalidException(AT_LEAST_ONE_DATE_REQUIRED_MESSAGE); - } - } - public static List toModel(List visibilitiesDto, String campaignId) { return visibilitiesDto.stream() .map(visibilityDto -> new Visibility(campaignId, @@ -46,8 +38,7 @@ public static List toModel(List visibil visibilityDto.identificationPhaseStartDate(), visibilityDto.collectionStartDate(), visibilityDto.collectionEndDate(), - visibilityDto.endDate(), - null + visibilityDto.endDate() )) .toList(); } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java similarity index 75% rename from src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityUpdateDto.java rename to src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java index 936b3baf..2e7062d4 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/visibility/VisibilityUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java @@ -1,7 +1,9 @@ -package fr.insee.pearljam.api.campaign.dto.input.visibility; +package fr.insee.pearljam.api.campaign.dto.input; import com.fasterxml.jackson.annotation.JsonInclude; +import fr.insee.pearljam.api.web.annotation.AtLeastOneDateValid; import fr.insee.pearljam.domain.campaign.model.Visibility; +import lombok.NonNull; /** * A Data Transfer Object for representing visibility information. @@ -14,6 +16,7 @@ * @param endDate End date of the visibility */ @JsonInclude(JsonInclude.Include.NON_NULL) +@AtLeastOneDateValid public record VisibilityUpdateDto( Long managementStartDate, Long interviewerStartDate, @@ -23,14 +26,15 @@ public record VisibilityUpdateDto( Long endDate ) { - public static Visibility toModel(VisibilityUpdateDto visibilityDto, String campaignId, String ouId) { + public static Visibility toModel(@NonNull VisibilityUpdateDto visibilityDto, + @NonNull String campaignId, + @NonNull String ouId) { return new Visibility(campaignId, ouId, visibilityDto.managementStartDate(), visibilityDto.interviewerStartDate(), visibilityDto.identificationPhaseStartDate(), visibilityDto.collectionStartDate(), visibilityDto.collectionEndDate(), - visibilityDto.endDate(), - null); + visibilityDto.endDate()); } } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java index e0c87f76..4c0a6022 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java @@ -1,7 +1,6 @@ package fr.insee.pearljam.api.campaign.dto.output; import com.fasterxml.jackson.annotation.JsonInclude; -import fr.insee.pearljam.api.campaign.dto.output.visibility.VisibilityCampaignDto; import fr.insee.pearljam.api.domain.Campaign; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/CommunicationTemplateResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java similarity index 95% rename from src/main/java/fr/insee/pearljam/api/campaign/dto/CommunicationTemplateResponseDto.java rename to src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java index 5b7dbb76..860c3fa9 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/CommunicationTemplateResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java @@ -1,4 +1,4 @@ -package fr.insee.pearljam.api.campaign.dto; +package fr.insee.pearljam.api.campaign.dto.output; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/visibility/VisibilityCampaignDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java similarity index 94% rename from src/main/java/fr/insee/pearljam/api/campaign/dto/output/visibility/VisibilityCampaignDto.java rename to src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java index 5baa969d..324fe9d9 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/visibility/VisibilityCampaignDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java @@ -1,4 +1,4 @@ -package fr.insee.pearljam.api.campaign.dto.output.visibility; +package fr.insee.pearljam.api.campaign.dto.output; import fr.insee.pearljam.domain.campaign.model.Visibility; diff --git a/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java b/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java index da1c5840..24837315 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java @@ -1,16 +1,10 @@ package fr.insee.pearljam.api.controller; import java.util.List; -import java.util.Optional; import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; -import fr.insee.pearljam.api.campaign.dto.output.visibility.VisibilityCampaignDto; -import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityUpdateDto; -import fr.insee.pearljam.domain.campaign.model.Visibility; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; -import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import fr.insee.pearljam.domain.exception.*; import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; @@ -27,7 +21,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import fr.insee.pearljam.api.domain.Campaign; import fr.insee.pearljam.api.domain.Interviewer; import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; import fr.insee.pearljam.api.dto.campaign.CampaignDto; @@ -36,7 +29,6 @@ import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; import fr.insee.pearljam.api.dto.referent.ReferentDto; import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; import fr.insee.pearljam.api.service.CampaignService; import fr.insee.pearljam.api.service.ReferentService; import io.swagger.v3.oas.annotations.Operation; @@ -65,8 +57,7 @@ public class CampaignController { @Operation(summary = "Create a Campaign") @PostMapping(path = Constants.API_CAMPAIGN) public void createCampaign(@Valid @NotNull @RequestBody CampaignCreateDto campaignDto) - throws CampaignAlreadyExistException, - CampaignNotFoundException, OrganizationalUnitNotFoundException { + throws CampaignAlreadyExistException, OrganizationalUnitNotFoundException, VisibilityHasInvalidDatesException { campaignService.createCampaign(campaignDto); } @@ -151,23 +142,6 @@ public ResponseEntity> getListInterviewers(@PathVariable(va } - /** - * This method returns the list of visibilities associated with the - * campaign {id} - * - * @param campaignId campaign id - * @return List of {@link VisibilityCampaignDto} - */ - @Operation(summary = "Get campaign visibilities") - @GetMapping(path = Constants.API_CAMPAIGN_ID_VISIBILITIES) - public List getVisibilities(@PathVariable(value = "id") String campaignId) throws CampaignNotFoundException { - String userId = authenticatedUserService.getCurrentUserId(); - log.info("{} try to get campaign[{}] visibilities ", userId, campaignId); - - List visibilities = campaignService.findAllVisibilitiesByCampaign(campaignId); - return VisibilityCampaignDto.fromModel(visibilities); - } - /** * This method is used to count survey units that are abandoned by campaign * Return the sum of survey units states by campaign as a list @@ -215,27 +189,6 @@ public ResponseEntity getNbSUNotAttributed(@PathVariable(value = "id") } - /** - * Update the visibility dates for a given campaign and organizational unit - * - * @param visibilityToUpdate the visibility to update - * @param idCampaign campaign identifier - * @param idOu organizational unit id - * @throws VisibilityNotFoundException if the visibility does not exist - */ - @Operation(summary = "Change visibility of a campaign for an Organizational Unit") - @PutMapping(path = Constants.API_CAMPAIGN_ID_OU_ID_VISIBILITY) - public void updateVisibility( - @Valid @NotNull @RequestBody VisibilityUpdateDto visibilityToUpdate, - @NotBlank @PathVariable(value = "idCampaign") String idCampaign, - @NotBlank @PathVariable(value = "idOu") String idOu) throws VisibilityNotFoundException { - String userId = authenticatedUserService.getCurrentUserId(); - log.info("{} try to change OU[{}] visibility on campaign[{}] ", userId, idOu, idCampaign); - campaignService.updateVisibility(VisibilityUpdateDto.toModel(visibilityToUpdate, idCampaign, idOu)); - log.info("Visibility with CampaignId {} for Organizational Unit {} updated", idCampaign, - idOu); - } - /** * This method deletes a campaign * @@ -245,26 +198,17 @@ public void updateVisibility( */ @Operation(summary = "Delete a campaign") @DeleteMapping(path = Constants.API_CAMPAIGN_ID) - public ResponseEntity deleteCampaignById( - @PathVariable(value = "id") String campaignId, - @RequestParam(required = false, defaultValue = DEFAULT_FORCE_VALUE) Boolean force) throws CampaignNotFoundException { + public void deleteCampaignById( + @NotBlank @PathVariable(value = "id") + String campaignId, + @RequestParam(required = false, defaultValue = DEFAULT_FORCE_VALUE) + boolean force) + throws CampaignNotFoundException, CampaignOnGoingException { String userId = authenticatedUserService.getCurrentUserId(); log.info("{} try to delete campaign {}", userId, campaignId); - Optional campaignOptional = campaignService.findById(campaignId); - if (!campaignOptional.isPresent()) { - log.error("DELETE campaign with id {} resulting in 404 because it does not exists", campaignId); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - if (Boolean.FALSE.equals(force) && campaignService.isCampaignOngoing(campaignId)) { - String errorMessage = String.format("Campaign %s is on-going and can't be deleted", campaignId); - log.info(errorMessage); - return ResponseEntity.status(HttpStatus.CONFLICT).body(errorMessage); - } - - campaignService.delete(campaignOptional.get()); + campaignService.delete(campaignId, force); log.info("DELETE campaign with id {} resulting in 200", campaignId); - return ResponseEntity.ok().build(); } /** @@ -275,13 +219,12 @@ public ResponseEntity deleteCampaignById( @Operation(summary = "Update campaign (label, email, configurations, visibilities") @PutMapping(path = Constants.API_CAMPAIGN_ID) public void updateCampaign(@NotBlank @PathVariable(value = "id") String id, - @Valid @NotNull @RequestBody CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException { + @Valid @NotNull @RequestBody CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { String userId = authenticatedUserService.getCurrentUserId(); log.info("{} try to update campaign {} collection dates", userId, id); campaignService.updateCampaign(id, campaign); log.info("Campaign with id {} updated", id); - } /** diff --git a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java index d1695dc1..b4eecbd4 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Optional; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; diff --git a/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java b/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java index f4e9a363..4eebbeb8 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java +++ b/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java @@ -3,6 +3,7 @@ import java.io.Serializable; import java.util.List; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; diff --git a/src/main/java/fr/insee/pearljam/api/service/CampaignService.java b/src/main/java/fr/insee/pearljam/api/service/CampaignService.java index a3fdf403..d450654c 100644 --- a/src/main/java/fr/insee/pearljam/api/service/CampaignService.java +++ b/src/main/java/fr/insee/pearljam/api/service/CampaignService.java @@ -5,10 +5,7 @@ import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; -import fr.insee.pearljam.domain.campaign.model.Visibility; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; -import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import fr.insee.pearljam.domain.exception.*; import fr.insee.pearljam.api.domain.Campaign; import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; @@ -16,7 +13,6 @@ import fr.insee.pearljam.api.dto.count.CountDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; /** * Service for the Campaign entity @@ -56,19 +52,15 @@ public interface CampaignService { CountDto getNbSUNotAttributedByCampaign(String userId, String campaignId) throws NotFoundException; - void createCampaign(CampaignCreateDto campaignDto) throws CampaignAlreadyExistException, CampaignNotFoundException, OrganizationalUnitNotFoundException; + void createCampaign(CampaignCreateDto campaignDto) throws CampaignAlreadyExistException, OrganizationalUnitNotFoundException, VisibilityHasInvalidDatesException; Optional findById(String campaignId); - void delete(Campaign campaign); + void delete(String campaignId, boolean force) throws CampaignNotFoundException, CampaignOnGoingException; - void updateCampaign(String id, CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException; + void updateCampaign(String id, CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException; boolean isCampaignOngoing(String id) throws CampaignNotFoundException; - List findAllVisibilitiesByCampaign(String campaignId) throws CampaignNotFoundException; - CampaignResponseDto getCampaignDtoById(String id) throws CampaignNotFoundException; - - void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNotFoundException; } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index 916b63e1..65a4a94c 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -2,7 +2,6 @@ import java.time.Instant; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -10,19 +9,18 @@ import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; -import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignUpdateDto; -import fr.insee.pearljam.api.campaign.dto.output.visibility.VisibilityCampaignDto; +import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.output.VisibilityCampaignDto; +import fr.insee.pearljam.api.domain.OrganizationUnit; +import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; +import fr.insee.pearljam.domain.exception.*; import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; import fr.insee.pearljam.domain.campaign.model.Visibility; -import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; -import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.domain.Campaign; import fr.insee.pearljam.api.domain.Referent; import fr.insee.pearljam.api.domain.SurveyUnit; @@ -32,13 +30,11 @@ import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; import fr.insee.pearljam.api.dto.referent.ReferentDto; -import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignCreateDto; +import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignCreateDto; import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; import fr.insee.pearljam.api.repository.CampaignRepository; import fr.insee.pearljam.api.repository.MessageRepository; import fr.insee.pearljam.api.repository.OrganizationUnitRepository; -import fr.insee.pearljam.api.repository.ReferentRepository; import fr.insee.pearljam.api.repository.SurveyUnitRepository; import fr.insee.pearljam.api.repository.UserRepository; import fr.insee.pearljam.api.service.CampaignService; @@ -67,15 +63,14 @@ public class CampaignServiceImpl implements CampaignService { private final CampaignRepository campaignRepository; private final UserRepository userRepository; private final SurveyUnitRepository surveyUnitRepository; - private final VisibilityRepository visibilityRepository; private final OrganizationUnitRepository organizationUnitRepository; private final MessageRepository messageRepository; - private final ReferentRepository referentRepository; private final UserService userService; private final UtilsService utilsService; private final SurveyUnitService surveyUnitService; private final PreferenceService preferenceService; private final ReferentService referentService; + private final VisibilityService visibilityService; @Override public List getListCampaign(String userId) { @@ -88,19 +83,20 @@ public List getListCampaign(String userId) { .distinct() .toList(); - List lstOuId = (userId.equals(Constants.GUEST)) ? Collections.singletonList(Constants.GUEST) - : organizationUnits.stream().map(OrganizationUnitDto::getId).toList(); + List lstOuId = organizationUnits.stream() + .map(OrganizationUnitDto::getId).toList(); List campaignDtoReturned = new ArrayList<>(); for (String idCampaign : campaignDtoIds) { CampaignDto campaign = campaignRepository.findDtoById(idCampaign); - CampaignVisibility visibility = visibilityRepository.findCampaignVisibility(idCampaign, lstOuId); - campaign.setManagementStartDate(visibility.managementStartDate()); - campaign.setInterviewerStartDate(visibility.interviewerStartDate()); - campaign.setIdentificationPhaseStartDate(visibility.identificationPhaseStartDate()); - campaign.setCollectionStartDate(visibility.collectionStartDate()); - campaign.setCollectionEndDate(visibility.collectionEndDate()); - campaign.setEndDate(visibility.endDate()); + + CampaignVisibility campaignVisibility = visibilityService.getCampaignVisibility(idCampaign, lstOuId); + campaign.setManagementStartDate(campaignVisibility.managementStartDate()); + campaign.setInterviewerStartDate(campaignVisibility.interviewerStartDate()); + campaign.setIdentificationPhaseStartDate(campaignVisibility.identificationPhaseStartDate()); + campaign.setCollectionStartDate(campaignVisibility.collectionStartDate()); + campaign.setCollectionEndDate(campaignVisibility.collectionEndDate()); + campaign.setEndDate(campaignVisibility.endDate()); campaign.setCampaignStats(surveyUnitRepository.getCampaignStats(idCampaign, lstOuId)); campaign.setPreference(isUserPreference(userId, idCampaign)); campaign.setReferents(referentService.findByCampaignId(idCampaign)); @@ -132,15 +128,6 @@ public List getListInterviewers(String userId, String campaignId return interviewersDtoReturned; } - @Override - public void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNotFoundException { - Visibility currentVisibility = visibilityRepository - .findVisibility(visibilityToUpdate.campaignId(), visibilityToUpdate.organizationalUnitId()) - .orElseThrow(VisibilityNotFoundException::new); - Visibility mergedVisibility = Visibility.merge(currentVisibility, visibilityToUpdate); - visibilityRepository.update(mergedVisibility); - } - @Override public boolean isUserPreference(String userId, String campaignId) { return (campaignRepository.checkCampaignPreferences(userId, campaignId).isEmpty()) || "GUEST".equals(userId); @@ -166,7 +153,7 @@ public CountDto getNbSUNotAttributedByCampaign(String userId, String campaignId) @Override public void createCampaign(CampaignCreateDto campaignDto) - throws CampaignAlreadyExistException, CampaignNotFoundException, OrganizationalUnitNotFoundException { + throws CampaignAlreadyExistException, OrganizationalUnitNotFoundException, VisibilityHasInvalidDatesException { String campaignId = campaignDto.campaign().toUpperCase(); Optional campOpt = campaignRepository.findById(campaignId); @@ -181,13 +168,21 @@ public void createCampaign(CampaignCreateDto campaignDto) campaignDto.contactAttemptConfiguration(), campaignDto.email(), campaignDto.communicationRequestConfiguration()); - campaignRepository.save(campaign); + campaign.setReferents(new ArrayList<>()); - for (VisibilityCampaignCreateDto visibilityDto : campaignDto.visibilities()) { - Visibility visibilityToCreate = VisibilityCampaignCreateDto.toModel(visibilityDto); - visibilityRepository.create(visibilityToCreate); + List visibilitiesDBToCreate = new ArrayList<>(); + List visibilities = VisibilityCampaignCreateDto.toModel(campaignDto.visibilities(), campaignDto.campaign()); + for (Visibility visibility : visibilities) { + if(!Visibility.isValid(visibility)) { + throw new VisibilityHasInvalidDatesException(); + } + OrganizationUnit organizationUnit = organizationUnitRepository.findById(visibility.organizationalUnitId()) + .orElseThrow(OrganizationalUnitNotFoundException::new); + visibilitiesDBToCreate.add(VisibilityDB.fromModel(visibility, campaign, organizationUnit)); } - persistReferents(campaignDto.referents(), campaign); + campaign.setVisibilities(visibilitiesDBToCreate); + updateReferents(campaign, campaignDto.referents()); + campaignRepository.save(campaign); } @Override @@ -196,12 +191,20 @@ public Optional findById(String campaignId) { } @Override - public void delete(Campaign campaign) { + public void delete(String campaignId, boolean force) throws CampaignNotFoundException, CampaignOnGoingException { + Campaign campaign = findById(campaignId) + .orElseThrow(CampaignNotFoundException::new); + + if (!force && isCampaignOngoing(campaignId)) { + String errorMessage = String.format("Campaign %s is on-going and can't be deleted", campaignId); + log.info(errorMessage); + throw new CampaignOnGoingException(); + } surveyUnitRepository.findByCampaignId(campaign.getId()).stream().forEach(surveyUnitService::delete); userRepository.findAll() .forEach(user -> { - List lstCampaignId = user.getCampaigns().stream().map(Campaign::getId) - .toList(); + List lstCampaignId = new ArrayList<>(user.getCampaigns().stream().map(Campaign::getId) + .toList()); if (lstCampaignId.contains(campaign.getId())) { lstCampaignId.remove(lstCampaignId.indexOf(campaign.getId())); preferenceService.setPreferences(lstCampaignId, user.getId()); @@ -212,13 +215,13 @@ public void delete(Campaign campaign) { } @Override - public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate) throws CampaignNotFoundException, VisibilityNotFoundException { + public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { Campaign currentCampaign = campaignRepository.findByIdIgnoreCase(campaignId) .orElseThrow(CampaignNotFoundException::new); List visibilitiesToUpdate = VisibilityCampaignUpdateDto.toModel(campaignToUpdate.visibilities(), campaignId); for(Visibility visibilityToUpdate : visibilitiesToUpdate) { - updateVisibility(visibilityToUpdate); + visibilityService.updateVisibility(visibilityToUpdate); } currentCampaign.setLabel(campaignToUpdate.campaignLabel()); @@ -227,14 +230,9 @@ public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate } updateConfiguration(currentCampaign, campaignToUpdate); - updateReferents(currentCampaign, campaignToUpdate); - } + updateReferents(currentCampaign, campaignToUpdate.referents()); - private void updateReferents(Campaign currentCampaign, CampaignUpdateDto campDto) { - if (campDto.referents() != null) { - referentRepository.deleteAll(currentCampaign.getReferents()); - persistReferents(campDto.referents(), currentCampaign); - } + campaignRepository.save(currentCampaign); } private void updateConfiguration(Campaign currentCampaign, CampaignUpdateDto campDto) { @@ -276,30 +274,24 @@ public List getInterviewerCampaigns(String userId) { @Override public boolean isCampaignOngoing(String campaignId) throws CampaignNotFoundException { - findById(campaignId) + Campaign campaign = findById(campaignId) .orElseThrow(CampaignNotFoundException::new); - List visibilities = visibilityRepository.findVisibilities(campaignId); + List visibilities = visibilityService.findVisibilities(campaign.getId()); return visibilities.stream() .anyMatch(visibility -> visibility.endDate() > Instant.now().toEpochMilli()); } - @Override - public List findAllVisibilitiesByCampaign(String campaignId) throws CampaignNotFoundException { - findById(campaignId) - .orElseThrow(CampaignNotFoundException::new); - return visibilityRepository.findVisibilities(campaignId); - } - - private void persistReferents(List referents, Campaign campaign) { - - referents.forEach(refDto -> { + private void updateReferents(Campaign campaign, List referentDtos) { + List referents = campaign.getReferents(); + referents.clear(); + referentDtos.forEach(refDto -> { Referent ref = new Referent(); ref.setCampaign(campaign); ref.setFirstName(refDto.getFirstName()); ref.setLastName(refDto.getLastName()); ref.setPhoneNumber(refDto.getPhoneNumber()); ref.setRole(refDto.getRole()); - referentRepository.save(ref); + referents.add(ref); }); } @@ -309,7 +301,7 @@ public CampaignResponseDto getCampaignDtoById(String campaignId) throws Campaign .orElseThrow(CampaignNotFoundException::new); List referents = referentService.findByCampaignId(campaignId); List visibilities = VisibilityCampaignDto.fromModel( - visibilityRepository.findVisibilities(campaignId) + visibilityService.findVisibilities(campaignId) ); return CampaignResponseDto.fromModel(campaignDB, referents, visibilities); } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java index eef143db..58e47aeb 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java @@ -16,7 +16,7 @@ import fr.insee.pearljam.api.domain.Interviewer; import fr.insee.pearljam.api.domain.Response; import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.api.domain.VisibilityDB; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import fr.insee.pearljam.api.dto.campaign.CampaignDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerContextDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java index 6875c72b..c5f4bcf5 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java @@ -14,7 +14,6 @@ import fr.insee.pearljam.api.dto.surveyunit.*; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitVisibilityDto; -import fr.insee.pearljam.domain.campaign.model.Visibility; import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; import fr.insee.pearljam.domain.exception.PersonNotFoundException; import fr.insee.pearljam.domain.exception.SurveyUnitNotFoundException; @@ -113,27 +112,13 @@ public SurveyUnitDetailDto getSurveyUnitDetail(String userId, String id) } public List getSurveyUnitDto(String userId, Boolean extended) { - List surveyUnitDtoIds = null; - if (userId.equals(GUEST)) { - surveyUnitDtoIds = surveyUnitRepository.findAllIds(); - } else { - surveyUnitDtoIds = surveyUnitRepository.findIdsByInterviewerId(userId); - } + List surveyUnitDtoIds = surveyUnitRepository.findIdsByInterviewerId(userId); + if (surveyUnitDtoIds.isEmpty()) { log.error("No Survey Unit found for interviewer {}", userId); return List.of(); } - if (userId.equals(GUEST)) { - return surveyUnitDtoIds.stream() - .map(idSurveyUnit -> { - Visibility visibility = visibilityRepository.getVisibilityBySurveyUnitId(idSurveyUnit); - return new SurveyUnitDto( - surveyUnitRepository.findById(idSurveyUnit).get(), - SurveyUnitVisibilityDto.fromModel(visibility), - extended); - }) - .toList(); - } + surveyUnitDtoIds = surveyUnitDtoIds.stream().filter(this::canBeSeenByInterviewer) .toList(); diff --git a/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateCampaignVisibilityValidator.java b/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateCampaignVisibilityValidator.java new file mode 100644 index 00000000..70572a8f --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateCampaignVisibilityValidator.java @@ -0,0 +1,13 @@ +package fr.insee.pearljam.api.web.annotation; + +import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignUpdateDto; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +public class AtLeastOneDateCampaignVisibilityValidator implements ConstraintValidator { + @Override + public boolean isValid(VisibilityCampaignUpdateDto dto, ConstraintValidatorContext context) { + return dto.managementStartDate() != null || dto.interviewerStartDate() != null || dto.identificationPhaseStartDate() != null || + dto.collectionStartDate() != null || dto.collectionEndDate() != null || dto.endDate() != null; + } +} diff --git a/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateValid.java b/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateValid.java new file mode 100644 index 00000000..89bb220c --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateValid.java @@ -0,0 +1,17 @@ +package fr.insee.pearljam.api.web.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Constraint(validatedBy = {AtLeastOneDateCampaignVisibilityValidator.class, AtLeastOneDateVisibilityValidator.class}) +@Target({ ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +public @interface AtLeastOneDateValid { + String message() default "At least one date must be provided for a visibility"; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateVisibilityValidator.java b/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateVisibilityValidator.java new file mode 100644 index 00000000..64f3e74e --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateVisibilityValidator.java @@ -0,0 +1,13 @@ +package fr.insee.pearljam.api.web.annotation; + +import fr.insee.pearljam.api.campaign.dto.input.VisibilityUpdateDto; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +public class AtLeastOneDateVisibilityValidator implements ConstraintValidator { + @Override + public boolean isValid(VisibilityUpdateDto dto, ConstraintValidatorContext context) { + return dto.managementStartDate() != null || dto.interviewerStartDate() != null || dto.identificationPhaseStartDate() != null || + dto.collectionStartDate() != null || dto.collectionEndDate() != null || dto.endDate() != null; + } +} diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java index a0f49c76..6cd11690 100644 --- a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java +++ b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java @@ -3,8 +3,10 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import fr.insee.pearljam.api.exception.NoOrganizationUnitException; +import fr.insee.pearljam.domain.exception.CampaignOnGoingException; import fr.insee.pearljam.domain.exception.EntityAlreadyExistException; import fr.insee.pearljam.domain.exception.EntityNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; import fr.insee.pearljam.infrastructure.mail.exception.SendMailException; import jakarta.validation.ConstraintViolationException; import lombok.extern.slf4j.Slf4j; @@ -34,7 +36,7 @@ public ExceptionControllerAdvice(ErrorAttributes errorAttributes) { this.errorComponent = new ApiExceptionComponent(errorAttributes); } - private static final String ERROR_OCCURRED_LABEL = "An error has occurred"; + public static final String ERROR_OCCURRED_LABEL = "An error has occurred"; public static final String INVALID_PARAMETERS_MESSAGE = "Invalid parameters"; /** @@ -126,9 +128,14 @@ public ResponseEntity exceptions(NoOrganizationUnitException e, WebReq return generateResponseError(e, HttpStatus.BAD_REQUEST, request); } - @ExceptionHandler(VisibilityInvalidException.class) - public ResponseEntity exceptions(VisibilityInvalidException e, WebRequest request) { - return generateResponseError(e, HttpStatus.BAD_REQUEST, request); + @ExceptionHandler(VisibilityHasInvalidDatesException.class) + public ResponseEntity exceptions(VisibilityHasInvalidDatesException e, WebRequest request) { + return generateResponseError(e, HttpStatus.CONFLICT, request); + } + + @ExceptionHandler(CampaignOnGoingException.class) + public ResponseEntity exceptions(CampaignOnGoingException e, WebRequest request) { + return generateResponseError(e, HttpStatus.CONFLICT, request); } @ExceptionHandler(HttpClientErrorException.class) diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/VisibilityInvalidException.java b/src/main/java/fr/insee/pearljam/api/web/exception/VisibilityInvalidException.java deleted file mode 100644 index e90075c5..00000000 --- a/src/main/java/fr/insee/pearljam/api/web/exception/VisibilityInvalidException.java +++ /dev/null @@ -1,8 +0,0 @@ -package fr.insee.pearljam.api.web.exception; - -public class VisibilityInvalidException extends RuntimeException { - - public VisibilityInvalidException(String message) { - super(message); - } -} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/CampaignVisibility.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/CampaignVisibility.java index 2be4797e..86e0ba86 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/model/CampaignVisibility.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/CampaignVisibility.java @@ -10,6 +10,7 @@ * @param collectionEndDate The end date of collection * @param endDate The end date of visibility */ + public record CampaignVisibility( Long managementStartDate, Long interviewerStartDate, diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java index aeab87aa..c2f3fbfc 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java @@ -1,9 +1,6 @@ package fr.insee.pearljam.domain.campaign.model; -import fr.insee.pearljam.api.web.exception.VisibilityInvalidException; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; - -import java.util.List; +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; /** * A class representing the visibility of a campaign for an organizational unit @@ -14,7 +11,6 @@ * @param collectionStartDate The start date of collection * @param collectionEndDate The end date of collection * @param endDate The end date of visibility - * @param communicationTemplates List of communication templates associated with the visibility */ public record Visibility( String campaignId, @@ -24,12 +20,9 @@ public record Visibility( Long identificationPhaseStartDate, Long collectionStartDate, Long collectionEndDate, - Long endDate, - List communicationTemplates + Long endDate ) { - public static final String DATE_SHOULD_BE_INCREASING = "Invalid Visibility dates : should be strictly increasing"; - - public static Visibility merge(Visibility currentVisibility, Visibility visibilityToUpdate) { + public static Visibility merge(Visibility currentVisibility, Visibility visibilityToUpdate) throws VisibilityHasInvalidDatesException { Long managementStartDate = visibilityToUpdate.managementStartDate() != null ? visibilityToUpdate.managementStartDate() : currentVisibility.managementStartDate(); Long interviewerStartDate = visibilityToUpdate.interviewerStartDate() != null ? @@ -51,17 +44,16 @@ public static Visibility merge(Visibility currentVisibility, Visibility visibili identificationPhaseStartDate, collectionStartDate, collectionEndDate, - endDate, - null); + endDate); if(isValid(updatedVisibility)) { return updatedVisibility; } - throw new VisibilityInvalidException(DATE_SHOULD_BE_INCREASING); + throw new VisibilityHasInvalidDatesException(); } - private static boolean isValid(Visibility visibility) { + public static boolean isValid(Visibility visibility) { return visibility.managementStartDate() < visibility.interviewerStartDate() && visibility.interviewerStartDate() < visibility.identificationPhaseStartDate() && visibility.identificationPhaseStartDate() < visibility.collectionStartDate() diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CampaignRepository.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CampaignRepository.java new file mode 100644 index 00000000..64000827 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CampaignRepository.java @@ -0,0 +1,4 @@ +package fr.insee.pearljam.domain.campaign.port.serverside; + +public interface CampaignRepository { +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java index 858b3e90..cf46ddba 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java @@ -2,8 +2,6 @@ import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; import fr.insee.pearljam.domain.campaign.model.Visibility; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; import java.util.List; @@ -11,15 +9,40 @@ public interface VisibilityRepository { - CampaignVisibility findCampaignVisibility(String idCampaign, List lstOuId); - + /** + * + * @param idCampaign campaign id + * @param ouIds organisational unit ids + * @return the campaign visibility + */ + CampaignVisibility getCampaignVisibility(String idCampaign, List ouIds); + + /** + * + * @param campaignId campaign id + * @param organizationalUnitId organizational unit id + * @return the visibility for a campaign and an organizational unit + */ Optional findVisibility(String campaignId, String organizationalUnitId); + /** + * + * @param campaignId campaign id + * @return the visibilites of a campaign + */ List findVisibilities(String campaignId); - void create(Visibility visibilityToCreate) throws CampaignNotFoundException, OrganizationalUnitNotFoundException; - - void update(Visibility visibilityToUpdate) throws VisibilityNotFoundException; - + /** + * Update dates for a visibility + * @param visibilityToUpdate the visibility to update + * @throws VisibilityNotFoundException if visibility not found + */ + void updateDates(Visibility visibilityToUpdate) throws VisibilityNotFoundException; + + /** + * + * @param surveyUnitId survey unit id + * @return the visibility for a survey unit + */ Visibility getVisibilityBySurveyUnitId(String surveyUnitId); } diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/VisibilityService.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/VisibilityService.java new file mode 100644 index 00000000..9b5c9f9f --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/VisibilityService.java @@ -0,0 +1,38 @@ +package fr.insee.pearljam.domain.campaign.port.userside; + +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; + +import java.util.List; + +public interface VisibilityService { + + /** + * + * @param campaignId campaign id + * @return the visibilities for the campaign + * @throws CampaignNotFoundException if campaign not found + */ + List findVisibilities(String campaignId) throws CampaignNotFoundException; + + /** + * update dates for a visibility + * @param visibilityToUpdate visibility to update + * @throws VisibilityNotFoundException if visibility not found + * @throws VisibilityHasInvalidDatesException if problems when updating + */ + void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNotFoundException, VisibilityHasInvalidDatesException; + + /** + * Return a global visibility for a campaign, taking into account all visibilities for the campaign + * and define the period the campaign is opened by checking all the visibilities of the organisational units for + * this campaign + * @param idCampaign campaign id + * @param ouIds organisational unit ids + * @return the campaign visibility + */ + CampaignVisibility getCampaignVisibility(String idCampaign, List ouIds); +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java b/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java new file mode 100644 index 00000000..a2d9a33b --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java @@ -0,0 +1,43 @@ +package fr.insee.pearljam.domain.campaign.service; + +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; +import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@RequiredArgsConstructor +@Transactional(rollbackFor = Exception.class) +@Slf4j +public class VisibilityServiceImpl implements VisibilityService { + + private final VisibilityRepository visibilityRepository; + + @Override + public List findVisibilities(String campaignId) throws CampaignNotFoundException { + return visibilityRepository.findVisibilities(campaignId); + } + + @Override + public void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNotFoundException, VisibilityHasInvalidDatesException { + Visibility currentVisibility = visibilityRepository + .findVisibility(visibilityToUpdate.campaignId(), visibilityToUpdate.organizationalUnitId()) + .orElseThrow(VisibilityNotFoundException::new); + Visibility mergedVisibility = Visibility.merge(currentVisibility, visibilityToUpdate); + visibilityRepository.updateDates(mergedVisibility); + } + + @Override + public CampaignVisibility getCampaignVisibility(String idCampaign, List ouIds) { + return visibilityRepository.getCampaignVisibility(idCampaign, ouIds); + } +} diff --git a/src/main/java/fr/insee/pearljam/domain/exception/CampaignOnGoingException.java b/src/main/java/fr/insee/pearljam/domain/exception/CampaignOnGoingException.java new file mode 100644 index 00000000..204bb72f --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/exception/CampaignOnGoingException.java @@ -0,0 +1,10 @@ +package fr.insee.pearljam.domain.exception; + +public class CampaignOnGoingException extends Exception { + + public static final String MESSAGE = "Campaign is ongoing"; + + public CampaignOnGoingException() { + super(MESSAGE); + } +} diff --git a/src/main/java/fr/insee/pearljam/domain/exception/VisibilityHasInvalidDatesException.java b/src/main/java/fr/insee/pearljam/domain/exception/VisibilityHasInvalidDatesException.java new file mode 100644 index 00000000..6577a086 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/exception/VisibilityHasInvalidDatesException.java @@ -0,0 +1,10 @@ +package fr.insee.pearljam.domain.exception; + +public class VisibilityHasInvalidDatesException extends Exception { + + public static final String MESSAGE = "Invalid Visibility dates : should be strictly increasing"; + + public VisibilityHasInvalidDatesException() { + super(MESSAGE); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java index 1e0000da..fe98c865 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java @@ -1,16 +1,10 @@ package fr.insee.pearljam.infrastructure.campaign.adapter; -import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.api.domain.OrganizationUnit; -import fr.insee.pearljam.api.repository.CampaignRepository; -import fr.insee.pearljam.api.repository.OrganizationUnitRepository; import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; import fr.insee.pearljam.domain.campaign.model.Visibility; import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; -import fr.insee.pearljam.api.domain.VisibilityDB; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import fr.insee.pearljam.infrastructure.campaign.jpa.VisibilityJpaRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; @@ -18,16 +12,15 @@ import java.util.List; import java.util.Optional; -@Repository @RequiredArgsConstructor +@Repository public class VisibilityDaoAdapter implements VisibilityRepository { private final VisibilityJpaRepository crudRepository; - private final CampaignRepository campaignRepository; - private final OrganizationUnitRepository organizationUnitRepository; @Override - public CampaignVisibility findCampaignVisibility(String campaignId, List ouIds) { - return crudRepository.findVisibilityByCampaignId(campaignId, ouIds); + public CampaignVisibility getCampaignVisibility(String campaignId, List ouIds) { + return crudRepository + .getCampaignVisibility(campaignId, ouIds); } @Override @@ -45,20 +38,9 @@ public List findVisibilities(String campaignId) { } @Override - public void create(Visibility visibilityToCreate) throws CampaignNotFoundException, OrganizationalUnitNotFoundException { - Campaign campaign = campaignRepository.findById(visibilityToCreate.campaignId()) - .orElseThrow(CampaignNotFoundException::new); - OrganizationUnit organizationUnit = organizationUnitRepository.findById(visibilityToCreate.organizationalUnitId()) - .orElseThrow(OrganizationalUnitNotFoundException::new); - - VisibilityDB visibilityDB = VisibilityDB.fromModel(visibilityToCreate, campaign, organizationUnit); - crudRepository.save(visibilityDB); - } - - @Override - public void update(Visibility visibilityToUpdate) throws VisibilityNotFoundException { + public void updateDates(Visibility visibilityToUpdate) throws VisibilityNotFoundException { VisibilityDB visibilityDB = crudRepository.findVisibilityByCampaignIdAndOuId( - visibilityToUpdate.campaignId(), visibilityToUpdate.organizationalUnitId()) + visibilityToUpdate.campaignId(), visibilityToUpdate.organizationalUnitId()) .orElseThrow(VisibilityNotFoundException::new); visibilityDB.updateDates(visibilityToUpdate); diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java index d56d832e..853522c1 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java @@ -1,6 +1,5 @@ package fr.insee.pearljam.infrastructure.campaign.entity; -import fr.insee.pearljam.api.domain.VisibilityDB; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; @@ -40,15 +39,6 @@ public class CommunicationTemplateDB implements Serializable { @Enumerated(EnumType.STRING) private CommunicationType type; - /** - * The reference to visibility table - */ - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "organization_unit_id", referencedColumnName = "organization_unit_id", insertable = false, updatable = false) - @JoinColumn(name = "campaign_id", referencedColumnName = "campaign_id", insertable = false, updatable = false) - private VisibilityDB visibility; - public static List toModel(List communicationTemplatesDB) { return communicationTemplatesDB.stream() .map(communicationTemplateDB -> new CommunicationTemplate( @@ -64,8 +54,7 @@ public static List fromModel(List new CommunicationTemplateDB(null, communicationTemplate.messhugahId(), communicationTemplate.medium(), - communicationTemplate.type(), - null)) + communicationTemplate.type())) .toList(); } } diff --git a/src/main/java/fr/insee/pearljam/api/domain/VisibilityDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java similarity index 87% rename from src/main/java/fr/insee/pearljam/api/domain/VisibilityDB.java rename to src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java index 9db8a9ef..f62b5741 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/VisibilityDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java @@ -1,10 +1,11 @@ -package fr.insee.pearljam.api.domain; +package fr.insee.pearljam.infrastructure.campaign.entity; import java.io.Serializable; import java.util.List; +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.api.domain.OrganizationUnit; import fr.insee.pearljam.domain.campaign.model.Visibility; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Getter; @@ -12,8 +13,8 @@ import lombok.Setter; import lombok.extern.slf4j.Slf4j; -@Entity(name = "visibility") -@Table +@Entity +@Table(name = "visibility") @NoArgsConstructor @AllArgsConstructor @Getter @@ -34,10 +35,6 @@ public class VisibilityDB implements Serializable { @JoinColumn(name = "campaign_id", insertable = false, updatable = false) private Campaign campaign; - - @OneToMany(fetch = FetchType.LAZY, mappedBy = "visibility", cascade = CascadeType.ALL, orphanRemoval = true) - private List communicationTemplates; - private Long managementStartDate; private Long interviewerStartDate; private Long identificationPhaseStartDate; @@ -78,7 +75,6 @@ public static VisibilityDB fromModel(Visibility visibility, Campaign campaign, O VisibilityDBId id = new VisibilityDBId(organizationUnit.getId(), campaign.getId()); return new VisibilityDB(id, organizationUnit, campaign, - CommunicationTemplateDB.fromModel(visibility.communicationTemplates()), visibility.managementStartDate(), visibility.interviewerStartDate(), visibility.identificationPhaseStartDate(), visibility.collectionStartDate(), visibility.collectionEndDate(), visibility.endDate()); } @@ -92,8 +88,7 @@ public static Visibility toModel(VisibilityDB visibilityDB) { visibilityDB.getIdentificationPhaseStartDate(), visibilityDB.getCollectionStartDate(), visibilityDB.getCollectionEndDate(), - visibilityDB.getEndDate(), - CommunicationTemplateDB.toModel(visibilityDB.getCommunicationTemplates())); + visibilityDB.getEndDate()); } public static List toModel(List visibilityDBs) { diff --git a/src/main/java/fr/insee/pearljam/api/domain/VisibilityDBId.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBId.java similarity index 92% rename from src/main/java/fr/insee/pearljam/api/domain/VisibilityDBId.java rename to src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBId.java index e8a1189f..a95cb55d 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/VisibilityDBId.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBId.java @@ -1,4 +1,4 @@ -package fr.insee.pearljam.api.domain; +package fr.insee.pearljam.infrastructure.campaign.entity; import java.io.Serializable; diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/VisibilityJpaRepository.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/VisibilityJpaRepository.java index 5549838d..2b9a55b3 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/VisibilityJpaRepository.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/VisibilityJpaRepository.java @@ -8,56 +8,45 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; -import fr.insee.pearljam.api.domain.VisibilityDB; -import fr.insee.pearljam.api.domain.VisibilityDBId; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDBId; public interface VisibilityJpaRepository extends JpaRepository { - @Query(value = "SELECT * " - + "FROM visibility " - + "WHERE campaign_id=?1 AND organization_unit_id=?2", nativeQuery = true) + @Query(value = """ + SELECT * FROM visibility + WHERE campaign_id=?1 + AND organization_unit_id=?2""", nativeQuery = true) Optional findVisibilityByCampaignIdAndOuId(String campaignId, String organizationalUnitId); - @Query(value = "SELECT * " - + "FROM visibility " - + "WHERE campaign_id=?1 AND organization_unit_id=?2 " - + "AND management_start_date<=?3 " - + "AND collection_start_date<=?3 " - + "AND collection_end_date>?3", nativeQuery = true) - Optional findVisibilityInCollectionPeriod(String campaignId, String organizationalUnitId, Long date); - - @Query(value = "SELECT * " - + "FROM visibility " - + "WHERE campaign_id=:campaignId AND organization_unit_id IN (:ouIds) " - + "AND management_start_date<=:date " - + "AND collection_start_date<=:date " - + "AND collection_end_date>:date", nativeQuery = true) - List findVisibilityInCollectionPeriodForOUs(@Param("campaignId") String campaignId, - @Param("ouIds") List ouIds, - @Param("date") Long date); - - @Query(value = "SELECT vi " - + "FROM VisibilityDB vi " - + "INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id " - + "WHERE su.id=?1 AND su.organizationUnit.id = vi.organizationUnit.id") + @Query(value = """ + SELECT vi FROM VisibilityDB vi + INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id + WHERE su.id=?1 + AND su.organizationUnit.id = vi.organizationUnit.id""") VisibilityDB getVisibilityBySurveyUnitId(String surveyUnitId); - @Query(value = "SELECT vi " - + "FROM VisibilityDB vi " - + "INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id " - + "WHERE su.organizationUnit.id = vi.organizationUnit.id " - + "AND su.id IN (:SUids)") - List findAllVisibilityBySurveyUnitIds(@Param("SUids") List surveyUnitIds); - - @Query(value = "SELECT new fr.insee.pearljam.domain.campaign.model.CampaignVisibility(MIN(vi.managementStartDate), MIN(vi.interviewerStartDate), MIN(vi.identificationPhaseStartDate), MIN(vi.collectionStartDate), MAX(vi.collectionEndDate), MAX(vi.endDate)) " - + "FROM VisibilityDB vi " - + "INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id " - + "WHERE vi.campaign.id=:campaignId AND vi.organizationUnit.id IN (:OUids)") - CampaignVisibility findVisibilityByCampaignId(@Param("campaignId") String campaignId, - @Param("OUids") List organizationalUnitIds); + @Query(value = """ + SELECT vi FROM VisibilityDB vi + INNER JOIN SurveyUnit su ON su.campaign.id = vi.campaign.id + WHERE su.organizationUnit.id = vi.organizationUnit.id + AND su.id IN (:surveyUnitIds)""") + List findAllVisibilityBySurveyUnitIds(@Param("surveyUnitIds") List surveyUnitIds); + + @Query(value = """ + SELECT new fr.insee.pearljam.domain.campaign.model.CampaignVisibility( + MIN(vi.managementStartDate), + MIN(vi.interviewerStartDate), + MIN(vi.identificationPhaseStartDate), + MIN(vi.collectionStartDate), + MAX(vi.collectionEndDate), + MAX(vi.endDate) + ) + FROM VisibilityDB vi + WHERE vi.campaign.id=:campaignId + AND vi.organizationUnit.id IN (:organizationalUnitIds)""") + CampaignVisibility getCampaignVisibility(@Param("campaignId") String campaignId, + @Param("organizationalUnitIds") List organizationalUnitIds); List findByCampaignId(String campaignId); - - Optional findByCampaignIdIgnoreCaseAndOrganizationUnitIdIgnoreCase(String campaignId, - String organizationalUnitId); } diff --git a/src/main/resources/db/changelog/541_add_communication_template.xml b/src/main/resources/db/changelog/541_add_communication_template.xml index 97aebf69..c9dab24f 100644 --- a/src/main/resources/db/changelog/541_add_communication_template.xml +++ b/src/main/resources/db/changelog/541_add_communication_template.xml @@ -3,12 +3,12 @@ xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd"> - + - + @@ -27,14 +27,14 @@ + baseColumnNames="campaign_id" + constraintName="fk_campaign" + referencedTableName="campaign" + referencedColumnNames="id"/> \ No newline at end of file diff --git a/src/main/resources/db/dataset/init-demo-data.sql b/src/main/resources/db/dataset/init-demo-data.sql index 23fa3013..c2a8cbce 100644 --- a/src/main/resources/db/dataset/init-demo-data.sql +++ b/src/main/resources/db/dataset/init-demo-data.sql @@ -9,7 +9,16 @@ INSERT INTO public.address (dtype, l1, l2, l3, l4, l5, l6, l7, elevator, buildin ('InseeAddress', 'Louise Walker' ,'','','6 impasse du lac' ,'','38200 Vienne' ,'France', false, null, null, null, null, false), ('InseeAddress', 'Anthony Bennett' ,'','','7 avenue de la Liberté' ,'','62000 Arras' ,'France', false, null, null, null, null, false), ('InseeAddress', 'Christopher Lewis' ,'','','8 route du moulin' ,'','35000 Rennes' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Laurent Neville' ,'','','5 route du sapin' ,'','35000 Rennes' ,'France', false, null, null, null, null, false); + ('InseeAddress', 'Laurent Neville' ,'','','5 route du sapin' ,'','35000 Rennes' ,'France', false, null, null, null, null, false) + ('InseeAddress', 'Alain Thé' ,'','','7 rue des Infusions' ,'','75001 Paris' ,'France', false, null, null, null, null, false), + ('InseeAddress', 'Brie Savarin' ,'','','15 avenue des Fromages' ,'','69002 Lyon' ,'France', false, null, null, null, null, false), + ('InseeAddress', 'Cécile Houte' ,'','','8 impasse des Aromates' ,'','13003 Marseille' ,'France', false, null, null, null, null, false), + ('InseeAddress', 'Dan Tifrice' ,'','','12 chemin du Dentifrice' ,'','33000 Bordeaux' ,'France', false, null, null, null, null, false), + ('InseeAddress', 'Émile Pates' ,'','','3 place des Pâtes' ,'','59000 Lille' ,'France', false, null, null, null, null, false), + ('InseeAddress', 'François Appétit' ,'','','22 rue de la Faim' ,'','67000 Strasbourg' ,'France', false, null, null, null, null, false), + ('InseeAddress', 'Gérard Dine' ,'','','9 allée des Gourmands' ,'','44000 Nantes' ,'France', false, null, null, null, null, false), + ('InseeAddress', 'Hélène Gume' ,'','','18 boulevard des Légumes' ,'','31000 Toulouse' ,'France', false, null, null, null, null, false), + ('InseeAddress', 'Jean Fromage' ,'','','5 rue des Croissants' ,'','06000 Nice' ,'France', false, null, null, null, null, false); INSERT INTO public.organization_unit (id, label, type, organization_unit_parent_id) VALUES ('OU-NATIONAL', 'National organizational unit', 'NATIONAL', null); INSERT INTO public.organization_unit (id, label, type, organization_unit_parent_id) VALUES ('OU-NORTH', 'North region organizational unit', 'LOCAL', 'OU-NATIONAL'); @@ -20,7 +29,8 @@ INSERT INTO public.interviewer (id, email, first_name, last_name, phone_number) ('INTW1', 'margie.lucas@ou.com', 'Margie', 'Lucas', '+3391231231230'), ('INTW2', 'carlton.campbell@ou.com', 'Carlton', 'Campbell', '+3391231231231'), ('INTW3', 'gerald.edwards@ou.com', 'Gerald', 'Edwards', '+3391231231231'), - ('INTW4', 'melody.grant@ou.com', 'Melody', 'Grant', '+3391231231231'); + ('INTW4', 'melody.grant@ou.com', 'Melody', 'Grant', '+3391231231231'), + ('GUEST', 'guest.guest@ou.com', 'GUEST', 'GUEST', '+3391231231231'); INSERT INTO public.sample_identifier (dtype, autre, bs, ec, le, nograp, noi, nole, nolog, numfa, rges, ssech) VALUES ('InseeSampleIdentifier', '11', 11, '1', 11, '11', 11, 11, 11, 11, 11, 1), @@ -31,7 +41,16 @@ INSERT INTO public.sample_identifier (dtype, autre, bs, ec, le, nograp, noi, nol ('InseeSampleIdentifier', '21', 21, '2', 21, '21', 21, 21, 21, 21, 21, 1), ('InseeSampleIdentifier', '22', 22, '2', 22, '22', 22, 22, 22, 22, 22, 2), ('InseeSampleIdentifier', '23', 23, '2', 23, '23', 23, 23, 23, 23, 23, 1), - ('InseeSampleIdentifier', '24', 24, '2', 24, '24', 24, 24, 24, 24, 24, 1); + ('InseeSampleIdentifier', '24', 24, '2', 24, '24', 24, 24, 24, 24, 24, 1), + ('InseeSampleIdentifier', '25', 25, '1', 25, '25', 25, 25, 25, 25, 25, 1), + ('InseeSampleIdentifier', '26', 26, '1', 26, '26', 26, 26, 26, 26, 26, 1), + ('InseeSampleIdentifier', '27', 27, '1', 27, '27', 27, 27, 27, 27, 27, 2), + ('InseeSampleIdentifier', '28', 28, '1', 28, '28', 28, 28, 28, 28, 28, 3), + ('InseeSampleIdentifier', '29', 29, '2', 29, '29', 29, 29, 29, 29, 29, 1), + ('InseeSampleIdentifier', '30', 30, '2', 30, '30', 30, 30, 30, 30, 30, 1), + ('InseeSampleIdentifier', '31', 31, '2', 31, '31', 31, 31, 31, 31, 31, 2), + ('InseeSampleIdentifier', '32', 32, '2', 32, '32', 32, 32, 32, 32, 32, 1), + ('InseeSampleIdentifier', '33', 33, '2', 33, '33', 33, 33, 33, 33, 33, 1); INSERT INTO public.USER (id, first_name, last_name, organization_unit_id) VALUES ('ABC', 'Melinda', 'Webb', 'OU-NORTH'), @@ -39,7 +58,7 @@ INSERT INTO public.USER (id, first_name, last_name, organization_unit_id) VALUES ('GHI', 'Elsie', 'Clarke', 'OU-SOUTH'), ('JKL', 'Julius', 'Howell', 'OU-NATIONAL'), ('MNO', 'Ted', 'Kannt', 'OU-WEST'), - ('GUEST', 'firstname', 'lastname', 'OU-NORTH'); + ('GUEST', 'firstname', 'lastname', 'OU-NATIONAL'); INSERT INTO public.campaign (id, label, email, identification_configuration, contact_attempt_configuration, contact_outcome_configuration) VALUES ('SIMPSONS2020X00', 'Survey on the Simpsons tv show 2020', 'first.email@test.com', 'IASCO', 'F2F', 'F2F'), @@ -50,7 +69,11 @@ INSERT INTO public.campaign (id, label, email, identification_configuration, con INSERT INTO public.preference (id_user, id_campaign) VALUES ('GHI', 'SIMPSONS2020X00'), ('JKL', 'SIMPSONS2020X00'), - ('JKL', 'VQS2021X00'); + ('JKL', 'VQS2021X00'), + ('GUEST', 'SIMPSONS2020X00'), + ('GUEST', 'VQS2021X00'), + ('GUEST', 'ZCLOSEDX00'), + ('GUEST', 'XCLOSEDX00'); INSERT INTO visibility ( @@ -119,16 +142,24 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000); -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '13', FALSE, a.id, 'SIMPSONS2020X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Claude Watkins' AND s.bs='13'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '14', FALSE, a.id, 'SIMPSONS2020X00', 'INTW3', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Veronica Gill' AND s.bs='14'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '20', FALSE, a.id, 'VQS2021X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christine Aguilar' AND s.bs='20'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '21', FALSE, a.id, 'VQS2021X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Louise Walker' AND s.bs='21'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '22', FALSE, a.id, 'VQS2021X00', 'INTW4', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Anthony Bennett' AND s.bs='22'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '23', FALSE, a.id, 'VQS2021X00', 'INTW4', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christopher Lewis' AND s.bs='23'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '24', TRUE, a.id, 'SIMPSONS2020X00', NULL, s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Laurent Neville' AND s.bs='24'; - +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', TRUE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '13', FALSE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Claude Watkins' AND s.bs='13'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '14', FALSE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Veronica Gill' AND s.bs='14'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '20', FALSE, a.id, 'VQS2021X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christine Aguilar' AND s.bs='20'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '21', FALSE, a.id, 'VQS2021X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Louise Walker' AND s.bs='21'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '22', FALSE, a.id, 'VQS2021X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Anthony Bennett' AND s.bs='22'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '23', FALSE, a.id, 'VQS2021X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christopher Lewis' AND s.bs='23'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '24', TRUE, a.id, 'SIMPSONS2020X00', NULL, s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Laurent Neville' AND s.bs='24'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '25', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Alain Thé' AND s.bs='25'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '26', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Brie Savarin' AND s.bs='26'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '27', FALSE, a.id, 'SIMPSONS2020X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cécile Houte' AND s.bs='27'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '28', FALSE, a.id, 'SIMPSONS2020X00', 'INTW3', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Dan Tifrice' AND s.bs='28'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '29', FALSE, a.id, 'VQS2021X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Émile Pates' AND s.bs='29'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '30', FALSE, a.id, 'VQS2021X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='François Appétit' AND s.bs='30'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '31', FALSE, a.id, 'VQS2021X00', 'INTW4', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Gérard Dine' AND s.bs='31'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '32', FALSE, a.id, 'VQS2021X00', 'INTW4', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Hélène Gume' AND s.bs='32'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '33', TRUE, a.id, 'SIMPSONS2020X00', NULL, s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Jean Fromage' AND s.bs='33'; INSERT INTO public.person (email, favorite_email, first_name, last_name, birthdate, title, privileged, survey_unit_id) VALUES ('test@test.com',TRUE, 'Ted', 'Farmer', 11111111, 0, TRUE, '11'), @@ -143,7 +174,20 @@ INSERT INTO public.person (email, favorite_email, first_name, last_name, birthda ('test@test.com', TRUE,'Aimée', 'Lamothe', 11111111, 0, TRUE, '21'), ('test@test.com', TRUE,'Perrin', 'Blanchard', 11111111, 0, TRUE, '22'), ('test@test.com', TRUE,'Artus', 'Arnoux', 11111111, 0, TRUE, '23'), - ('test@test.com', TRUE,'Laurent', 'Neville', 11111111, 0, TRUE, '24'); + ('test@test.com', TRUE,'Laurent', 'Neville', 11111111, 0, TRUE, '24'), + ('test@test.com', TRUE, 'Harry', 'Cover', 11111111, 1, FALSE, '25'), + ('test@test.com', TRUE, 'Ella', 'Gance', 11111111, 0, FALSE, '25'), + ('test@test.com', TRUE, 'Jean', 'Neige', 11111111, 0, FALSE, '26'), + ('test@test.com', TRUE, 'Phil', 'Harmonie', 11111111, 0, FALSE, '28') + ('test@test.com', TRUE, 'Alain', 'Thé', 11111111, 0, TRUE, '25'), + ('test@test.com', TRUE, 'Brie', 'Savarin', 11111111, 1, TRUE, '26'), + ('test@test.com', TRUE, 'Cécile', 'Houte', 11111111, 0, TRUE, '27'), + ('test@test.com', TRUE, 'Dan', 'Tifrice', 11111111, 1 TRUE, '28'), + ('test@test.com', TRUE, 'Émile', 'Pates', 11111111, 1, TRUE, '29'), + ('test@test.com', TRUE, 'François', 'Appétit', 11111111, 1, TRUE, '30'), + ('test@test.com', TRUE, 'Gérard', 'Dine', 11111111, 0, TRUE, '31'), + ('test@test.com', TRUE, 'Hélène', 'Gume', 11111111, 0, TRUE, '32'), + ('test@test.com', TRUE, 'Jean', 'Fromage', 11111111, 0, TRUE, '33'); @@ -161,8 +205,19 @@ INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRU INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Perrin' and p.last_name='Blanchard' and p.survey_unit_id='22'; INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Artus' and p.last_name='Arnoux' and p.survey_unit_id='23'; INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Laurent' and p.last_name='Neville' and p.survey_unit_id='24'; - - +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Harry' and p.last_name='Cover' and p.survey_unit_id='25'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT FALSE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Ella' and p.last_name='Gance' and p.survey_unit_id='25'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Jean' and p.last_name='Neige' and p.survey_unit_id='26'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Phil' and p.last_name='Harmonie' and p.survey_unit_id='28'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Alain' and p.last_name='Thé' and p.survey_unit_id='25'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Brie' and p.last_name='Savarin' and p.survey_unit_id='26'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Cécile' and p.last_name='Houte' and p.survey_unit_id='27'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Dan' and p.last_name='Tifrice' and p.survey_unit_id='28'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Émile' and p.last_name='Pates' and p.survey_unit_id='29'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='François' and p.last_name='Appétit' and p.survey_unit_id='30'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Gérard' and p.last_name='Dine' and p.survey_unit_id='31'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Hélène' and p.last_name='Gume' and p.survey_unit_id='32'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Jean' and p.last_name='Fromage' and p.survey_unit_id='33'; INSERT INTO public.state (date, type, survey_unit_id) VALUES (111112111,'VIN', '11'), @@ -175,20 +230,34 @@ INSERT INTO public.state (date, type, survey_unit_id) VALUES (1590504478334, 'VIC', '20'), (1590504478334, 'VIC', '21'), (1590504478334, 'FIN', '22'), - (1590504478334, 'VIC', '23'); + (1590504478334, 'VIC', '23'), + (111112111,'VIN', '25'), + (110111111,'NNS', '25'), + (111111111,'TBR', '26'), + (111111111,'TBR', '27'), + (111111111,'TBR', '28'), + (101111111,'TBR', '25'), + (101111111,'TBR', '33'), + (1590504478334, 'VIC', '29'), + (1590504478334, 'VIC', '30'), + (1590504478334, 'FIN', '31'), + (1590504478334, 'VIC', '32'); INSERT INTO public.contact_outcome (date, type, survey_unit_id) VALUES - (1590504478334, 'DUK', '24'); + (1590504478334, 'DUK', '24'), + (1590504478334, 'DUK', '33'); INSERT INTO public.comment (type, value, survey_unit_id) VALUES - ('INTERVIEWER', 'un commentaire', '13'); + ('INTERVIEWER', 'un commentaire', '13'), + ('INTERVIEWER', 'un commentaire', '27'); INSERT INTO closing_cause (date, type, survey_unit_id) VALUES - (EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, 'NPI', '11'); + (EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, 'NPI', '11'), + (EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, 'NPI', '25'); INSERT INTO public.identification (survey_unit_id, identification,access,situation,category,occupant) VALUES - ('11', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'); - -INSERT INTO public.identification (survey_unit_id, identification,access,situation,category,occupant) VALUES - ('21', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'); \ No newline at end of file + ('11', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + ('21', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + ('25', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + ('30', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'); \ No newline at end of file diff --git a/src/main/resources/db/dataset/reinit-test-data.sql b/src/main/resources/db/dataset/reinit-test-data.sql index 49b6fdf3..6d5271fa 100644 --- a/src/main/resources/db/dataset/reinit-test-data.sql +++ b/src/main/resources/db/dataset/reinit-test-data.sql @@ -65,7 +65,7 @@ INSERT INTO public.USER (id, first_name, last_name, organization_unit_id) VALUES ('GHI', 'Elsie', 'Clarke', 'OU-SOUTH'), ('JKL', 'Julius', 'Howell', 'OU-NATIONAL'), ('MNO', 'Ted', 'Kannt', 'OU-WEST'), - ('GUEST', 'firstname', 'lastname', 'OU-NORTH'); + ('GUEST', 'firstname', 'lastname', 'OU-NATIONAL'); INSERT INTO public.campaign (id, label, email, identification_configuration, contact_attempt_configuration, contact_outcome_configuration) VALUES ('SIMPSONS2020X00', 'Survey on the Simpsons tv show 2020', 'first.email@test.com', 'IASCO', 'F2F', 'F2F'), @@ -76,7 +76,11 @@ INSERT INTO public.campaign (id, label, email, identification_configuration, con INSERT INTO public.preference (id_user, id_campaign) VALUES ('GHI', 'SIMPSONS2020X00'), ('JKL', 'SIMPSONS2020X00'), - ('JKL', 'VQS2021X00'); + ('JKL', 'VQS2021X00'), + ('GUEST', 'SIMPSONS2020X00'), + ('GUEST', 'VQS2021X00'), + ('GUEST', 'ZCLOSEDX00'), + ('GUEST', 'XCLOSEDX00'); INSERT INTO visibility ( @@ -89,61 +93,15 @@ INSERT INTO visibility ( interviewer_start_date, management_start_date ) VALUES - ('OU-NORTH', 'SIMPSONS2020X00', - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('MONTH', 1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('MONTH', 2, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -2, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -3, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -4, CURRENT_TIMESTAMP())) * 1000), - - ('OU-NORTH', 'VQS2021X00', - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('MONTH', 1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('MONTH', 2, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -2, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -3, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -4, CURRENT_TIMESTAMP())) * 1000), - - ('OU-SOUTH', 'VQS2021X00', - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('MONTH', 1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('MONTH', 2, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -2, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -3, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -4, CURRENT_TIMESTAMP())) * 1000), - - ('OU-SOUTH', 'SIMPSONS2020X00', - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('MONTH', 1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('MONTH', 2, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -2, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -3, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -4, CURRENT_TIMESTAMP())) * 1000), - - ('OU-SOUTH', 'ZCLOSEDX00', - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -3, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -4, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -5, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -6, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -7, CURRENT_TIMESTAMP())) * 1000), - - ('OU-WEST', 'ZCLOSEDX00', - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -3, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -4, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -5, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -6, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -7, CURRENT_TIMESTAMP())) * 1000), - - ('OU-SOUTH', 'XCLOSEDX00', - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -3, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -4, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -1, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -5, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -6, CURRENT_TIMESTAMP())) * 1000, - DATEDIFF('SECOND', '1970-01-01 00:00:00', DATEADD('DAY', -7, CURRENT_TIMESTAMP())) * 1000); + ('OU-NORTH', 'SIMPSONS2020X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308), + ('OU-SOUTH', 'SIMPSONS2020X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308), + ('OU-NORTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308), + ('OU-SOUTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308), + ('OU-SOUTH', 'XCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308), + ('OU-SOUTH', 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308), + ('OU-WEST' , 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308); + + INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; @@ -188,8 +146,6 @@ INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRU INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Artus' and p.last_name='Arnoux' and p.survey_unit_id='23'; INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Laurent' and p.last_name='Neville' and p.survey_unit_id='24'; - - INSERT INTO public.state (date, type, survey_unit_id) VALUES (111112111,'VIN', '11'), (110111111,'NNS', '11'), @@ -206,6 +162,9 @@ INSERT INTO public.state (date, type, survey_unit_id) VALUES INSERT INTO public.contact_outcome (date, type, survey_unit_id) VALUES (1590504478334, 'DUK', '24'); +INSERT INTO public.referent (campaign_id, first_name, last_name, role, phone_number) VALUES + ('SIMPSONS2020X00', 'Gerard', 'Menvuca', 'PRIMARY', '0303030303'); + INSERT INTO public.comment (type, value, survey_unit_id) VALUES ('INTERVIEWER', 'un commentaire', '13'); diff --git a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java index e018b10b..f2d553ee 100644 --- a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java +++ b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java @@ -20,15 +20,14 @@ import java.time.Instant; import java.time.LocalDate; -import java.time.LocalDateTime; import java.time.ZoneId; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.List; import java.util.Optional; -import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignUpdateDto; import fr.insee.pearljam.api.service.*; +import fr.insee.pearljam.api.utils.MockMvcTestUtils; import org.json.JSONException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -48,7 +47,6 @@ import org.springframework.test.web.client.ExpectedCount; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.web.client.RestTemplate; @@ -58,7 +56,6 @@ import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.controller.WsText; -import fr.insee.pearljam.api.domain.Campaign; import fr.insee.pearljam.api.domain.ClosingCause; import fr.insee.pearljam.api.domain.ClosingCauseType; import fr.insee.pearljam.domain.surveyunit.model.CommentType; @@ -78,9 +75,8 @@ import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.api.domain.Title; import fr.insee.pearljam.api.domain.User; -import fr.insee.pearljam.api.domain.VisibilityDB; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import fr.insee.pearljam.api.dto.address.AddressDto; -import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; import fr.insee.pearljam.api.surveyunit.dto.CommentDto; import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; @@ -90,7 +86,6 @@ import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; import fr.insee.pearljam.api.dto.person.PersonDto; import fr.insee.pearljam.api.dto.phonenumber.PhoneNumberDto; -import fr.insee.pearljam.api.dto.referent.ReferentDto; import fr.insee.pearljam.api.dto.sampleidentifier.SampleIdentifiersDto; import fr.insee.pearljam.api.dto.state.StateDto; import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitContextDto; @@ -98,8 +93,6 @@ import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitInterviewerLinkDto; import fr.insee.pearljam.api.dto.user.UserContextDto; import fr.insee.pearljam.api.dto.user.UserDto; -import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignCreateDto; -import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitVisibilityDto; import fr.insee.pearljam.api.exception.NotFoundException; import fr.insee.pearljam.api.repository.CampaignRepository; import fr.insee.pearljam.api.repository.ClosingCauseRepository; @@ -185,7 +178,7 @@ private ResultMatcher expectTimestampFromCurrentDate(String expression, int unit return mvcResult -> { String content = mvcResult.getResponse().getContentAsString(); long timestamp = JsonPath.read(content, expression); - LocalDate localDateNow = LocalDate.now(); + LocalDate localDateNow = MockMvcTestUtils.getDate(); Instant instant = Instant.ofEpochMilli(timestamp); LocalDate dateToCheck = LocalDate.ofInstant(instant, ZoneId.systemDefault()); assertEquals(dateToCheck, localDateNow.plus(unitToAdd, chronoUnit)); @@ -929,147 +922,6 @@ void testGetNbSuNotAttributedNotFound() throws Exception { .andExpect(status().isNotFound()); } - /** - * Test that the PUT endpoint - * "api/campaign/{idCampaign}/organizational-unit/{idOu}/visibility" - * return 200 when modifying all dates - * - * @throws InterruptedException - */ - @Test - @Order(29) - void testPutVisibilityModifyAllDates() throws Exception { - String campaignInput = """ - { - "managementStartDate": 1575937000000, - "interviewerStartDate": 1576801000000, - "identificationPhaseStartDate": 1577233000000, - "collectionStartDate": 1577837800000, - "collectionEndDate": 1640996200000, - "endDate": 1641514600000 - } - """; - - mockMvc.perform(put("/api/campaign/SIMPSONS2020X00/organizational-unit/OU-NORTH/visibility") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON) - .content(campaignInput)) - .andExpect(status().isOk()); - - Optional visi = visibilityRepository.findVisibilityByCampaignIdAndOuId("SIMPSONS2020X00", - "OU-NORTH"); - assertEquals(true, visi.isPresent()); - assertEquals(1575937000000L, visi.get().getManagementStartDate()); - assertEquals(1576801000000L, visi.get().getInterviewerStartDate()); - assertEquals(1577233000000L, visi.get().getIdentificationPhaseStartDate()); - assertEquals(1577837800000L, visi.get().getCollectionStartDate()); - assertEquals(1640996200000L, visi.get().getCollectionEndDate()); - assertEquals(1641514600000L, visi.get().getEndDate()); - } - - /** - * Test that the PUT endpoint - * "api/campaign/{idCampaign}/organizational-unit/{idOu}/visibility" - * return 200 when modifying start date - * - * @throws InterruptedException - */ - @Test - @Disabled("Need Clock injection refactor") - @Order(30) - void testPutVisibilityModifyCollectionStartDate() - throws Exception { - - long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); - String jsonContent = String.format("{\"collectionStartDate\": %d}", now); - - mockMvc.perform(put("/api/campaign/SIMPSONS2020X00/organizational-unit/OU-NORTH/visibility") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON) - .content(jsonContent)) - .andExpectAll( - status().isOk(), - expectValidCollectionStartDate()); - - Optional visi = visibilityRepository.findVisibilityByCampaignIdAndOuId("SIMPSONS2020X00", - "OU-NORTH"); - assertEquals(true, visi.isPresent()); - assertEquals(now, visi.get().getCollectionStartDate()); - - } - - /** - * Test that the PUT endpoint - * "api/campaign/{idCampaign}/organizational-unit/{idOu}/visibility" - * return 200 when modifying end date - * - * @throws InterruptedException - */ - @Test - @Disabled("Need Clock injection refactor") - @Order(31) - void testPutVisibilityModifyCollectionEndDate() - throws Exception { - long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); - String jsonContent = String.format("{\"collectionEndDate\": %d}", now); - - mockMvc.perform(put("/api/campaign/SIMPSONS2020X00/organizational-unit/OU-NORTH/visibility") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON) - .content(jsonContent)) - .andExpect(status().isOk()); - Optional visi = visibilityRepository.findVisibilityByCampaignIdAndOuId("SIMPSONS2020X00", - "OU-NORTH"); - assertEquals(true, visi.isPresent()); - assertEquals(now, visi.get().getCollectionEndDate()); - } - - /** - * Test that the PUT endpoint - * "api/campaign/{idCampaign}/organizational-unit/{idOu}/visibility" - * return 400 when empty body - * - * @throws InterruptedException - */ - @Test - @Order(32) - void testPutVisibilityEmptyBody() throws Exception { - mockMvc.perform(put("/api/campaign/SIMPSONS2020X00/organizational-unit/OU-NORTH/visibility") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON) - .content("{}")) - .andExpect(status().isBadRequest()); - - } - - /** - * Test that the PUT endpoint - * "api/campaign/{idCampaign}/organizational-unit/{idOu}/visibility" - * return 400 when bad format - * - * @throws InterruptedException - */ - @Test - @Order(33) - void testPutVisibilityBadFormat() throws Exception { - String requestBody = """ - { - "managementStartDate": 1640996200000, - "interviewerStartDate": "10/10/2020", - "identificationPhaseStartDate": 1641514600000, - "collectionStartDate": 1577233000000, - "collectionEndDate": 1576801000000, - "endDate": 1575937000000 - }"""; - - mockMvc.perform(put("/api/campaign/SIMPSONS2020X00/organizational-unit/OU-NORTH/visibility") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON) - .content(requestBody)) - .andExpect(status().isBadRequest()); - - } - /** * Test that the POST endpoint "api/message" return 200 * @@ -1562,142 +1414,6 @@ void testGetOrganizationUnits() throws Exception { } - /** - * Test that the Post endpoint - * "/campaign" returns 200 - * - * @throws InterruptedException - */ - @Test - @Order(100) - void testPostCampaignContext() throws Exception { - VisibilityCampaignCreateDto visi1 = generateDumbVisibilityCampaignCreateDto("OU-NORTH"); - VisibilityCampaignCreateDto visi2 = generateDumbVisibilityCampaignCreateDto("OU-SOUTH"); - - CampaignCreateDto campDto = new CampaignCreateDto( - "campId", - "An other campaign", - List.of(visi1, visi2), - List.of(new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY")), - null, - IdentificationConfiguration.IASCO, - ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, - null - ); - - mockMvc.perform(post(Constants.API_CAMPAIGN) - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campDto))) - .andExpect(status().isOk()); - - Optional campOpt = campaignRepository.findById("CAMPID"); - assertTrue(campOpt.isPresent()); - assertEquals("An other campaign", campOpt.get().getLabel()); - - Optional visi1Opt = visibilityRepository.findVisibilityByCampaignIdAndOuId("CAMPID", "OU-NORTH"); - Optional visi2Opt = visibilityRepository.findVisibilityByCampaignIdAndOuId("CAMPID", "OU-SOUTH"); - - assertTrue(visi1Opt.isPresent()); - assertTrue(visi2Opt.isPresent()); - - VisibilityDB visi = visi1Opt.get(); - assertEquals(1111L, visi.getCollectionStartDate()); - assertEquals(2222L, visi.getCollectionEndDate()); - assertEquals(3333L, visi.getIdentificationPhaseStartDate()); - assertEquals(4444L, visi.getInterviewerStartDate()); - assertEquals(5555L, visi.getManagementStartDate()); - assertEquals(6666L, visi.getEndDate()); - - List refs = referentservice.findByCampaignId("CAMPID"); - assertEquals(1, refs.size()); - assertEquals("Bob", refs.get(0).getFirstName()); - assertEquals("Marley", refs.get(0).getLastName()); - assertEquals("0123456789", refs.get(0).getPhoneNumber()); - assertEquals("PRIMARY", refs.get(0).getRole()); - - assertEquals(IdentificationConfiguration.IASCO, campOpt.get().getIdentificationConfiguration()); - assertEquals(ContactAttemptConfiguration.F2F, campOpt.get().getContactAttemptConfiguration()); - assertEquals(ContactOutcomeConfiguration.F2F, campOpt.get().getContactOutcomeConfiguration()); - assertEquals(false, campOpt.get().getCommunicationConfiguration()); - - } - - /** - * Test that the Post endpoint - * "/campaign" returns 400 - * when an attribute is missing - * - * @throws InterruptedException - */ - @Test - @Order(101) - void testPostCampaignContextNoLabel() throws Exception { - VisibilityCampaignCreateDto visi1 = generateDumbVisibilityCampaignCreateDto("OU-NORTH"); - VisibilityCampaignCreateDto visi2 = generateDumbVisibilityCampaignCreateDto("OU-SOUTH"); - - CampaignCreateDto campDto = new CampaignCreateDto( - "campId2", - null, - List.of(visi1, visi2), - null, - null, - null, - null, - null, - null - ); - - mockMvc.perform(post(Constants.API_CAMPAIGN) - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campDto))) - .andExpect(status().isBadRequest()); - - // Campaign should not have been created - Optional campOpt = campaignRepository.findById("campId2"); - assertTrue(!campOpt.isPresent()); - } - - /** - * Test that the Post endpoint - * "/campaign" returns 400 - * when an an organizational unit does not exist - * - * @throws InterruptedException - */ - @Test - @Order(102) - void testPostCampaignContextMissingOU() throws Exception { - - VisibilityCampaignCreateDto visi1 = generateDumbVisibilityCampaignCreateDto("OU-NORTH"); - VisibilityCampaignCreateDto visi2 = generateDumbVisibilityCampaignCreateDto("AN-OU-THAT-DOESNT-EXIST"); - - CampaignCreateDto campDto = new CampaignCreateDto( - "campId3", - null, - List.of(visi1, visi2), - null, - null, - null, - null, - null, - null - ); - - mockMvc.perform(post(Constants.API_CAMPAIGN) - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campDto))) - .andExpect(status().isBadRequest()); - - // Campaign should not have been created - Optional campOpt = campaignRepository.findById("campId3"); - assertTrue(!campOpt.isPresent()); - - } - /** * Test that the Post endpoint * "/organization-unit/context" returns 200 @@ -2499,46 +2215,6 @@ void testOngoingNotFound() throws Exception { .andExpect(status().isNotFound()); } - @Test - @Order(221) - void testUpdateVisibilityByOu() throws Exception { - SurveyUnitVisibilityDto visibility = generateSurveyUnitVisibilityDto("OU-WEST", "ZCLOSEDX00", false); - SurveyUnitVisibilityDto invalidVcd = generateSurveyUnitVisibilityDto("OU-WEST", "ZCLOSEDX00", true); - - String visibilityJson = asJsonString(visibility); - String emptyVisibilityJson = "{}"; - String invalidVisibilityJson = asJsonString(invalidVcd); - - // BAD REQUEST - updateVisibility("ZCLOSEDX00", "OU-WEST", emptyVisibilityJson).andExpect(status().isBadRequest()); - - // NOT FOUND - updateVisibility("ZCLOSEDX00", "MISSING", visibilityJson).andExpect(status().isNotFound()); - - // CONFLICT - updateVisibility("ZCLOSEDX00", "OU-WEST", invalidVisibilityJson).andExpect(status().isConflict()); - - // OK - updateVisibility("ZCLOSEDX00", "OU-WEST", visibilityJson).andExpect(status().isOk()); - assertEquals(visibility.endDate(), - visibilityRepository.findVisibilityByCampaignIdAndOuId("ZCLOSEDX00", "OU-WEST").get().getEndDate()); - } - - private ResultActions updateVisibility(String campaignId, String OuId, String visibility) throws Exception { - return mockMvc.perform( - put(updateVisibilityUrl(campaignId, OuId)) - .with(authentication(LOCAL_USER)) - .content(visibility) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)); - } - - private static String updateVisibilityFormat = "/api/campaign/%s/organizational-unit/%s/visibility"; - - private String updateVisibilityUrl(String campaignId, String OuId) { - return String.format(updateVisibilityFormat, campaignId, OuId); - } - private static String asJsonString(final Object obj) { try { return new ObjectMapper().writeValueAsString(obj); @@ -2593,43 +2269,6 @@ private InterviewerContextDto generateInterviewerBContextDto(String id) { Title.MISS); } - private VisibilityCampaignCreateDto generateDumbVisibilityCampaignCreateDto(String ouId) { - return new VisibilityCampaignCreateDto(5555L, 4444L, - 3333L, 1111L, - 2222L, 6666L, ouId, null); - } - - private VisibilityCampaignCreateDto generateVisibilityCampaignCreateDto(String OuId, String campaignId) { - VisibilityDB vis = visibilityRepository.findVisibilityByCampaignIdAndOuId(campaignId, OuId).get(); - return new VisibilityCampaignCreateDto(vis.getManagementStartDate(), vis.getInterviewerStartDate(), - vis.getIdentificationPhaseStartDate(), vis.getCollectionStartDate(), - vis.getCollectionEndDate(), vis.getEndDate(), vis.getOrganizationUnit().getId(), null); - } - - private VisibilityCampaignUpdateDto generateVisibilityCampaignUpdateDto(String OuId, String campaignId, boolean isInvalid) { - VisibilityDB vis = visibilityRepository.findVisibilityByCampaignIdAndOuId(campaignId, OuId).get(); - Long interviewerStartDate = vis.getInterviewerStartDate(); - if(isInvalid) { - interviewerStartDate = vis.getIdentificationPhaseStartDate(); - } - return new VisibilityCampaignUpdateDto(vis.getManagementStartDate(), interviewerStartDate, - vis.getIdentificationPhaseStartDate(), vis.getCollectionStartDate(), - vis.getCollectionEndDate(), vis.getEndDate(), vis.getOrganizationUnit().getId()); - } - - private SurveyUnitVisibilityDto generateSurveyUnitVisibilityDto(String ouId, String campaignId, - boolean isInvalid) { - VisibilityDB vis = visibilityRepository.findVisibilityByCampaignIdAndOuId(campaignId, ouId).get(); - - Long interviewerStartDate = vis.getInterviewerStartDate(); - if(isInvalid) { - interviewerStartDate = vis.getIdentificationPhaseStartDate(); - } - return new SurveyUnitVisibilityDto(vis.getManagementStartDate(), interviewerStartDate, - vis.getIdentificationPhaseStartDate(), vis.getCollectionStartDate(), - vis.getCollectionEndDate(), vis.getEndDate()); - } - private UserDto generateValidUser() { OrganizationUnitDto ou = organizationUnitRepository.findDtoByIdIgnoreCase("OU-SOUTH").get(); return new UserDto("XYZ", "Bob", "Lennon", ou, null); diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java index fa3af95a..5dd18795 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java @@ -1,7 +1,7 @@ package fr.insee.pearljam.api.campaign.controller; import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; -import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignCreateDto; +import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignCreateDto; import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.controller.CampaignController; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; @@ -9,17 +9,19 @@ import fr.insee.pearljam.api.domain.IdentificationConfiguration; import fr.insee.pearljam.api.dto.referent.ReferentDto; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.JsonTestHelper; import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; import fr.insee.pearljam.api.web.exception.ExceptionControllerAdvice; import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; -import org.javatuples.Pair; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import fr.insee.pearljam.api.service.dummy.CampaignFakeService; -import fr.insee.pearljam.api.service.dummy.ReferentFakeService; +import fr.insee.pearljam.api.campaign.controller.dummy.CampaignFakeService; +import fr.insee.pearljam.api.campaign.controller.dummy.ReferentFakeService; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; @@ -52,82 +54,64 @@ void setup() { @Test @DisplayName("Should create campaign") void testCreateCampaign01() throws Exception { - Pair firstVisibility = generateVisibility("OU-NORTH", 1721683250L, - 1721683251L, - 1721683252L, - 1721683253L, - 1721683254L, - 1721683255L); - Pair secondVisibility = generateVisibility("OU-SOUTH", 1721683260L, - 1721683261L, - 1721683262L, - 1721683263L, - 1721683264L, - 1721683265L); - Pair firstReferent = generateReferent("Bob", "Marley", "0123456789", "PRIMARY"); - Pair secondReferent = generateReferent("Dupont", "Jean", "1234567890", "PRIMARY"); - Pair campaign = generateCampaign("campId", "An other campaign", - "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, - true, - List.of(firstVisibility, secondVisibility), - List.of(firstReferent, secondReferent)); + CampaignCreateDto campaign= generateDefaultCampaign(); mockMvc.perform(post(Constants.API_CAMPAIGN) .contentType(MediaType.APPLICATION_JSON) - .content(campaign.getValue0())) + .content(JsonTestHelper.toJson(campaign))) .andExpect(status().isOk()); CampaignCreateDto campaignCreated = campaignService.getCampaignCreated(); - assertThat(campaignCreated).isEqualTo(campaign.getValue1()); + assertThat(campaignCreated).isEqualTo(campaign); } @Test @DisplayName("Should return bad request when campaign already exists") void testCreateCampaign02() throws Exception { campaignService.setShouldThrowCampaignAlreadyExistException(true); - Pair visibility = generateVisibility("OU-SOUTH", 1721683260L, - 1721683261L, - 1721683262L, - 1721683263L, - 1721683264L, - 1721683265L); - Pair campaign = generateCampaign("campId", "An other campaign", - "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, - true, - List.of(visibility), - List.of()); + CampaignCreateDto campaign = generateDefaultCampaign(); mockMvc.perform(post(Constants.API_CAMPAIGN) .contentType(MediaType.APPLICATION_JSON) - .content(campaign.getValue0())) + .content(JsonTestHelper.toJson(campaign))) .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, CampaignAlreadyExistException.MESSAGE)); } @Test - @DisplayName("Should return bad request when invalid campaign input") + @DisplayName("Should return bad request when organizationalUnit does not exist") void testCreateCampaign03() throws Exception { + campaignService.setShouldThrowOrganizationalUnitNotFoundException(true); + CampaignCreateDto campaign = generateDefaultCampaign(); - Pair visibility = generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, + mockMvc.perform(post(Constants.API_CAMPAIGN) + .contentType(MediaType.APPLICATION_JSON) + .content(JsonTestHelper.toJson(campaign))) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, Constants.API_CAMPAIGN, OrganizationalUnitNotFoundException.MESSAGE)); + } + + @Test + @DisplayName("Should return bad request when invalid campaign label") + void testCreateCampaign04() throws Exception { + + VisibilityCampaignCreateDto visibility = generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, 1721683253L, 1721683254L, 1721683255L); - Pair campaign1 = generateCampaign(" ", "An other campaign", + CampaignCreateDto campaign1 = generateCampaign(" ", "An other campaign", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, true, List.of(visibility), List.of()); - Pair campaign2 = generateCampaign("campId", " ", + CampaignCreateDto campaign2 = generateCampaign("campId", " ", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, true, List.of(visibility), List.of()); - List> campaigns = List.of(campaign1, campaign2); - for(Pair campaign : campaigns) { + List campaigns = List.of(campaign1, campaign2); + for(CampaignCreateDto campaign : campaigns) { mockMvc.perform(post(Constants.API_CAMPAIGN) .contentType(MediaType.APPLICATION_JSON) - .content(campaign.getValue0())) + .content(JsonTestHelper.toJson(campaign))) .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); CampaignCreateDto campaignCreated = campaignService.getCampaignCreated(); @@ -138,8 +122,8 @@ void testCreateCampaign03() throws Exception { @Test @DisplayName("Should return bad request when invalid visibility") - void testCreateCampaign04() throws Exception { - List> invalidVisibilities = new ArrayList<>(Arrays.asList( + void testCreateCampaign05() throws Exception { + List invalidVisibilities = new ArrayList<>(Arrays.asList( generateVisibility(" ", 1721683250L, 1721683251L, 1721683252L, 1721683253L, 1721683254L, 1721683255L), generateVisibility("OU-NORTH", null, 1721683251L, 1721683252L, @@ -157,12 +141,12 @@ void testCreateCampaign04() throws Exception { )); invalidVisibilities.add(null); - for(Pair invalidVisibility : invalidVisibilities) { - List> invalidCampaignVisibilities = List.of(); + for(VisibilityCampaignCreateDto invalidVisibility : invalidVisibilities) { + List invalidCampaignVisibilities = List.of(); if(invalidVisibility != null) { invalidCampaignVisibilities = List.of(invalidVisibility); } - Pair campaign = generateCampaign("campId", "campaignLabel", + CampaignCreateDto campaign = generateCampaign("campId", "campaignLabel", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, true, @@ -170,117 +154,80 @@ void testCreateCampaign04() throws Exception { List.of()); mockMvc.perform(post(Constants.API_CAMPAIGN) .contentType(MediaType.APPLICATION_JSON) - .content(campaign.getValue0())) + .content(JsonTestHelper.toJson(campaign))) .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); CampaignCreateDto campaignCreated = campaignService.getCampaignCreated(); assertThat(campaignCreated).isNull(); } - } - private Pair generateCampaign(String campaignId, String campaignLabel, - String email, IdentificationConfiguration identificationConfiguration, - ContactOutcomeConfiguration contactOutcomeConfiguration, - ContactAttemptConfiguration contactAttemptConfiguration, - Boolean communicationRequestConfiguration, - List> visibilities, - List> referents) { - StringBuilder visibilitiesJson = new StringBuilder("\"visibilities\": ["); - for(Pair visibility : visibilities) { - visibilitiesJson.append(visibility.getValue0()); - if(!visibility.getValue0().equals(visibilities.getLast().getValue0())) { - visibilitiesJson.append(", "); - } - } - visibilitiesJson.append("], "); + @Test + @DisplayName("Should return conflict when invalid visibility dates") + void testCreateCampaign06() throws Exception { + campaignService.setShouldThrowVisibilityHasInvalidDatesException(true); + CampaignCreateDto campaign = generateDefaultCampaign(); - StringBuilder referentsJson = new StringBuilder("\"referents\": ["); - for(Pair referent : referents) { - referentsJson.append(referent.getValue0()); - if(!referent.getValue0().equals(referents.getLast().getValue0())) { - referentsJson.append(", "); - } - } - referentsJson.append("], "); + mockMvc.perform(post(Constants.API_CAMPAIGN) + .contentType(MediaType.APPLICATION_JSON) + .content(JsonTestHelper.toJson(campaign))) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.CONFLICT, Constants.API_CAMPAIGN, VisibilityHasInvalidDatesException.MESSAGE)); + } - String campaignTemplate = """ - {""" + visibilitiesJson + referentsJson + """ - "campaign": "%s", - "campaignLabel": "%s", - "email": "%s", - "identificationConfiguration": "%s", - "contactOutcomeConfiguration": "%s", - "contactAttemptConfiguration": "%s", - "communicationRequestConfiguration": %b - } - """; - String campaignJson = String.format(campaignTemplate, campaignId, campaignLabel, email, identificationConfiguration, - contactOutcomeConfiguration, contactAttemptConfiguration, communicationRequestConfiguration); + /** + * Generate a default campaign + * @return a pair of json string and dto object for the campaign + */ + public CampaignCreateDto generateDefaultCampaign() { + VisibilityCampaignCreateDto firstVisibility = generateVisibility("OU-NORTH", 1721683250L, + 1721683251L, + 1721683252L, + 1721683253L, + 1721683254L, + 1721683255L); + VisibilityCampaignCreateDto secondVisibility = generateVisibility("OU-SOUTH", 1721683260L, + 1721683261L, + 1721683262L, + 1721683263L, + 1721683264L, + 1721683265L); + ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); + ReferentDto secondReferent = new ReferentDto("Dupont", "Jean", "1234567890", "PRIMARY"); + return generateCampaign("campId", "An other campaign", + "test.test@sdf.com", IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, + ContactAttemptConfiguration.TEL, + true, + List.of(firstVisibility, secondVisibility), + List.of(firstReferent, secondReferent)); + } + + private CampaignCreateDto generateCampaign( + String campaignId, String campaignLabel, + String email, IdentificationConfiguration identificationConfiguration, + ContactOutcomeConfiguration contactOutcomeConfiguration, + ContactAttemptConfiguration contactAttemptConfiguration, + Boolean communicationRequestConfiguration, + List visibilities, + List referents) { - CampaignCreateDto campaignCreateDto = new CampaignCreateDto(campaignId, + return new CampaignCreateDto(campaignId, campaignLabel, - visibilities.stream() - .map(Pair::getValue1) - .toList(), - referents.stream() - .map(Pair::getValue1) - .toList(), + visibilities, + referents, email, - IdentificationConfiguration.IASCO, - ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, + identificationConfiguration, + contactOutcomeConfiguration, + contactAttemptConfiguration, communicationRequestConfiguration ); - - return Pair.with(campaignJson, campaignCreateDto); - } - - /** - * Generate a pair of visibility json string and visbility create dto - * @param organizationalUnit - * @param managementDate - * @param interviewerDate - * @param identificationDate - * @param collectionStartDate - * @param collectionEndDate - * @param endDate - * @return - */ - private Pair generateVisibility(String organizationalUnit, - Long managementDate, Long interviewerDate, - Long identificationDate, Long collectionStartDate, - Long collectionEndDate, Long endDate) { - String visibilityPlaceHolder = """ - { - "organizationalUnit": "%s", - "managementStartDate": %d, - "interviewerStartDate": %d, - "identificationPhaseStartDate": %d, - "collectionStartDate": %d, - "collectionEndDate": %d, - "endDate": %d - }"""; - String visibilityJson = String.format(String.format(visibilityPlaceHolder, organizationalUnit, - managementDate, interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate)); - - VisibilityCampaignCreateDto visibilityCampaignCreateDto = new VisibilityCampaignCreateDto(managementDate, - interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit, null); - return Pair.with(visibilityJson, visibilityCampaignCreateDto); } - private Pair generateReferent(String firstName, String lastName, String phoneNumber, String role) { - String referentPlaceHolder = """ - { - "firstName": "%s", - "lastName": "%s", - "phoneNumber": "%s", - "role": "%s" - }"""; - String referentJson = String.format(referentPlaceHolder, firstName, lastName, phoneNumber, role); - - ReferentDto referentDto = new ReferentDto(firstName, lastName, phoneNumber, role); - return Pair.with(referentJson, referentDto); + private VisibilityCampaignCreateDto generateVisibility(String organizationalUnit, + Long managementDate, Long interviewerDate, + Long identificationDate, Long collectionStartDate, + Long collectionEndDate, Long endDate) { + return new VisibilityCampaignCreateDto(managementDate, + interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java new file mode 100644 index 00000000..c318a13b --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java @@ -0,0 +1,117 @@ +package fr.insee.pearljam.api.campaign.controller; + +import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; +import fr.insee.pearljam.api.controller.CampaignController; +import fr.insee.pearljam.api.campaign.controller.dummy.CampaignFakeService; +import fr.insee.pearljam.api.campaign.controller.dummy.ReferentFakeService; +import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; +import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.JsonTestHelper; +import fr.insee.pearljam.api.utils.MockMvcTestUtils; +import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.CampaignOnGoingException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class CampaignControllerTest { + + private MockMvc mockMvc; + private CampaignFakeService campaignService; + private final String deletePath = "/api/campaign/campaign-id"; + private final String getPath = "/api/campaign/campaign-id"; + + + @BeforeEach + void setup() { + campaignService = new CampaignFakeService(); + ReferentFakeService referentService = new ReferentFakeService(); + AuthenticationUserFakeService authenticatedUserService = new AuthenticationUserFakeService(AuthenticatedUserTestHelper.AUTH_ADMIN); + CampaignController campaignController = new CampaignController(campaignService, referentService, authenticatedUserService); + mockMvc = MockMvcBuilders + .standaloneSetup(campaignController) + .setControllerAdvice(MockMvcTestUtils.createExceptionControllerAdvice()) + .build(); + } + + @Test + @DisplayName("Should retrieve campaign") + void testGetCampaign01() throws Exception { + CampaignResponseDto campaign = new CampaignResponseDto("campaign-id", "label", null, null, "email", + IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.F2F, true); + campaignService.setCampaignToRetrieve(campaign); + + MvcResult mvcResult = mockMvc.perform(get(getPath) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn(); + + String contentResult = mvcResult.getResponse().getContentAsString(); + String expectedResult = JsonTestHelper.toJson(campaign); + JSONAssert.assertEquals(contentResult, expectedResult, JSONCompareMode.NON_EXTENSIBLE); + } + + @Test + @DisplayName("Should return not found when campaign not found") + void testGetCampaign02() throws Exception { + campaignService.setShouldThrowCampaignNotFoundException(true); + mockMvc.perform(get(getPath) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, getPath, CampaignNotFoundException.MESSAGE)); + } + + @Test + @DisplayName("Should delete campaign") + void testDeleteCampaign01() throws Exception { + mockMvc.perform(delete(deletePath) + .param("force", "true") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + assertThat(campaignService.isDeleteForced()).isTrue(); + assertThat(campaignService.isDeleted()).isTrue(); + } + + @Test + @DisplayName("Should not force delete when force parameter not set") + void testDeleteCampaign02() throws Exception { + mockMvc.perform(delete(deletePath) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + assertThat(campaignService.isDeleteForced()).isFalse(); + assertThat(campaignService.isDeleted()).isTrue(); + } + + @Test + @DisplayName("Should return not found when campaign does not exist") + void testDeleteCampaign03() throws Exception { + campaignService.setShouldThrowCampaignNotFoundException(true); + mockMvc.perform(delete(deletePath) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, deletePath, CampaignNotFoundException.MESSAGE)); + } + + @Test + @DisplayName("Should return conflict when campaign is ongoing") + void testDeleteCampaign04() throws Exception { + campaignService.setShouldThrowCampaignOnGoingException(true); + mockMvc.perform(delete(deletePath) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.CONFLICT, deletePath, CampaignOnGoingException.MESSAGE)); + } +} diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java index e3ac6ade..1bff715a 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java @@ -1,22 +1,22 @@ package fr.insee.pearljam.api.campaign.controller; import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; -import fr.insee.pearljam.api.campaign.dto.input.visibility.VisibilityCampaignUpdateDto; -import fr.insee.pearljam.api.constants.Constants; +import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignUpdateDto; import fr.insee.pearljam.api.controller.CampaignController; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.campaign.controller.dummy.CampaignFakeService; +import fr.insee.pearljam.api.campaign.controller.dummy.ReferentFakeService; import fr.insee.pearljam.api.dto.referent.ReferentDto; -import fr.insee.pearljam.api.service.dummy.CampaignFakeService; -import fr.insee.pearljam.api.service.dummy.ReferentFakeService; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.JsonTestHelper; import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; import fr.insee.pearljam.api.web.exception.ExceptionControllerAdvice; import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; -import org.javatuples.Pair; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -29,6 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; class CampaignControllerUpdateTest { @@ -52,107 +53,82 @@ void setup() { @Test @DisplayName("Should update campaign") void testUpdateCampaign01() throws Exception { - Pair firstVisibility = generateVisibility("OU-NORTH", 1721683250L, - 1721683251L, - 1721683252L, - 1721683253L, - 1721683254L, - 1721683255L); - Pair secondVisibility = generateVisibility("OU-SOUTH", 1721683260L, - 1721683261L, - 1721683262L, - 1721683263L, - 1721683264L, - 1721683265L); - Pair firstReferent = generateReferent("Bob", "Marley", "0123456789", "PRIMARY"); - Pair secondReferent = generateReferent("Dupont", "Jean", "1234567890", "PRIMARY"); - Pair campaign = generateCampaign("An other campaign", - "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, - true, - List.of(firstVisibility, secondVisibility), - List.of(firstReferent, secondReferent)); + CampaignUpdateDto campaign = generateDefaultCampaign(); mockMvc.perform(put(updatePath) .contentType(MediaType.APPLICATION_JSON) - .content(campaign.getValue0())) + .content(JsonTestHelper.toJson(campaign))) .andExpect(status().isOk()); CampaignUpdateDto campaignUpdated = campaignService.getCampaignUpdated(); - assertThat(campaignUpdated).isEqualTo(campaign.getValue1()); + assertThat(campaignUpdated).isEqualTo(campaign); } @Test - @DisplayName("Should return not found when campaign does not exists") + @DisplayName("Should return bad request when invalid campaign label") void testUpdateCampaign02() throws Exception { - campaignService.setShouldThrowCampaignNotFoundException(true); - Pair visibility = generateVisibility("OU-SOUTH", 1721683260L, - 1721683261L, - 1721683262L, - 1721683263L, - 1721683264L, - 1721683265L); - Pair campaign = generateCampaign("An other campaign", + CampaignUpdateDto campaign = generateCampaign(" ", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, true, - List.of(visibility), + List.of(), List.of()); - mockMvc.perform(put(updatePath) .contentType(MediaType.APPLICATION_JSON) - .content(campaign.getValue0())) - .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updatePath, CampaignNotFoundException.MESSAGE)); + .content(JsonTestHelper.toJson(campaign))) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, updatePath, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); + + CampaignUpdateDto campaignUpdated = campaignService.getCampaignUpdated(); + + assertThat(campaignUpdated).isNull(); } @Test - @DisplayName("Should return not found when visibility does not exist") + @DisplayName("Should return bad request when invalid OU in visibility") void testUpdateCampaign03() throws Exception { - campaignService.setShouldThrowVisibilityNotFoundException(true); - Pair visibility = generateVisibility("OU-SOUTH", 1721683260L, - 1721683261L, - 1721683262L, - 1721683263L, - 1721683264L, - 1721683265L); - Pair campaign = generateCampaign("An other campaign", - "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, - true, - List.of(visibility), - List.of()); - - mockMvc.perform(put(updatePath) - .contentType(MediaType.APPLICATION_JSON) - .content(campaign.getValue0())) - .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updatePath, VisibilityNotFoundException.MESSAGE)); + VisibilityCampaignUpdateDto visibility = generateVisibility(" ", 1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L); + testUpdateExceptions(visibility, HttpStatus.BAD_REQUEST, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE); } @Test - @DisplayName("Should return bad request when invalid campaign input") + @DisplayName("Should return not found when campaign does not exist") void testUpdateCampaign04() throws Exception { - Pair campaign = generateCampaign(" ", - "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, - true, - List.of(), - List.of()); - mockMvc.perform(put(updatePath) - .contentType(MediaType.APPLICATION_JSON) - .content(campaign.getValue0())) - .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); + campaignService.setShouldThrowCampaignNotFoundException(true); + testUpdateExceptions(HttpStatus.NOT_FOUND, CampaignNotFoundException.MESSAGE); + } - CampaignUpdateDto campaignUpdated = campaignService.getCampaignUpdated(); + @Test + @DisplayName("Should return not found when visibility does not exist") + void testUpdateCampaign05() throws Exception { + campaignService.setShouldThrowVisibilityNotFoundException(true); + testUpdateExceptions(HttpStatus.NOT_FOUND, VisibilityNotFoundException.MESSAGE); + } - assertThat(campaignUpdated).isNull(); + @Test + @DisplayName("Should return bad request when visibility has no date set") + void testUpdateCampaign06() throws Exception { + VisibilityCampaignUpdateDto visibility = generateVisibility("ou-id", + null, null, + null, null, + null, null); + testUpdateExceptions(visibility, HttpStatus.BAD_REQUEST, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE); } @Test - @DisplayName("Should return bad request when invalid visibility") - void testUpdateCampaign05() throws Exception { - Pair visibility = generateVisibility(" ", 1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L); - Pair campaign = generateCampaign("campaignLabel", + @DisplayName("Should return conflict when invalidating update") + void testUpdateCampaign07() throws Exception { + campaignService.setShouldThrowVisibilityHasInvalidDatesException(true); + testUpdateExceptions(HttpStatus.CONFLICT, VisibilityHasInvalidDatesException.MESSAGE); + } + + private void testUpdateExceptions(HttpStatus httpStatus, + String message) throws Exception { + testUpdateExceptions(generateDefaultVisibility(), httpStatus, message); + } + + private void testUpdateExceptions(VisibilityCampaignUpdateDto visibility, HttpStatus httpStatus, String message) throws Exception { + CampaignUpdateDto campaign = generateCampaign("campaignLabel", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, true, @@ -160,195 +136,63 @@ void testUpdateCampaign05() throws Exception { List.of()); mockMvc.perform(put(updatePath) .contentType(MediaType.APPLICATION_JSON) - .content(campaign.getValue0())) - .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); + .content(JsonTestHelper.toJson(campaign))) + .andDo(print()) + .andExpect(MockMvcTestUtils.apiErrorMatches(httpStatus, updatePath, message)); CampaignUpdateDto campaignUpdated = campaignService.getCampaignUpdated(); assertThat(campaignUpdated).isNull(); } - private Pair generateCampaign(String campaignLabel, - String email, IdentificationConfiguration identificationConfiguration, - ContactOutcomeConfiguration contactOutcomeConfiguration, - ContactAttemptConfiguration contactAttemptConfiguration, - Boolean communicationRequestConfiguration, - List> visibilities, - List> referents) { - StringBuilder visibilitiesJson = new StringBuilder("\"visibilities\": ["); - for(Pair visibility : visibilities) { - visibilitiesJson.append(visibility.getValue0()); - if(!visibility.getValue0().equals(visibilities.getLast().getValue0())) { - visibilitiesJson.append(", "); - } - } - visibilitiesJson.append("], "); - - StringBuilder referentsJson = new StringBuilder("\"referents\": ["); - for(Pair referent : referents) { - referentsJson.append(referent.getValue0()); - if(!referent.getValue0().equals(referents.getLast().getValue0())) { - referentsJson.append(", "); - } - } - referentsJson.append("], "); - - String campaignTemplate = """ - {""" + visibilitiesJson + referentsJson + """ - "campaignLabel": "%s", - "email": "%s", - "identificationConfiguration": "%s", - "contactOutcomeConfiguration": "%s", - "contactAttemptConfiguration": "%s", - "communicationRequestConfiguration": %b - } - """; - String campaignJson = String.format(campaignTemplate, campaignLabel, email, identificationConfiguration, - contactOutcomeConfiguration, contactAttemptConfiguration, communicationRequestConfiguration); + private CampaignUpdateDto generateDefaultCampaign() { + VisibilityCampaignUpdateDto firstVisibility = generateDefaultVisibility(); + VisibilityCampaignUpdateDto secondVisibility = generateVisibility("OU-SOUTH", 1721683260L, + 1721683261L, + 1721683262L, + 1721683263L, + 1721683264L, + 1721683265L); + ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); + ReferentDto secondReferent = new ReferentDto("Dupont", "Jean", "1234567890", "PRIMARY"); + return generateCampaign("An other campaign", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(firstVisibility, secondVisibility), + List.of(firstReferent, secondReferent)); + } - CampaignUpdateDto campaignUpdateDto = new CampaignUpdateDto( + private CampaignUpdateDto generateCampaign(String campaignLabel, + String email, IdentificationConfiguration identificationConfiguration, + ContactOutcomeConfiguration contactOutcomeConfiguration, + ContactAttemptConfiguration contactAttemptConfiguration, + Boolean communicationRequestConfiguration, + List visibilities, + List referents) { + return new CampaignUpdateDto( campaignLabel, - visibilities.stream() - .map(Pair::getValue1) - .toList(), - referents.stream() - .map(Pair::getValue1) - .toList(), + visibilities, + referents, email, - IdentificationConfiguration.IASCO, - ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, + identificationConfiguration, + contactOutcomeConfiguration, + contactAttemptConfiguration, communicationRequestConfiguration ); - return Pair.with(campaignJson, campaignUpdateDto); } - /** - * Generate a pair of visibility json string and visbility create dto - * @param organizationalUnit - * @param managementDate - * @param interviewerDate - * @param identificationDate - * @param collectionStartDate - * @param collectionEndDate - * @param endDate - * @return - */ - private Pair generateVisibility(String organizationalUnit, - Long managementDate, Long interviewerDate, - Long identificationDate, Long collectionStartDate, - Long collectionEndDate, Long endDate) { - String visibilityPlaceHolder = """ - { - "organizationalUnit": "%s", - "managementStartDate": %d, - "interviewerStartDate": %d, - "identificationPhaseStartDate": %d, - "collectionStartDate": %d, - "collectionEndDate": %d, - "endDate": %d - }"""; - String visibilityJson = String.format(String.format(visibilityPlaceHolder, organizationalUnit, - managementDate, interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate)); - - VisibilityCampaignUpdateDto VisibilityCampaignUpdateDto = new VisibilityCampaignUpdateDto(managementDate, - interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit); - return Pair.with(visibilityJson, VisibilityCampaignUpdateDto); + private VisibilityCampaignUpdateDto generateDefaultVisibility() { + return generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L); } - private Pair generateReferent(String firstName, String lastName, String phoneNumber, String role) { - String referentPlaceHolder = """ - { - "firstName": "%s", - "lastName": "%s", - "phoneNumber": "%s", - "role": "%s" - }"""; - String referentJson = String.format(referentPlaceHolder, firstName, lastName, phoneNumber, role); - - ReferentDto referentDto = new ReferentDto(firstName, lastName, phoneNumber, role); - return Pair.with(referentJson, referentDto); + private VisibilityCampaignUpdateDto generateVisibility(String organizationalUnit, + Long managementDate, Long interviewerDate, + Long identificationDate, Long collectionStartDate, + Long collectionEndDate, Long endDate) { + return new VisibilityCampaignUpdateDto(managementDate, + interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit); } - - /* - @Test - @Order(220) - void testPutCampaign() throws Exception { - CampaignUpdateDto campaignUpdateDto = new CampaignUpdateDto( - "Everyday life and health survey 2021", - List.of(visi1, visi2), - List.of(new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY")), - null, - IdentificationConfiguration.IASCO, - ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, - null - ); - - VisibilityCampaignUpdateDto wvcd = generateVisibilityCampaignUpdateDto("OU-WEST", "ZCLOSEDX00", false); - - VisibilityCampaignUpdateDto svcd = generateVisibilityCampaignUpdateDto("OU-SOUTH", "ZCLOSEDX00", false); - - VisibilityCampaignUpdateDto emptyVcd = new VisibilityCampaignUpdateDto(null, null, - null, null, null, - null, "OU-WEST"); - - VisibilityCampaignUpdateDto missingVcd = generateVisibilityCampaignUpdateDto("OU-SOUTH", "ZCLOSEDX00", false); - missingVcd.setOrganizationalUnit("OU-TEAPOT"); - - VisibilityCampaignUpdateDto invalidVcd = generateVisibilityCampaignUpdateDto("OU-WEST", "ZCLOSEDX00", true); - - // path variable campaignId not found in DB - mockMvc.perform(put("/api/campaign/MISSING") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignUpdateDto))) - .andExpect(status().isNotFound()); - - campaignUpdateDto.setCampaignLabel("Everyday life and health survey 2021"); - campaignUpdateDto.setVisibilities(List.of(emptyVcd)); - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignUpdateDto))) - .andExpect(status().isBadRequest()); - - // NOT FOUND VISIBILITY - campaignUpdateDto.setVisibilities(List.of(missingVcd)); - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignUpdateDto))) - .andExpect(status().isNotFound()); - - // CONFLICT due to visibilities - campaignUpdateDto.setVisibilities(List.of(invalidVcd)); - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignUpdateDto))) - .andExpect(status().isConflict()); - - // 200 - campaignUpdateDto.setVisibilities(List.of(wvcd, svcd)); - campaignUpdateDto.setEmail("updated.email@test.com"); - campaignUpdateDto.setContactAttemptConfiguration(ContactAttemptConfiguration.TEL); - campaignUpdateDto.setContactOutcomeConfiguration(ContactOutcomeConfiguration.TEL); - campaignUpdateDto.setIdentificationConfiguration(IdentificationConfiguration.NOIDENT); - - mockMvc.perform(put("/api/campaign/ZCLOSEDX00") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(campaignUpdateDto))) - .andExpect(status().isOk()); - - assertEquals(wvcd.endDate(), - visibilityRepository.findVisibilityByCampaignIdAndOuId("ZCLOSEDX00", "OU-WEST").get().getEndDate()); - CampaignDto updatedCampaign = campaignRepository.findDtoById("ZCLOSEDX00"); - assertEquals("updated.email@test.com", updatedCampaign.getEmail()); - assertEquals(ContactAttemptConfiguration.TEL, updatedCampaign.getContactAttemptConfiguration()); - assertEquals(ContactOutcomeConfiguration.TEL, updatedCampaign.getContactOutcomeConfiguration()); - assertEquals(IdentificationConfiguration.NOIDENT, updatedCampaign.getIdentificationConfiguration()); - }*/ } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java new file mode 100644 index 00000000..e28d7e4f --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java @@ -0,0 +1,152 @@ +package fr.insee.pearljam.api.campaign.controller; + +import fr.insee.pearljam.api.campaign.controller.dummy.VisibilityFakeService; +import fr.insee.pearljam.api.campaign.dto.input.VisibilityUpdateDto; +import fr.insee.pearljam.api.campaign.dto.output.VisibilityCampaignDto; +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.JsonTestHelper; +import fr.insee.pearljam.api.utils.MockMvcTestUtils; +import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; +import fr.insee.pearljam.api.web.exception.ExceptionControllerAdvice; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class VisibilityControllerTest { + + private MockMvc mockMvc; + private VisibilityFakeService visibilityService; + private final String campaignId = "campaign-id"; + private final String organizationalUnitId = "ou-id"; + private String updatePath; + private String findPath; + + @BeforeEach + void setup() { + updatePath = String.format("/api/campaign/%s/organizational-unit/%s/visibility", campaignId, organizationalUnitId); + findPath = String.format("/api/campaign/%s/visibilities", campaignId); + + visibilityService = new VisibilityFakeService(); + AuthenticationUserFakeService authenticatedUserService = new AuthenticationUserFakeService(AuthenticatedUserTestHelper.AUTH_ADMIN); + VisibilityController visibilityController = new VisibilityController(visibilityService, authenticatedUserService); + mockMvc = MockMvcBuilders + .standaloneSetup(visibilityController) + .setControllerAdvice(MockMvcTestUtils.createExceptionControllerAdvice()) + .build(); + } + + @Test + @DisplayName("Should return not found when campaign does not exist") + void testGetVisibilities01() throws Exception { + // Given + List visibilities = List.of( + new Visibility(campaignId, organizationalUnitId, 1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L), + new Visibility(campaignId, "ou-id2", 1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L) + ); + visibilityService.setVisibilitiesToFind(visibilities); + + // When & Then + MvcResult result = mockMvc.perform(get(findPath) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn(); + + List visibilitiesExpected = VisibilityCampaignDto.fromModel(visibilities); + String resultContent = result.getResponse().getContentAsString(); + JSONAssert.assertEquals(resultContent, + JsonTestHelper.toJson(visibilitiesExpected), + JSONCompareMode.STRICT); + } + + @Test + @DisplayName("Should return not found when campaign does not exist") + void testGetVisibilities02() throws Exception { + visibilityService.setShouldThrowCampaignNotFoundException(true); + mockMvc.perform(get(findPath) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, findPath, CampaignNotFoundException.MESSAGE)); + } + + @Test + @DisplayName("Should update visibility") + void testUpdateVisibility01() throws Exception { + VisibilityUpdateDto visibilityToUpdate = generateUpdateVisibility(); + + mockMvc.perform(put(updatePath) + .content(JsonTestHelper.toJson(visibilityToUpdate)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + Visibility visibilityUpdated = visibilityService.getVisibilityUpdated(); + Visibility visibilityExpected = VisibilityUpdateDto.toModel(visibilityToUpdate, campaignId, organizationalUnitId); + + assertThat(visibilityUpdated).isEqualTo(visibilityExpected); + } + + @Test + @DisplayName("Should return not found when visibility does not exist") + void testUpdateVisibility02() throws Exception { + visibilityService.setShouldThrowVisibilityNotFoundException(true); + VisibilityUpdateDto visibilityToUpdate = generateUpdateVisibility(); + mockMvc.perform(put(updatePath) + .content(JsonTestHelper.toJson(visibilityToUpdate)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updatePath, VisibilityNotFoundException.MESSAGE)); + } + + @Test + @DisplayName("Should return conflict when problems with dates") + void testUpdateVisibility03() throws Exception { + visibilityService.setShouldThrowVisibilityMergingException(true); + VisibilityUpdateDto visibilityToUpdate = generateUpdateVisibility(); + mockMvc.perform(put(updatePath) + .content(JsonTestHelper.toJson(visibilityToUpdate)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.CONFLICT, updatePath, VisibilityHasInvalidDatesException.MESSAGE)); + } + + @Test + @DisplayName("Should return bad request when visibility has no date set") + void testUpdateVisibility04() throws Exception { + VisibilityUpdateDto visibility = generateUpdateVisibility( + null, null, + null, null, + null, null); + mockMvc.perform(put(updatePath) + .content(JsonTestHelper.toJson(visibility)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, updatePath, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); + } + + private VisibilityUpdateDto generateUpdateVisibility() { + return generateUpdateVisibility(1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L); + } + + private VisibilityUpdateDto generateUpdateVisibility( + Long managementDate, Long interviewerDate, + Long identificationDate, Long collectionStartDate, + Long collectionEndDate, Long endDate) { + return new VisibilityUpdateDto(managementDate, + interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate); + } +} diff --git a/src/test/java/fr/insee/pearljam/api/service/dummy/CampaignFakeService.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/CampaignFakeService.java similarity index 68% rename from src/test/java/fr/insee/pearljam/api/service/dummy/CampaignFakeService.java rename to src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/CampaignFakeService.java index 40a0a492..510a11d2 100644 --- a/src/test/java/fr/insee/pearljam/api/service/dummy/CampaignFakeService.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/CampaignFakeService.java @@ -1,13 +1,11 @@ -package fr.insee.pearljam.api.service.dummy; +package fr.insee.pearljam.api.campaign.controller.dummy; import java.util.List; import java.util.Optional; import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; -import fr.insee.pearljam.domain.campaign.model.Visibility; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import fr.insee.pearljam.domain.exception.*; import lombok.RequiredArgsConstructor; import fr.insee.pearljam.api.domain.Campaign; @@ -16,7 +14,6 @@ import fr.insee.pearljam.api.dto.count.CountDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; import fr.insee.pearljam.api.service.CampaignService; import lombok.Getter; import lombok.Setter; @@ -27,21 +24,36 @@ public class CampaignFakeService implements CampaignService { @Getter private boolean deleted = false; + @Getter + private boolean deleteForced = false; + @Setter private boolean shouldThrowCampaignAlreadyExistException = false; @Setter private boolean shouldThrowCampaignNotFoundException = false; + @Setter + private boolean shouldThrowCampaignOnGoingException = false; + @Setter private boolean shouldThrowVisibilityNotFoundException = false; + @Setter + private boolean shouldThrowVisibilityHasInvalidDatesException = false; + + @Setter + private boolean shouldThrowOrganizationalUnitNotFoundException = false; + @Getter private CampaignCreateDto campaignCreated = null; @Getter private CampaignUpdateDto campaignUpdated = null; + @Setter + private CampaignResponseDto campaignToRetrieve = null; + @Override public List getListCampaign(String userId) { throw new UnsupportedOperationException("Unimplemented method 'getListCampaign'"); @@ -79,10 +91,16 @@ public CountDto getNbSUNotAttributedByCampaign(String userId, String campaignId) @Override public void createCampaign(CampaignCreateDto campaignDto) - throws CampaignAlreadyExistException { + throws CampaignAlreadyExistException, OrganizationalUnitNotFoundException, VisibilityHasInvalidDatesException { if(shouldThrowCampaignAlreadyExistException) { throw new CampaignAlreadyExistException(); } + if(shouldThrowOrganizationalUnitNotFoundException) { + throw new OrganizationalUnitNotFoundException(); + } + if(shouldThrowVisibilityHasInvalidDatesException) { + throw new VisibilityHasInvalidDatesException(); + } campaignCreated = campaignDto; } @@ -92,18 +110,28 @@ public Optional findById(String campaignId) { } @Override - public void delete(Campaign campaign) { + public void delete(String campaignId, boolean force) throws CampaignNotFoundException, CampaignOnGoingException { + deleteForced = force; + if(shouldThrowCampaignNotFoundException) { + throw new CampaignNotFoundException(); + } + if(shouldThrowCampaignOnGoingException) { + throw new CampaignOnGoingException(); + } deleted = true; } @Override - public void updateCampaign(String id, CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException{ + public void updateCampaign(String id, CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { if(shouldThrowCampaignNotFoundException) { throw new CampaignNotFoundException(); } if(shouldThrowVisibilityNotFoundException) { throw new VisibilityNotFoundException(); } + if(shouldThrowVisibilityHasInvalidDatesException) { + throw new VisibilityHasInvalidDatesException(); + } campaignUpdated = campaign; } @@ -113,17 +141,10 @@ public boolean isCampaignOngoing(String id) { } @Override - public List findAllVisibilitiesByCampaign(String campaignId) { - throw new UnsupportedOperationException("Unimplemented method 'findAllVisiblitiesByCampaign'"); - } - - @Override - public CampaignResponseDto getCampaignDtoById(String id) { - throw new UnsupportedOperationException("Unimplemented method 'getCampaignDtoById'"); - } - - @Override - public void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNotFoundException { - throw new UnsupportedOperationException("Unimplemented method 'updateVisibility'"); + public CampaignResponseDto getCampaignDtoById(String campaignId) throws CampaignNotFoundException{ + if(shouldThrowCampaignNotFoundException) { + throw new CampaignNotFoundException(); + } + return campaignToRetrieve; } } diff --git a/src/test/java/fr/insee/pearljam/api/service/dummy/ReferentFakeService.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/ReferentFakeService.java similarity index 87% rename from src/test/java/fr/insee/pearljam/api/service/dummy/ReferentFakeService.java rename to src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/ReferentFakeService.java index beff73d8..b2f07e25 100644 --- a/src/test/java/fr/insee/pearljam/api/service/dummy/ReferentFakeService.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/ReferentFakeService.java @@ -1,4 +1,4 @@ -package fr.insee.pearljam.api.service.dummy; +package fr.insee.pearljam.api.campaign.controller.dummy; import java.util.List; diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java new file mode 100644 index 00000000..689cab4f --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java @@ -0,0 +1,56 @@ +package fr.insee.pearljam.api.campaign.controller.dummy; + +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import lombok.Getter; +import lombok.Setter; + +import java.util.ArrayList; +import java.util.List; + +public class VisibilityFakeService implements VisibilityService { + + @Setter + private boolean shouldThrowCampaignNotFoundException = false; + + @Setter + private boolean shouldThrowVisibilityNotFoundException = false; + + @Setter + private boolean shouldThrowVisibilityMergingException = false; + + @Getter + private Visibility visibilityUpdated = null; + + @Setter + private List visibilitiesToFind = new ArrayList<>(); + + @Override + public List findVisibilities(String campaignId) throws CampaignNotFoundException { + if(shouldThrowCampaignNotFoundException) { + throw new CampaignNotFoundException(); + } + return visibilitiesToFind; + } + + @Override + public void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNotFoundException, VisibilityHasInvalidDatesException { + if(shouldThrowVisibilityMergingException) { + throw new VisibilityHasInvalidDatesException(); + } + + if(shouldThrowVisibilityNotFoundException) { + throw new VisibilityNotFoundException(); + } + visibilityUpdated = visibilityToUpdate; + } + + @Override + public CampaignVisibility getCampaignVisibility(String idCampaign, List ouIds) { + return null; + } +} diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java new file mode 100644 index 00000000..fe40748e --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java @@ -0,0 +1,41 @@ +package fr.insee.pearljam.api.campaign.dto.input; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class CommunicationTemplateCreateDtoTest { + + @Test + @DisplayName("Should return model objects") + void testToModel() { + // Given + CommunicationTemplateCreateDto dto1 = new CommunicationTemplateCreateDto("msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplateCreateDto dto2 = new CommunicationTemplateCreateDto("msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER); + List dtoList = List.of(dto1, dto2); + + // When + List modelList = CommunicationTemplateCreateDto.toModel(dtoList); + + // Then + assertThat(modelList).hasSize(2); + + CommunicationTemplate firstTemplate = modelList.getFirst(); + assertThat(firstTemplate.id()).isNull(); + assertThat(firstTemplate.messhugahId()).isEqualTo("msg1"); + assertThat(firstTemplate.medium()).isEqualTo(CommunicationMedium.EMAIL); + assertThat(firstTemplate.type()).isEqualTo(CommunicationType.NOTICE); + + CommunicationTemplate lastTemplate = modelList.getLast(); + assertThat(lastTemplate.id()).isNull(); + assertThat(lastTemplate.messhugahId()).isEqualTo("msg2"); + assertThat(lastTemplate.medium()).isEqualTo(CommunicationMedium.MAIL); + assertThat(lastTemplate.type()).isEqualTo(CommunicationType.REMINDER); + } +} diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java new file mode 100644 index 00000000..282228b3 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java @@ -0,0 +1,45 @@ +package fr.insee.pearljam.api.campaign.dto.input; + +import fr.insee.pearljam.domain.campaign.model.Visibility; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class VisibilityCampaignCreateDtoTest { + + @Test + @DisplayName("Should return model object") + void testToModel() { + // Given + Long managementStartDate = 1627845600000L; + Long interviewerStartDate = 1627932000000L; + Long identificationPhaseStartDate = 1628018400000L; + Long collectionStartDate = 1628104800000L; + Long collectionEndDate = 1628191200000L; + Long endDate = 1628277600000L; + String organizationalUnit = "OU1"; + String campaignId = "campaign-id"; + + VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto( + managementStartDate, interviewerStartDate, identificationPhaseStartDate, + collectionStartDate, collectionEndDate, endDate, organizationalUnit); + + // When + Visibility visibility = VisibilityCampaignCreateDto + .toModel(List.of(visibilityDto), campaignId) + .getFirst(); + + // Then + assertThat(visibility.campaignId()).isEqualTo(campaignId); + assertThat(visibility.organizationalUnitId()).isEqualTo(organizationalUnit); + assertThat(visibility.managementStartDate()).isEqualTo(managementStartDate); + assertThat(visibility.interviewerStartDate()).isEqualTo(interviewerStartDate); + assertThat(visibility.identificationPhaseStartDate()).isEqualTo(identificationPhaseStartDate); + assertThat(visibility.collectionStartDate()).isEqualTo(collectionStartDate); + assertThat(visibility.collectionEndDate()).isEqualTo(collectionEndDate); + assertThat(visibility.endDate()).isEqualTo(endDate); + } +} \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java new file mode 100644 index 00000000..87e17cd1 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java @@ -0,0 +1,48 @@ +package fr.insee.pearljam.api.campaign.dto.input; + +import fr.insee.pearljam.domain.campaign.model.Visibility; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class VisibilityCampaignUpdateDtoTest { + + @Test + @DisplayName("Should return model objects") + void testToModel() { + // Given + String campaignId = "campaign1"; + VisibilityCampaignUpdateDto dto1 = new VisibilityCampaignUpdateDto(1L, 2L, 3L, 4L, 5L, 6L, "OU1"); + VisibilityCampaignUpdateDto dto2 = new VisibilityCampaignUpdateDto(11L, 12L, 13L, 14L, 15L, 16L, "OU2"); + List dtoList = List.of(dto1, dto2); + + // When + List modelList = VisibilityCampaignUpdateDto.toModel(dtoList, campaignId); + + // Then + assertThat(modelList).hasSize(2); + + Visibility firstVisibility = modelList.getFirst(); + assertThat(firstVisibility.campaignId()).isEqualTo(campaignId); + assertThat(firstVisibility.organizationalUnitId()).isEqualTo("OU1"); + assertThat(firstVisibility.managementStartDate()).isEqualTo(1L); + assertThat(firstVisibility.interviewerStartDate()).isEqualTo(2L); + assertThat(firstVisibility.identificationPhaseStartDate()).isEqualTo(3L); + assertThat(firstVisibility.collectionStartDate()).isEqualTo(4L); + assertThat(firstVisibility.collectionEndDate()).isEqualTo(5L); + assertThat(firstVisibility.endDate()).isEqualTo(6L); + + Visibility lastVisibility = modelList.getLast(); + assertThat(lastVisibility.campaignId()).isEqualTo(campaignId); + assertThat(lastVisibility.organizationalUnitId()).isEqualTo("OU2"); + assertThat(lastVisibility.managementStartDate()).isEqualTo(11L); + assertThat(lastVisibility.interviewerStartDate()).isEqualTo(12L); + assertThat(lastVisibility.identificationPhaseStartDate()).isEqualTo(13L); + assertThat(lastVisibility.collectionStartDate()).isEqualTo(14L); + assertThat(lastVisibility.collectionEndDate()).isEqualTo(15L); + assertThat(lastVisibility.endDate()).isEqualTo(16L); + } +} diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java new file mode 100644 index 00000000..9675697a --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java @@ -0,0 +1,41 @@ +package fr.insee.pearljam.api.campaign.dto.input; + +import fr.insee.pearljam.domain.campaign.model.Visibility; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class VisibilityUpdateDtoTest { + + @Test + @DisplayName("Should return model object") + void testToModel() { + // Given + Long managementStartDate = 1627845600000L; + Long interviewerStartDate = 1627932000000L; + Long identificationPhaseStartDate = 1628018400000L; + Long collectionStartDate = 1628104800000L; + Long collectionEndDate = 1628191200000L; + Long endDate = 1628277600000L; + String campaignId = "campaign1"; + String ouId = "OU1"; + + VisibilityUpdateDto dto = new VisibilityUpdateDto( + managementStartDate, interviewerStartDate, identificationPhaseStartDate, + collectionStartDate, collectionEndDate, endDate); + + // When + Visibility model = VisibilityUpdateDto.toModel(dto, campaignId, ouId); + + // Then + assertThat(model.campaignId()).isEqualTo(campaignId); + assertThat(model.organizationalUnitId()).isEqualTo(ouId); + assertThat(model.managementStartDate()).isEqualTo(managementStartDate); + assertThat(model.interviewerStartDate()).isEqualTo(interviewerStartDate); + assertThat(model.identificationPhaseStartDate()).isEqualTo(identificationPhaseStartDate); + assertThat(model.collectionStartDate()).isEqualTo(collectionStartDate); + assertThat(model.collectionEndDate()).isEqualTo(collectionEndDate); + assertThat(model.endDate()).isEqualTo(endDate); + } +} diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java new file mode 100644 index 00000000..1c4407d5 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java @@ -0,0 +1,41 @@ +package fr.insee.pearljam.api.campaign.dto.output; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class CommunicationTemplateResponseDtoTest { + + @Test + @DisplayName("Should return dto objects") + void testFromModel() { + // Given + CommunicationTemplate template1 = new CommunicationTemplate(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplate template2 = new CommunicationTemplate(2L, "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER); + List communicationTemplates = List.of(template1, template2); + + // When + List communicationDtos = CommunicationTemplateResponseDto.fromModel(communicationTemplates); + + // Then + assertThat(communicationDtos).hasSize(2); + + CommunicationTemplateResponseDto dto1 = communicationDtos.get(0); + assertThat(dto1.id()).isEqualTo(1L); + assertThat(dto1.messhugahId()).isEqualTo("msg1"); + assertThat(dto1.medium()).isEqualTo(CommunicationMedium.EMAIL); + assertThat(dto1.type()).isEqualTo(CommunicationType.NOTICE); + + CommunicationTemplateResponseDto dto2 = communicationDtos.get(1); + assertThat(dto2.id()).isEqualTo(2L); + assertThat(dto2.messhugahId()).isEqualTo("msg2"); + assertThat(dto2.medium()).isEqualTo(CommunicationMedium.MAIL); + assertThat(dto2.type()).isEqualTo(CommunicationType.REMINDER); + } +} diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java new file mode 100644 index 00000000..3a9f3d8e --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java @@ -0,0 +1,43 @@ +package fr.insee.pearljam.api.campaign.dto.output; + +import fr.insee.pearljam.domain.campaign.model.Visibility; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class VisibilityCampaignDtoTest { + + @Test + @DisplayName("Should return dto objects from models") + void testFromModel() { + // Given + Visibility visibility1 = new Visibility("campaign-id", "OU1", 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + Visibility visibility2 = new Visibility("campaign-id", "OU2", 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + List visibilityList = List.of(visibility1, visibility2); + + // When + List dtoList = VisibilityCampaignDto.fromModel(visibilityList); + + // Then + assertThat(dtoList).hasSize(2); + + assertThat(dtoList.getFirst().organizationalUnit()).isEqualTo("OU1"); + assertThat(dtoList.getFirst().managementStartDate()).isEqualTo(1627845600000L); + assertThat(dtoList.getFirst().interviewerStartDate()).isEqualTo(1627932000000L); + assertThat(dtoList.getFirst().identificationPhaseStartDate()).isEqualTo(1628018400000L); + assertThat(dtoList.getFirst().collectionStartDate()).isEqualTo(1628104800000L); + assertThat(dtoList.getFirst().collectionEndDate()).isEqualTo(1628191200000L); + assertThat(dtoList.getFirst().endDate()).isEqualTo(1628277600000L); + + assertThat(dtoList.getLast().organizationalUnit()).isEqualTo("OU2"); + assertThat(dtoList.getLast().managementStartDate()).isEqualTo(1627845600000L); + assertThat(dtoList.getLast().interviewerStartDate()).isEqualTo(1627932000000L); + assertThat(dtoList.getLast().identificationPhaseStartDate()).isEqualTo(1628018400000L); + assertThat(dtoList.getLast().collectionStartDate()).isEqualTo(1628104800000L); + assertThat(dtoList.getLast().collectionEndDate()).isEqualTo(1628191200000L); + assertThat(dtoList.getLast().endDate()).isEqualTo(1628277600000L); + } +} \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/message/controller/MessageControllerTest.java b/src/test/java/fr/insee/pearljam/api/message/controller/MessageControllerTest.java index 49bc63bb..d363eae7 100644 --- a/src/test/java/fr/insee/pearljam/api/message/controller/MessageControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/message/controller/MessageControllerTest.java @@ -76,7 +76,7 @@ void testMail02() throws Exception { .content(mail)) .andExpectAll(status().isInternalServerError(), MockMvcTestUtils - .apiErrorMatches(HttpStatus.INTERNAL_SERVER_ERROR, mailPath, "") + .apiErrorMatches(HttpStatus.INTERNAL_SERVER_ERROR, mailPath, ExceptionControllerAdvice.ERROR_OCCURRED_LABEL) ); assertThat(mailSender.isMailSent()).isFalse(); diff --git a/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java b/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java index 6f85190e..39b97db4 100644 --- a/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java +++ b/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.List; import com.jayway.jsonpath.JsonPath; +import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.ScriptConstants; import org.json.JSONException; import org.junit.jupiter.api.MethodOrderer; @@ -78,10 +79,11 @@ private ResultMatcher expectValidEndDate() { } private ResultMatcher expectTimestampFromCurrentDate(String expression, int unitToAdd, ChronoUnit chronoUnit) { + return mvcResult -> { String content = mvcResult.getResponse().getContentAsString(); long timestamp = JsonPath.read(content, expression); - LocalDate localDateNow = LocalDate.now(); + LocalDate localDateNow = MockMvcTestUtils.getDate(); Instant instant = Instant.ofEpochMilli(timestamp); LocalDate dateToCheck = LocalDate.ofInstant(instant, ZoneId.systemDefault()); assertEquals(dateToCheck, localDateNow.plus(unitToAdd, chronoUnit)); @@ -93,7 +95,7 @@ private ResultMatcher expectTimestampFromCurrentDate(String expression, int unit /** * Test that the GET endpoint "api/campaigns" * return 404 - * + * * @throws InterruptedException * @throws JSONException * @throws ParseException diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java index b7e5757c..ffbdf216 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java @@ -61,8 +61,7 @@ void updateComment01() throws Exception { @ParameterizedTest @ValueSource(strings = { "{\"value\": \"5\"}", - "{\"type\": \"INTERVIEWER\"}", - "{\"value\": \"5\",\"type\": \"INVALID\"}" + "{\"type\": \"INTERVIEWER\"}" }) @DisplayName("Should return bad request when comment type or value is invalid") void updateComment02(String invalidComment) throws Exception { diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java index ff73c5df..2b0e103b 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java @@ -129,8 +129,7 @@ void updateSurveyUnit03() throws Exception { @ParameterizedTest @ValueSource(strings = { "\"comments\": [{\"value\": \"5\"}]", - "\"comments\": [{\"type\": \"INTERVIEWER\"}]", - "\"comments\": [{\"value\": \"5\",\"type\": \"INVALID\"}]" + "\"comments\": [{\"type\": \"INTERVIEWER\"}]" }) @DisplayName("Should return bad request when comment are invalid") void updateSurveyUnit04(String invalidComment) throws Exception { diff --git a/src/test/java/fr/insee/pearljam/api/utils/JsonTestHelper.java b/src/test/java/fr/insee/pearljam/api/utils/JsonTestHelper.java new file mode 100644 index 00000000..e0dc952c --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/utils/JsonTestHelper.java @@ -0,0 +1,16 @@ +package fr.insee.pearljam.api.utils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; + +public class JsonTestHelper { + + public JsonTestHelper() { + throw new IllegalArgumentException("Utility class"); + } + + public static String toJson(Object object) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + return objectMapper.writeValueAsString(object); + } +} diff --git a/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java b/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java index d7bb8fab..fc5b7c17 100644 --- a/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java +++ b/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java @@ -6,6 +6,10 @@ import org.springframework.http.HttpStatus; import org.springframework.test.web.servlet.ResultMatcher; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; + import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -13,15 +17,20 @@ public class MockMvcTestUtils { public static ResultMatcher apiErrorMatches(HttpStatus errorStatus, String path, String message) { return result -> { - status().is(errorStatus.value()); - jsonPath("$.code").value(errorStatus.value()); - jsonPath("$.path").value(path); - jsonPath("$.message").value(message); - jsonPath("$.timestamp", new StructureDateMatcher()); + status().is(errorStatus.value()).match(result); + jsonPath("$.code").value(errorStatus.value()).match(result); + jsonPath("$.path").value(path).match(result); + jsonPath("$.message").value(message).match(result); + jsonPath("$.timestamp", new StructureDateMatcher()).match(result); }; } public static ExceptionControllerAdvice createExceptionControllerAdvice() { return new ExceptionControllerAdvice(new DefaultErrorAttributes()); } + + public static LocalDate getDate() { + Instant fixedInstant = Instant.ofEpochMilli(1719324512000L); + return LocalDate.ofInstant(fixedInstant, ZoneId.systemDefault()); + } } \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/config/ArchunitApplicationTests.java b/src/test/java/fr/insee/pearljam/config/ArchunitApplicationTests.java index 72043a38..aa6299a8 100644 --- a/src/test/java/fr/insee/pearljam/config/ArchunitApplicationTests.java +++ b/src/test/java/fr/insee/pearljam/config/ArchunitApplicationTests.java @@ -27,6 +27,7 @@ public void setup() { architecture = Architectures.layeredArchitecture() .consideringOnlyDependenciesInLayers() .layer("application").definedBy("..api..") + .layer("old.service").definedBy("..api..service..") .layer("domain.port.userside").definedBy("..domain..port.userside..") .layer("domain.port.serverside").definedBy("..domain..port.serverside..") .layer("domain.model").definedBy("..domain..model..") @@ -60,7 +61,7 @@ void usersidePortsShouldOnlyBeAccessedByControllerAndServices() { @Test void serversidePortsShouldOnlyBeAccessedByDaoAndServices() { architecture - .whereLayer("domain.port.serverside").mayOnlyBeAccessedByLayers("domain.service", "infrastructure.adapter") + .whereLayer("domain.port.serverside").mayOnlyBeAccessedByLayers("domain.service", "infrastructure.adapter", "old.service") .check(importedClasses); } diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java new file mode 100644 index 00000000..b831e533 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java @@ -0,0 +1,51 @@ +package fr.insee.pearljam.domain.campaign.model; + +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class VisibilityTest { + + @Test + @DisplayName("Should merge 2 visibilities and validate the merged one") + void testMergeAndDateValidation() throws VisibilityHasInvalidDatesException { + // Given + Visibility currentVisibility = new Visibility("campaign1", "OU1", + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + + Visibility updateVisibility = new Visibility("campaign1", "OU1", + null, 1627933000000L, null, null, null, 1628277601000L); + + // When + Visibility mergedVisibility = Visibility.merge(currentVisibility, updateVisibility); + + // Then + assertThat(mergedVisibility.campaignId()).isEqualTo("campaign1"); + assertThat(mergedVisibility.organizationalUnitId()).isEqualTo("OU1"); + assertThat(mergedVisibility.managementStartDate()).isEqualTo(1627845600000L); + assertThat(mergedVisibility.interviewerStartDate()).isEqualTo(1627933000000L); + assertThat(mergedVisibility.identificationPhaseStartDate()).isEqualTo(1628018400000L); + assertThat(mergedVisibility.collectionStartDate()).isEqualTo(1628104800000L); + assertThat(mergedVisibility.collectionEndDate()).isEqualTo(1628191200000L); + assertThat(mergedVisibility.endDate()).isEqualTo(1628277601000L); + } + + @Test + @DisplayName("Should throw exception when merged visibilities dates are invalid") + void testMergeThrowsExceptionForInvalidDates() { + // Given + Visibility currentVisibility = new Visibility("campaign1", "OU1", + 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + + Visibility updateVisibility = new Visibility("campaign1", "OU1", + 1427931000000L, 1327932000001L, null, null, null, null); + + // When & Then + assertThatThrownBy(() -> Visibility.merge(currentVisibility, updateVisibility)) + .isInstanceOf(VisibilityHasInvalidDatesException.class) + .hasMessage(VisibilityHasInvalidDatesException.MESSAGE); + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilitytTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilitytTest.java deleted file mode 100644 index 2024819d..00000000 --- a/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilitytTest.java +++ /dev/null @@ -1,4 +0,0 @@ -package fr.insee.pearljam.domain.campaign.model; - -public class VisibilitytTest { -} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java index 9b67c662..f3e2ccd1 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java @@ -1,4 +1,5 @@ package fr.insee.pearljam.domain.campaign.model.communication; -public class CommunicationTemplateTest { +// TODO +class CommunicationTemplateTest { } diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceTest.java new file mode 100644 index 00000000..42b55045 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceTest.java @@ -0,0 +1,5 @@ +package fr.insee.pearljam.domain.campaign.service; + +// TODO +class CampaignServiceTest { +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceTest.java new file mode 100644 index 00000000..edc7dc38 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceTest.java @@ -0,0 +1,5 @@ +package fr.insee.pearljam.domain.campaign.service; + +// TODO +class VisibilityServiceTest { +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java new file mode 100644 index 00000000..f68aea3b --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java @@ -0,0 +1,36 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; + +import java.util.List; +import java.util.Optional; + +public class VisibilityFakeRepository implements VisibilityRepository { + @Override + public CampaignVisibility getCampaignVisibility(String idCampaign, List ouIds) { + throw new UnsupportedOperationException("not implemented yet"); + } + + @Override + public Optional findVisibility(String campaignId, String organizationalUnitId) { + throw new UnsupportedOperationException("not implemented yet"); + } + + @Override + public List findVisibilities(String campaignId) { + throw new UnsupportedOperationException("not implemented yet"); + } + + @Override + public void updateDates(Visibility visibilityToUpdate) throws VisibilityNotFoundException { + throw new UnsupportedOperationException("not implemented yet"); + } + + @Override + public Visibility getVisibilityBySurveyUnitId(String surveyUnitId) { + throw new UnsupportedOperationException("not implemented yet"); + } +} diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java deleted file mode 100644 index 19f32344..00000000 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java +++ /dev/null @@ -1,4 +0,0 @@ -package fr.insee.pearljam.infrastructure.campaign.adapter; - -public class VisibilityDaoAdapter { -} diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java new file mode 100644 index 00000000..bad514b7 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java @@ -0,0 +1,211 @@ +package fr.insee.pearljam.infrastructure.campaign.adapter; + +import fr.insee.pearljam.api.domain.*; +import fr.insee.pearljam.api.repository.CampaignRepository; +import fr.insee.pearljam.api.repository.OrganizationUnitRepository; +import fr.insee.pearljam.api.repository.SurveyUnitRepository; +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDBId; +import fr.insee.pearljam.infrastructure.campaign.jpa.VisibilityJpaRepository; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@SpringBootTest +@ActiveProfiles("auth") +@Transactional +@Slf4j +class VisibilityDaoAdapterTest { + @Autowired + private CampaignRepository campaignRepository; + + @Autowired + private SurveyUnitRepository surveyUnitRepository; + + @Autowired + private OrganizationUnitRepository organizationUnitRepository; + + @Autowired + private VisibilityDaoAdapter visibilityDaoAdapter; + + @Autowired + private VisibilityJpaRepository crudRepository; + + @PersistenceContext + private EntityManager entityManager; + + private Campaign campaign; + private OrganizationUnit organizationUnit; + private OrganizationUnit organizationUnit2; + private VisibilityDB visibilityDB1, visibilityDB2; + + @BeforeEach + void setup() { + campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, + "email@plop.com", true); + + organizationUnit = new OrganizationUnit("OU-SOUTHWEST", "South west", OrganizationUnitType.LOCAL); + organizationUnit2 = new OrganizationUnit("OU-NORTHWEST", "North west", OrganizationUnitType.NATIONAL); + campaignRepository.save(campaign); + organizationUnit = organizationUnitRepository.save(organizationUnit); + organizationUnit2 = organizationUnitRepository.save(organizationUnit2); + visibilityDB1 = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, + 10L, 20L, + 11L, 30L, 12L, 40L); + visibilityDB2 = new VisibilityDB(new VisibilityDBId(organizationUnit2.getId(), campaign.getId()), organizationUnit2, campaign, + 11L, 12L, + 13L, 14L, 15L, 16L); + List visibilities = new ArrayList<>(); + visibilities.add(visibilityDB1); + visibilities.add(visibilityDB2); + campaign.setVisibilities(visibilities); + campaign = campaignRepository.save(campaign); + } + + @Test + @DisplayName("Should update visibility") + void testUpdateDatesVisibilities01() throws VisibilityNotFoundException { + Visibility visibilityToUpdate = new Visibility(campaign.getId(), organizationUnit.getId(), + 21L, 22L, 23L, + 24L, 25L, 26L); + visibilityDaoAdapter.updateDates(visibilityToUpdate); + + Optional campaignOptional = campaignRepository.findById(campaign.getId()); + assertThat(campaignOptional).isPresent(); + campaign = campaignOptional.get(); + List visibilities = campaign.getVisibilities(); + + assertThat(visibilities) + .hasSize(2) + .anySatisfy(visibilityDBUpdated -> assertEquals(visibilityDBUpdated, visibilityToUpdate)) + .anySatisfy(visibilityDBNotUpdated -> assertEquals(visibilityDBNotUpdated, visibilityDB2)); + + Optional visibilityUpdatedOptional = visibilityDaoAdapter.findVisibility(campaign.getId(), organizationUnit.getId()); + assertThat(visibilityUpdatedOptional).isPresent(); + Visibility visibilityUpdated = visibilityUpdatedOptional.get(); + assertThat(visibilityUpdated).isEqualTo(visibilityToUpdate); + } + + @Test + @DisplayName("Should throw exception when visibility doesn't exist") + void testUpdateDatesVisibility02() { + Visibility visibilityToUpdate = new Visibility(campaign.getId(), "invalid-id", + 21L, 22L, 23L, + 24L, 25L, 26L); + + assertThatThrownBy(() -> visibilityDaoAdapter.updateDates(visibilityToUpdate)) + .isInstanceOf(VisibilityNotFoundException.class) + .hasMessage(VisibilityNotFoundException.MESSAGE); + } + + @Test + @DisplayName("Should retrieve campaign visibility") + void testGetCampaignVisibility01() { + // Given + List ouIds = List.of(organizationUnit.getId(), + organizationUnit2.getId()); + + // When + CampaignVisibility campaignVisibility = visibilityDaoAdapter.getCampaignVisibility(campaign.getId(), ouIds); + + // Then + assertThat(campaignVisibility).isNotNull(); + assertThat(campaignVisibility.managementStartDate()).isEqualTo(visibilityDB1.getManagementStartDate()); + assertThat(campaignVisibility.interviewerStartDate()).isEqualTo(visibilityDB2.getInterviewerStartDate()); + assertThat(campaignVisibility.identificationPhaseStartDate()).isEqualTo(visibilityDB1.getIdentificationPhaseStartDate()); + assertThat(campaignVisibility.collectionStartDate()).isEqualTo(visibilityDB2.getCollectionStartDate()); + assertThat(campaignVisibility.collectionEndDate()).isEqualTo(visibilityDB2.getCollectionEndDate()); + assertThat(campaignVisibility.endDate()).isEqualTo(visibilityDB1.getEndDate()); + } + + @Test + @DisplayName("Should find visibility") + void testFindVisibility() { + // When + Optional optionalVisibility = visibilityDaoAdapter.findVisibility(campaign.getId(), organizationUnit.getId()); + + // Then + assertThat(optionalVisibility).isPresent(); + assertEquals(optionalVisibility.get(), visibilityDB1); + } + + @Test + @DisplayName("Should find visibilities") + void testFindVisibilities() { + // When + List visibilities = visibilityDaoAdapter.findVisibilities(campaign.getId()); + + // Then + assertThat(visibilities).hasSize(2); + assertEquals(visibilities.getFirst(), visibilityDB1); + assertEquals(visibilities.getLast(), visibilityDB2); + } + + @Test + @DisplayName("Should retrieve visibility for a survey unit") + void testGetVisibilityBySurveyUnitId() { + // Given + String surveyUnitId = "SU1"; + SurveyUnit surveyUnit = new SurveyUnit(surveyUnitId, true, true, null, + null, campaign, null, organizationUnit, null); + surveyUnitRepository.save(surveyUnit); + + // When + Visibility visibility = visibilityDaoAdapter.getVisibilityBySurveyUnitId(surveyUnitId); + + // Then + assertThat(visibility).isNotNull(); + assertEquals(visibility, visibilityDB1); + } + + private void assertEquals(Visibility visibilityToCheck, VisibilityDB visibilityDBExpected) { + assertThat(visibilityToCheck.campaignId()).isEqualTo(visibilityDBExpected.getCampaign().getId()); + assertThat(visibilityToCheck.organizationalUnitId()).isEqualTo(visibilityDBExpected.getOrganizationUnit().getId()); + assertThat(visibilityToCheck.managementStartDate()).isEqualTo(visibilityDBExpected.getManagementStartDate()); + assertThat(visibilityToCheck.interviewerStartDate()).isEqualTo(visibilityDBExpected.getInterviewerStartDate()); + assertThat(visibilityToCheck.identificationPhaseStartDate()).isEqualTo(visibilityDBExpected.getIdentificationPhaseStartDate()); + assertThat(visibilityToCheck.collectionStartDate()).isEqualTo(visibilityDBExpected.getCollectionStartDate()); + assertThat(visibilityToCheck.collectionEndDate()).isEqualTo(visibilityDBExpected.getCollectionEndDate()); + assertThat(visibilityToCheck.endDate()).isEqualTo(visibilityDBExpected.getEndDate()); + } + + private void assertEquals(VisibilityDB visibilityDBToCheck, Visibility visibilityExpected) { + assertThat(visibilityDBToCheck.getCampaign().getId()).isEqualTo(visibilityExpected.campaignId()); + assertThat(visibilityDBToCheck.getOrganizationUnit().getId()).isEqualTo(visibilityExpected.organizationalUnitId()); + assertThat(visibilityDBToCheck.getManagementStartDate()).isEqualTo(visibilityExpected.managementStartDate()); + assertThat(visibilityDBToCheck.getInterviewerStartDate()).isEqualTo(visibilityExpected.interviewerStartDate()); + assertThat(visibilityDBToCheck.getIdentificationPhaseStartDate()).isEqualTo(visibilityExpected.identificationPhaseStartDate()); + assertThat(visibilityDBToCheck.getCollectionStartDate()).isEqualTo(visibilityExpected.collectionStartDate()); + assertThat(visibilityDBToCheck.getCollectionEndDate()).isEqualTo(visibilityExpected.collectionEndDate()); + assertThat(visibilityDBToCheck.getEndDate()).isEqualTo(visibilityExpected.endDate()); + } + + private void assertEquals(VisibilityDB visibilityDBToCheck, VisibilityDB visibilityExpected) { + assertThat(visibilityDBToCheck.getCampaign().getId()).isEqualTo(visibilityExpected.getCampaign().getId()); + assertThat(visibilityDBToCheck.getOrganizationUnit().getId()).isEqualTo(visibilityExpected.getOrganizationUnit().getId()); + assertThat(visibilityDBToCheck.getManagementStartDate()).isEqualTo(visibilityExpected.getManagementStartDate()); + assertThat(visibilityDBToCheck.getInterviewerStartDate()).isEqualTo(visibilityExpected.getInterviewerStartDate()); + assertThat(visibilityDBToCheck.getIdentificationPhaseStartDate()).isEqualTo(visibilityExpected.getIdentificationPhaseStartDate()); + assertThat(visibilityDBToCheck.getCollectionStartDate()).isEqualTo(visibilityExpected.getCollectionStartDate()); + assertThat(visibilityDBToCheck.getCollectionEndDate()).isEqualTo(visibilityExpected.getCollectionEndDate()); + assertThat(visibilityDBToCheck.getEndDate()).isEqualTo(visibilityExpected.getEndDate()); + } +} diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java new file mode 100644 index 00000000..10244997 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java @@ -0,0 +1,64 @@ +package fr.insee.pearljam.infrastructure.campaign.entity; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class CommunicationTemplateDBTest { + + @Test + @DisplayName("Should create model objects") + void testToModel() { + // Given + CommunicationTemplateDB templateDB1 = new CommunicationTemplateDB(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplateDB templateDB2 = new CommunicationTemplateDB(2L, "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER); + List dbList = List.of(templateDB1, templateDB2); + + // When + List modelList = CommunicationTemplateDB.toModel(dbList); + + // Then + assertThat(modelList).hasSize(2); + + assertThat(modelList.getFirst().id()).isEqualTo(1L); + assertThat(modelList.getFirst().messhugahId()).isEqualTo("msg1"); + assertThat(modelList.getFirst().medium()).isEqualTo(CommunicationMedium.EMAIL); + assertThat(modelList.getFirst().type()).isEqualTo(CommunicationType.NOTICE); + + assertThat(modelList.getLast().id()).isEqualTo(2L); + assertThat(modelList.getLast().messhugahId()).isEqualTo("msg2"); + assertThat(modelList.getLast().medium()).isEqualTo(CommunicationMedium.MAIL); + assertThat(modelList.getLast().type()).isEqualTo(CommunicationType.REMINDER); + } + + @Test + @DisplayName("Should create entity objects") + void testFromModel() { + // Given + CommunicationTemplate template1 = new CommunicationTemplate(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplate template2 = new CommunicationTemplate(2L, "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER); + List modelList = List.of(template1, template2); + + // When + List dbList = CommunicationTemplateDB.fromModel(modelList); + + // Then + assertThat(dbList).hasSize(2); + + assertThat(dbList.getFirst().getId()).isNull(); // ID is null because it's not set in fromModel method + assertThat(dbList.getFirst().getMesshugahId()).isEqualTo("msg1"); + assertThat(dbList.getFirst().getMedium()).isEqualTo(CommunicationMedium.EMAIL); + assertThat(dbList.getFirst().getType()).isEqualTo(CommunicationType.NOTICE); + + assertThat(dbList.getLast().getId()).isNull(); // ID is null because it's not set in fromModel method + assertThat(dbList.getLast().getMesshugahId()).isEqualTo("msg2"); + assertThat(dbList.getLast().getMedium()).isEqualTo(CommunicationMedium.MAIL); + assertThat(dbList.getLast().getType()).isEqualTo(CommunicationType.REMINDER); + } +} diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java index d12110cd..9f662f9d 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java @@ -1,4 +1,192 @@ package fr.insee.pearljam.infrastructure.campaign.entity; -public class VisibilityDBTest { +import fr.insee.pearljam.api.domain.*; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class VisibilityDBTest { + private Campaign campaign; + private OrganizationUnit organizationUnit; + + @BeforeEach + void setup() { + campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, + "email@plop.com", true); + organizationUnit = new OrganizationUnit("OU-SOUTHWEST", "South west", OrganizationUnitType.LOCAL); + } + + @Test + @DisplayName("Should return model object") + void testToModel01() { + VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, + 1L, 2L, + 3L, 4L, 5L, 6L); + + Visibility visibility = VisibilityDB.toModel(visibilityDB); + assertThat(visibility.campaignId()).isEqualTo(visibilityDB.getVisibilityId().getCampaignId()); + assertThat(visibility.organizationalUnitId()).isEqualTo(visibilityDB.getVisibilityId().getOrganizationUnitId()); + assertThat(visibility.managementStartDate()).isEqualTo(visibilityDB.getManagementStartDate()); + assertThat(visibility.interviewerStartDate()).isEqualTo(visibilityDB.getInterviewerStartDate()); + assertThat(visibility.identificationPhaseStartDate()).isEqualTo(visibilityDB.getIdentificationPhaseStartDate()); + assertThat(visibility.collectionStartDate()).isEqualTo(visibilityDB.getCollectionStartDate()); + assertThat(visibility.collectionEndDate()).isEqualTo(visibilityDB.getCollectionEndDate()); + assertThat(visibility.endDate()).isEqualTo(visibilityDB.getEndDate()); + } + + @Test + @DisplayName("Should return entity object") + void testFromModel01() { + Visibility visibility = generateVisibility(1L, 2L, 3L, + 4L, 5L, 6L); + + VisibilityDB visibilityDB = VisibilityDB.fromModel(visibility, campaign, organizationUnit); + assertThat(visibilityDB.getVisibilityId().getCampaignId()).isEqualTo(visibility.campaignId()); + assertThat(visibilityDB.getCampaign()).isEqualTo(campaign); + assertThat(visibilityDB.getOrganizationUnit()).isEqualTo(organizationUnit); + assertThat(visibilityDB.getVisibilityId().getOrganizationUnitId()).isEqualTo(visibility.organizationalUnitId()); + assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibility.managementStartDate()); + assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibility.interviewerStartDate()); + assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibility.identificationPhaseStartDate()); + assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibility.collectionStartDate()); + assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibility.collectionEndDate()); + assertThat(visibilityDB.getEndDate()).isEqualTo(visibility.endDate()); + } + + @Test + @DisplayName("Should update dates from entity object") + void testUpdateDates01() { + VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, + 1L, 2L, + 3L, 4L, 5L, 6L); + Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, + 14L, 15L, 16L); + + visibilityDB.updateDates(visibilityToUpdate); + assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); + assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); + assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); + assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); + assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); + assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + } + + @Test + @DisplayName("Should not update management start date") + void testUpdateDates02() { + VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, + 1L, 2L, + 3L, 4L, 5L, 6L); + Visibility visibilityToUpdate = generateVisibility(null, 12L, 13L, + 14L, 15L, 16L); + + visibilityDB.updateDates(visibilityToUpdate); + assertThat(visibilityDB.getManagementStartDate()).isNotNull(); + assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); + assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); + assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); + assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); + assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + } + + @Test + @DisplayName("Should not update interviewer start date") + void testUpdateDates03() { + VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, + 1L, 2L, + 3L, 4L, 5L, 6L); + Visibility visibilityToUpdate = generateVisibility(11L, null, 13L, + 14L, 15L, 16L); + + visibilityDB.updateDates(visibilityToUpdate); + assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); + assertThat(visibilityDB.getInterviewerStartDate()).isNotNull(); + assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); + assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); + assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); + assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + } + + @Test + @DisplayName("Should not update identification start date") + void testUpdateDates04() { + VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, + 1L, 2L, + 3L, 4L, 5L, 6L); + Visibility visibilityToUpdate = generateVisibility(11L, 12L, null, + 14L, 15L, 16L); + + visibilityDB.updateDates(visibilityToUpdate); + assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); + assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); + assertThat(visibilityDB.getIdentificationPhaseStartDate()).isNotNull(); + assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); + assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); + assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + } + + @Test + @DisplayName("Should not update collection start date") + void testUpdateDates05() { + VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, + 1L, 2L, + 3L, 4L, 5L, 6L); + Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, + null, 15L, 16L); + + visibilityDB.updateDates(visibilityToUpdate); + assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); + assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); + assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); + assertThat(visibilityDB.getCollectionStartDate()).isNotNull(); + assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); + assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + } + + @Test + @DisplayName("Should not update collection end date") + void testUpdateDates06() { + VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, + 1L, 2L, + 3L, 4L, 5L, 6L); + Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, + 14L, null, 16L); + + visibilityDB.updateDates(visibilityToUpdate); + assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); + assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); + assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); + assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); + assertThat(visibilityDB.getCollectionEndDate()).isNotNull(); + assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + } + + @Test + @DisplayName("Should not update end date") + void testUpdateDates07() { + VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, + 1L, 2L, + 3L, 4L, 5L, 6L); + Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, + 14L, 15L, null); + + visibilityDB.updateDates(visibilityToUpdate); + assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); + assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); + assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); + assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); + assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); + assertThat(visibilityDB.getEndDate()).isNotNull(); + } + + private Visibility generateVisibility(Long managementStartDate, Long interviewerStartDate, Long identificationPhaseStartDate, + Long collectionStartDate, Long collectionEndDate, Long endDate) { + return new Visibility(campaign.getId(), organizationUnit.getId(), managementStartDate, interviewerStartDate, + identificationPhaseStartDate, collectionStartDate, collectionEndDate, endDate); + + } } diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java new file mode 100644 index 00000000..35da47c1 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -0,0 +1,319 @@ +package fr.insee.pearljam.integration.campaign; + +import fr.insee.pearljam.api.constants.Constants; +import fr.insee.pearljam.api.domain.*; +import fr.insee.pearljam.api.repository.CampaignRepository; +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.ScriptConstants; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; +import org.json.JSONException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.transaction.annotation.Transactional; + +import java.text.ParseException; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ActiveProfiles("auth") +@AutoConfigureMockMvc +@ContextConfiguration +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Transactional +class CampaignIT { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private CampaignRepository campaignRepository; + + /** + * Test that the GET endpoint "api/campaigns" + * return 404 + * + * @throws InterruptedException + * @throws JSONException + * @throws ParseException + */ + + @Test + @DisplayName("Should retrieve campaign") + void testGetCampaign() throws Exception { + MvcResult mvcResult = mockMvc.perform(get("/api/campaign/SIMPSONS2020X00") + .with(authentication(AuthenticatedUserTestHelper.AUTH_LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn(); + + String contentResult = mvcResult.getResponse().getContentAsString(); + String expectedResult = """ + { + "campaign":"SIMPSONS2020X00", + "campaignLabel":"Survey on the Simpsons tv show 2020", + "visibilities":[ + { + "organizationalUnit":"OU-NORTH", + "managementStartDate":1718966154308, + "interviewerStartDate":1719052554308, + "identificationPhaseStartDate":1719138954308, + "collectionStartDate":1719225354308, + "collectionEndDate":1721903754308, + "endDate":1724582154308 + }, + { + "organizationalUnit":"OU-SOUTH", + "managementStartDate":1718966154308, + "interviewerStartDate":1719052554308, + "identificationPhaseStartDate":1719138954308, + "collectionStartDate":1719225354308, + "collectionEndDate":1721903754308, + "endDate":1724582154308 + } + ], + "referents":[ + { + "firstName":"Gerard", + "lastName":"Menvuca", + "phoneNumber":"0303030303", + "role":"PRIMARY" + } + ], + "email":"first.email@test.com", + "identificationConfiguration":"IASCO", + "contactOutcomeConfiguration":"F2F", + "contactAttemptConfiguration":"F2F" + } + """; + JSONAssert.assertEquals(contentResult, expectedResult, JSONCompareMode.NON_EXTENSIBLE); + } + + + @Test + @DisplayName("Should create campaign") + @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) + void testCreateCampaign() throws Exception { + String campaignId = "NEW-ONE"; + String content = """ + { + "campaign":"NEW-ONE", + "campaignLabel":"An other campaign", + "visibilities":[ + { + "managementStartDate":1721683250, + "interviewerStartDate":1721683251, + "identificationPhaseStartDate":1721683252, + "collectionStartDate":1721683253, + "collectionEndDate":1721683254, + "endDate":1721683255, + "organizationalUnit":"OU-NORTH" + }, + { + "managementStartDate":1721683260, + "interviewerStartDate":1721683261, + "identificationPhaseStartDate":1721683262, + "collectionStartDate":1721683263, + "collectionEndDate":1721683264, + "endDate":1721683265, + "organizationalUnit":"OU-SOUTH" + } + ], + "referents":[ + { + "firstName":"Bob", + "lastName":"Marley", + "phoneNumber":"0123456789", + "role":"PRIMARY" + }, + { + "firstName":"Mylene", + "lastName":"Mikoton", + "phoneNumber":"2345678901", + "role":"PRIMARY" + } + ], + "email": "test.email@plop.com", + "identificationConfiguration":"IASCO", + "contactOutcomeConfiguration":"F2F", + "contactAttemptConfiguration":"F2F", + "communicationRequestConfiguration": null + } + """; + mockMvc.perform(post(Constants.API_CAMPAIGN) + .with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(content)) + .andExpect(status().isOk()); + + Optional campaignOptional = campaignRepository.findById(campaignId); + + assertThat(campaignOptional).isPresent(); + Campaign campaignCreated = campaignOptional.get(); + assertCampaignInfos(campaignCreated, campaignId, "An other campaign", "test.email@plop.com", + false, ContactAttemptConfiguration.F2F, IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F); + assertThat(campaignCreated.getVisibilities()).hasSize(2); + assertThat(campaignCreated.getVisibilities()) + .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", + 1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L)) + .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", + 1721683250L, 1721683251L, 1721683252L, + 1721683253L, 1721683254L, 1721683255L)); + assertThat(campaignCreated.getReferents()).hasSize(2); + assertThat(campaignCreated.getReferents()) + .anySatisfy(referentToCheck -> assertReferent(referentToCheck, campaignId, "PRIMARY", + "Marley", "Bob", "0123456789")) + .anySatisfy(referentToCheck -> assertReferent(referentToCheck, campaignId, "PRIMARY", + "Mikoton", "Mylene", "2345678901")); + } + + @Test + @DisplayName("Should update campaign") + @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) + void testUpdateCampaign() throws Exception { + String campaignId = "SIMPSONS2020X00"; + + String content = """ + { + "campaignLabel":"An other campaign", + "visibilities":[ + { + "managementStartDate":1721683250, + "interviewerStartDate":1721683251, + "identificationPhaseStartDate":1721683252, + "collectionStartDate":1721683253, + "collectionEndDate":1721683254, + "endDate":1721683255, + "organizationalUnit":"OU-NORTH" + }, + { + "managementStartDate":1721683260, + "interviewerStartDate":1721683261, + "identificationPhaseStartDate":1721683262, + "collectionStartDate":1721683263, + "collectionEndDate":1721683264, + "endDate":1721683265, + "organizationalUnit":"OU-SOUTH" + } + ], + "referents":[ + { + "firstName":"Bob", + "lastName":"Marley", + "phoneNumber":"0123456789", + "role":"PRIMARY" + }, + { + "firstName":"Dupont", + "lastName":"Jean", + "phoneNumber":"1234567890", + "role":"PRIMARY" + } + ], + "email":"test.test@sdf.com", + "identificationConfiguration":"NOIDENT", + "contactOutcomeConfiguration":"TEL", + "contactAttemptConfiguration":"F2F", + "communicationRequestConfiguration":true + } + """; + mockMvc.perform(put("/api/campaign/" + campaignId) + .with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(content)) + .andExpect(status().isOk()); + + Optional campaignOptional = campaignRepository.findById(campaignId); + + assertThat(campaignOptional).isPresent(); + Campaign campaignUpdated = campaignOptional.get(); + assertCampaignInfos(campaignUpdated, campaignId, "An other campaign", "test.test@sdf.com", + true, ContactAttemptConfiguration.F2F, IdentificationConfiguration.NOIDENT, + ContactOutcomeConfiguration.TEL); + assertThat(campaignUpdated.getVisibilities()).hasSize(2); + assertThat(campaignUpdated.getVisibilities()) + .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", + 1721683250L, 1721683251L, + 1721683252L, 1721683253L, + 1721683254L, 1721683255L)) + .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", + 1721683250L, 1721683251L, + 1721683252L, 1721683253L, + 1721683254L, 1721683255L)); + + assertThat(campaignUpdated.getReferents()).hasSize(2); + assertThat(campaignUpdated.getReferents()) + .anySatisfy(referentToCheck -> assertReferent(referentToCheck, campaignId, "PRIMARY", + "Marley", "Bob", "0123456789")) + .anySatisfy(referentToCheck -> assertReferent(referentToCheck, campaignId, "PRIMARY", + "Jean", "Dupont", "1234567890")); + } + + @Test + @DisplayName("Should delete campaign") + @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) + void testDeleteCampaign() throws Exception { + String campaignId = "SIMPSONS2020X00"; + mockMvc.perform(delete("/api/campaign/" + campaignId) + .param("force", "true") + .with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + Optional campaignOptional = campaignRepository.findById(campaignId); + assertThat(campaignOptional).isEmpty(); + } + + private void assertVisibility(VisibilityDB visibilityToCheck, String campaignId, String organizationUnitId, + long managementStartDate, long interviewerStartDate, + long identificationPhaseStartDate, long collectionStartDate, + long collectionEndDate, long endDate) { + assertThat(visibilityToCheck.getCampaign().getId()).isEqualTo(campaignId); + assertThat(visibilityToCheck.getOrganizationUnit().getId()).isEqualTo(organizationUnitId); + assertThat(visibilityToCheck.getManagementStartDate()).isEqualTo(managementStartDate); + assertThat(visibilityToCheck.getInterviewerStartDate()).isEqualTo(interviewerStartDate); + assertThat(visibilityToCheck.getIdentificationPhaseStartDate()).isEqualTo(identificationPhaseStartDate); + assertThat(visibilityToCheck.getCollectionStartDate()).isEqualTo(collectionStartDate); + assertThat(visibilityToCheck.getCollectionEndDate()).isEqualTo(collectionEndDate); + assertThat(visibilityToCheck.getEndDate()).isEqualTo(endDate); + } + + private void assertReferent(Referent referentToCheck, String campaignId, String role, String lastName, + String firstName, String phoneNumber) { + assertThat(referentToCheck.getCampaign().getId()).isEqualTo(campaignId); + assertThat(referentToCheck.getId()).isNotNull(); + assertThat(referentToCheck.getRole()).isEqualTo(role); + assertThat(referentToCheck.getLastName()).isEqualTo(lastName); + assertThat(referentToCheck.getFirstName()).isEqualTo(firstName); + assertThat(referentToCheck.getPhoneNumber()).isEqualTo(phoneNumber); + } + + private void assertCampaignInfos(Campaign campaignToCheck, String campaignId, String label, String email, + boolean communicationConfiguration, ContactAttemptConfiguration contactAttemptConfig, + IdentificationConfiguration identificationConfig, ContactOutcomeConfiguration contactOutcomeConfig) { + assertThat(campaignToCheck.getId()).isEqualTo(campaignId); + assertThat(campaignToCheck.getLabel()).isEqualTo(label); + assertThat(campaignToCheck.getEmail()).isEqualTo(email); + assertThat(campaignToCheck.getCommunicationConfiguration()).isEqualTo(communicationConfiguration); + assertThat(campaignToCheck.getContactAttemptConfiguration()).isEqualTo(contactAttemptConfig); + assertThat(campaignToCheck.getIdentificationConfiguration()).isEqualTo(identificationConfig); + assertThat(campaignToCheck.getContactOutcomeConfiguration()).isEqualTo(contactOutcomeConfig); + } +} diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java new file mode 100644 index 00000000..419f1b89 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java @@ -0,0 +1,113 @@ +package fr.insee.pearljam.integration.campaign; + +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.ScriptConstants; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDBId; +import fr.insee.pearljam.infrastructure.campaign.jpa.VisibilityJpaRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.transaction.annotation.Transactional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; + +@ActiveProfiles("auth") +@AutoConfigureMockMvc +@ContextConfiguration +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Transactional +class VisibilityIT { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private VisibilityJpaRepository visibilityRepository; + + @Test + void testGetVisibilities() throws Exception { + MvcResult mvcResult = mockMvc.perform( + get("/api/campaign/SIMPSONS2020X00/visibilities") + .with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andReturn(); + + String resultContent = mvcResult.getResponse().getContentAsString(); + String expectedResult = """ + [ + { + "organizationalUnit":"OU-NORTH", + "managementStartDate":1718966154308, + "interviewerStartDate":1719052554308, + "identificationPhaseStartDate":1719138954308, + "collectionStartDate":1719225354308, + "collectionEndDate":1721903754308, + "endDate":1724582154308 + }, + { + "organizationalUnit":"OU-SOUTH", + "managementStartDate":1718966154308, + "interviewerStartDate":1719052554308, + "identificationPhaseStartDate":1719138954308, + "collectionStartDate":1719225354308, + "collectionEndDate":1721903754308, + "endDate":1724582154308 + } + ] + """; + JSONAssert.assertEquals(resultContent, expectedResult, JSONCompareMode.NON_EXTENSIBLE); + } + + @Test + @DisplayName("Should update visibility") + @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) + void testUpdateVisibility() throws Exception { + String organizationalUnitId = "OU-NORTH"; + String campaignId = "SIMPSONS2020X00"; + String updatePath = String.format("/api/campaign/%s/organizational-unit/%s/visibility", campaignId, organizationalUnitId); + String content = """ + { + "managementStartDate":1718966200000, + "interviewerStartDate":null, + "identificationPhaseStartDate":1719138954308, + "collectionStartDate":null, + "collectionEndDate":1921903754308, + "endDate":2024582154308 + }"""; + + mockMvc.perform(put(updatePath) + .with(authentication(AuthenticatedUserTestHelper.AUTH_LOCAL_USER)) + .content(content) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + VisibilityDB visibilityDBToCheck = visibilityRepository.getReferenceById(new VisibilityDBId(organizationalUnitId, campaignId)); + + assertThat(visibilityDBToCheck.getCampaign().getId()).isEqualTo(campaignId); + assertThat(visibilityDBToCheck.getOrganizationUnit().getId()).isEqualTo(organizationalUnitId); + assertThat(visibilityDBToCheck.getManagementStartDate()).isEqualTo(1718966200000L); + assertThat(visibilityDBToCheck.getInterviewerStartDate()).isEqualTo(1719052554308L); + assertThat(visibilityDBToCheck.getIdentificationPhaseStartDate()).isEqualTo(1719138954308L); + assertThat(visibilityDBToCheck.getCollectionStartDate()).isEqualTo(1719225354308L); + assertThat(visibilityDBToCheck.getCollectionEndDate()).isEqualTo(1921903754308L); + assertThat(visibilityDBToCheck.getEndDate()).isEqualTo(2024582154308L); + } +} diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java new file mode 100644 index 00000000..3dbde567 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -0,0 +1,11 @@ +package fr.insee.pearljam.integration.surveyunit; + +import org.junit.jupiter.api.Test; + +class SurveyUnitIT { + + @Test + void testGetSurveyUnits() { + // TODO + } +} diff --git a/src/test/resources/application-auth.yml b/src/test/resources/application-auth.yml index ab1a5902..a225656e 100644 --- a/src/test/resources/application-auth.yml +++ b/src/test/resources/application-auth.yml @@ -22,9 +22,8 @@ spring: password: password logging: level: - root: DEBUG - liquibase: INFO - + root: INFO + liquibase: WARN feature: oidc: enabled: true From 8ac74ca1111accda2e7340e89e7c426390edc4ee Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 20 Aug 2024 14:42:56 +0200 Subject: [PATCH 04/48] fix: link only campaign to communication template --- .../entity/CommunicationTemplateDB.java | 12 +++-- .../541_add_communication_template.xml | 3 -- .../entity/CommunicationTemplateDBTest.java | 53 ++++++++++++++----- 3 files changed, 48 insertions(+), 20 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java index 853522c1..910bfe3d 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.infrastructure.campaign.entity; +import fr.insee.pearljam.api.domain.Campaign; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; @@ -14,7 +15,7 @@ @Entity(name = "communication_template") @Table(uniqueConstraints = { - @UniqueConstraint(columnNames = {"type", "medium", "campaign_id", "organization_unit_id"}) + @UniqueConstraint(columnNames = {"type", "medium", "campaign_id"}) }) @Getter @Setter @@ -39,6 +40,10 @@ public class CommunicationTemplateDB implements Serializable { @Enumerated(EnumType.STRING) private CommunicationType type; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "campaign_id", insertable = false, updatable = false) + private Campaign campaign; + public static List toModel(List communicationTemplatesDB) { return communicationTemplatesDB.stream() .map(communicationTemplateDB -> new CommunicationTemplate( @@ -49,12 +54,13 @@ public static List toModel(List .toList(); } - public static List fromModel(List communicationTemplates) { + public static List fromModel(List communicationTemplates, Campaign campaign) { return communicationTemplates.stream() .map(communicationTemplate -> new CommunicationTemplateDB(null, communicationTemplate.messhugahId(), communicationTemplate.medium(), - communicationTemplate.type())) + communicationTemplate.type(), + campaign)) .toList(); } } diff --git a/src/main/resources/db/changelog/541_add_communication_template.xml b/src/main/resources/db/changelog/541_add_communication_template.xml index c9dab24f..b90421ad 100644 --- a/src/main/resources/db/changelog/541_add_communication_template.xml +++ b/src/main/resources/db/changelog/541_add_communication_template.xml @@ -17,9 +17,6 @@ - - - diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java index 10244997..9a3df298 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java @@ -1,5 +1,9 @@ package fr.insee.pearljam.infrastructure.campaign.entity; +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; +import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; +import fr.insee.pearljam.api.domain.IdentificationConfiguration; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; @@ -16,15 +20,19 @@ class CommunicationTemplateDBTest { @DisplayName("Should create model objects") void testToModel() { // Given - CommunicationTemplateDB templateDB1 = new CommunicationTemplateDB(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); - CommunicationTemplateDB templateDB2 = new CommunicationTemplateDB(2L, "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER); + Campaign campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, + "email@plop.com", true); + CommunicationTemplateDB templateDB1 = new CommunicationTemplateDB(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE, campaign); + CommunicationTemplateDB templateDB2 = new CommunicationTemplateDB(2L, "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER, campaign); List dbList = List.of(templateDB1, templateDB2); // When List modelList = CommunicationTemplateDB.toModel(dbList); // Then - assertThat(modelList).hasSize(2); + assertThat(modelList) + .hasSize(2); assertThat(modelList.getFirst().id()).isEqualTo(1L); assertThat(modelList.getFirst().messhugahId()).isEqualTo("msg1"); @@ -41,24 +49,41 @@ void testToModel() { @DisplayName("Should create entity objects") void testFromModel() { // Given + Campaign campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, + "email@plop.com", true); CommunicationTemplate template1 = new CommunicationTemplate(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); CommunicationTemplate template2 = new CommunicationTemplate(2L, "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER); List modelList = List.of(template1, template2); // When - List dbList = CommunicationTemplateDB.fromModel(modelList); + List dbList = CommunicationTemplateDB.fromModel(modelList, campaign); // Then - assertThat(dbList).hasSize(2); - - assertThat(dbList.getFirst().getId()).isNull(); // ID is null because it's not set in fromModel method - assertThat(dbList.getFirst().getMesshugahId()).isEqualTo("msg1"); - assertThat(dbList.getFirst().getMedium()).isEqualTo(CommunicationMedium.EMAIL); - assertThat(dbList.getFirst().getType()).isEqualTo(CommunicationType.NOTICE); + assertThat(dbList) + .hasSize(2) + .anySatisfy(templateDB -> { + verifyCommunicationTemplateDB(templateDB, null, + "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE, campaign); + }) + .anySatisfy(templateDB -> { + verifyCommunicationTemplateDB(templateDB, null, + "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER, campaign); + }); + } - assertThat(dbList.getLast().getId()).isNull(); // ID is null because it's not set in fromModel method - assertThat(dbList.getLast().getMesshugahId()).isEqualTo("msg2"); - assertThat(dbList.getLast().getMedium()).isEqualTo(CommunicationMedium.MAIL); - assertThat(dbList.getLast().getType()).isEqualTo(CommunicationType.REMINDER); + private void verifyCommunicationTemplateDB( + CommunicationTemplateDB templateDB, + Long expectedId, + String expectedMesshugahId, + CommunicationMedium expectedMedium, + CommunicationType expectedType, + Campaign expectedCampaign + ) { + assertThat(templateDB.getId()).isEqualTo(expectedId); + assertThat(templateDB.getMesshugahId()).isEqualTo(expectedMesshugahId); + assertThat(templateDB.getMedium()).isEqualTo(expectedMedium); + assertThat(templateDB.getType()).isEqualTo(expectedType); + assertThat(templateDB.getCampaign()).isEqualTo(expectedCampaign); } } From 683c539ec21907b53166c69e198758e9ed93f0bb Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 20 Aug 2024 14:44:55 +0200 Subject: [PATCH 05/48] fix: timestamp to milliseconds in tests --- .../CampaignControllerCreateTest.java | 54 +++++++-------- .../CampaignControllerUpdateTest.java | 29 ++++---- .../controller/VisibilityControllerTest.java | 22 +++--- .../integration/campaign/CampaignIT.java | 68 +++++++++---------- 4 files changed, 88 insertions(+), 85 deletions(-) diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java index 5dd18795..27ff7436 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java @@ -93,8 +93,8 @@ void testCreateCampaign03() throws Exception { @DisplayName("Should return bad request when invalid campaign label") void testCreateCampaign04() throws Exception { - VisibilityCampaignCreateDto visibility = generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L); + VisibilityCampaignCreateDto visibility = generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L); CampaignCreateDto campaign1 = generateCampaign(" ", "An other campaign", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, @@ -124,20 +124,20 @@ void testCreateCampaign04() throws Exception { @DisplayName("Should return bad request when invalid visibility") void testCreateCampaign05() throws Exception { List invalidVisibilities = new ArrayList<>(Arrays.asList( - generateVisibility(" ", 1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L), - generateVisibility("OU-NORTH", null, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L), - generateVisibility("OU-NORTH", 1721683250L, null, 1721683252L, - 1721683253L, 1721683254L, 1721683255L), - generateVisibility("OU-NORTH", 1721683250L, 1721683251L, null, - 1721683253L, 1721683254L, 1721683255L), - generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, - null, 1721683254L, 1721683255L), - generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, - 1721683253L, null, 1721683255L), - generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, null) + generateVisibility(" ", 1721683250000L, 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L), + generateVisibility("OU-NORTH", null, 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L), + generateVisibility("OU-NORTH", 1721683250000L, null, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L), + generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, null, + 1721683253000L, 1721683254000L, 1721683255000L), + generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, + null, 1721683254000L, 1721683255000L), + generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, + 1721683253000L, null, 1721683255000L), + generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, null) )); invalidVisibilities.add(null); @@ -180,18 +180,18 @@ void testCreateCampaign06() throws Exception { * @return a pair of json string and dto object for the campaign */ public CampaignCreateDto generateDefaultCampaign() { - VisibilityCampaignCreateDto firstVisibility = generateVisibility("OU-NORTH", 1721683250L, - 1721683251L, - 1721683252L, - 1721683253L, - 1721683254L, - 1721683255L); + VisibilityCampaignCreateDto firstVisibility = generateVisibility("OU-NORTH", 1721683250000L, + 1721683251000L, + 1721683252000L, + 1721683253000L, + 1721683254000L, + 1721683255000L); VisibilityCampaignCreateDto secondVisibility = generateVisibility("OU-SOUTH", 1721683260L, - 1721683261L, - 1721683262L, - 1721683263L, - 1721683264L, - 1721683265L); + 1721683261000L, + 1721683262000L, + 1721683263000L, + 1721683264000L, + 1721683265000L); ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); ReferentDto secondReferent = new ReferentDto("Dupont", "Jean", "1234567890", "PRIMARY"); return generateCampaign("campId", "An other campaign", diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java index 1bff715a..4ade19ee 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java @@ -86,8 +86,10 @@ void testUpdateCampaign02() throws Exception { @Test @DisplayName("Should return bad request when invalid OU in visibility") void testUpdateCampaign03() throws Exception { - VisibilityCampaignUpdateDto visibility = generateVisibility(" ", 1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L); + VisibilityCampaignUpdateDto visibility = generateVisibility(" ", 1721683250000L, + 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, + 1721683255000L); testUpdateExceptions(visibility, HttpStatus.BAD_REQUEST, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE); } @@ -148,11 +150,11 @@ private void testUpdateExceptions(VisibilityCampaignUpdateDto visibility, HttpSt private CampaignUpdateDto generateDefaultCampaign() { VisibilityCampaignUpdateDto firstVisibility = generateDefaultVisibility(); VisibilityCampaignUpdateDto secondVisibility = generateVisibility("OU-SOUTH", 1721683260L, - 1721683261L, - 1721683262L, - 1721683263L, - 1721683264L, - 1721683265L); + 1721683261000L, + 1721683262000L, + 1721683263000L, + 1721683264000L, + 1721683265000L); ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); ReferentDto secondReferent = new ReferentDto("Dupont", "Jean", "1234567890", "PRIMARY"); return generateCampaign("An other campaign", @@ -184,14 +186,15 @@ private CampaignUpdateDto generateCampaign(String campaignLabel, } private VisibilityCampaignUpdateDto generateDefaultVisibility() { - return generateVisibility("OU-NORTH", 1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L); + return generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, + 1721683252000L, 1721683253000L, + 1721683254000L, 1721683255000L); } - private VisibilityCampaignUpdateDto generateVisibility(String organizationalUnit, - Long managementDate, Long interviewerDate, - Long identificationDate, Long collectionStartDate, - Long collectionEndDate, Long endDate) { + private VisibilityCampaignUpdateDto generateVisibility( + String organizationalUnit, Long managementDate, + Long interviewerDate, Long identificationDate, + Long collectionStartDate, Long collectionEndDate, Long endDate) { return new VisibilityCampaignUpdateDto(managementDate, interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit); } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java index e28d7e4f..3b2cc1e8 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java @@ -35,14 +35,11 @@ class VisibilityControllerTest { private VisibilityFakeService visibilityService; private final String campaignId = "campaign-id"; private final String organizationalUnitId = "ou-id"; - private String updatePath; - private String findPath; + private final String updatePath = String.format("/api/campaign/%s/organizational-unit/%s/visibility", campaignId, organizationalUnitId); + private final String findPath = String.format("/api/campaign/%s/visibilities", campaignId); @BeforeEach void setup() { - updatePath = String.format("/api/campaign/%s/organizational-unit/%s/visibility", campaignId, organizationalUnitId); - findPath = String.format("/api/campaign/%s/visibilities", campaignId); - visibilityService = new VisibilityFakeService(); AuthenticationUserFakeService authenticatedUserService = new AuthenticationUserFakeService(AuthenticatedUserTestHelper.AUTH_ADMIN); VisibilityController visibilityController = new VisibilityController(visibilityService, authenticatedUserService); @@ -57,10 +54,12 @@ void setup() { void testGetVisibilities01() throws Exception { // Given List visibilities = List.of( - new Visibility(campaignId, organizationalUnitId, 1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L), - new Visibility(campaignId, "ou-id2", 1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L) + new Visibility(campaignId, organizationalUnitId, 1721683250000L, + 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L), + new Visibility(campaignId, "ou-id2", 1721683250L, + 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L) ); visibilityService.setVisibilitiesToFind(visibilities); @@ -138,8 +137,9 @@ void testUpdateVisibility04() throws Exception { } private VisibilityUpdateDto generateUpdateVisibility() { - return generateUpdateVisibility(1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L); + return generateUpdateVisibility(1721683250000L, 1721683251000L, + 1721683252000L, 1721683253000L, + 1721683254000L, 1721683255000L); } private VisibilityUpdateDto generateUpdateVisibility( diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index 35da47c1..cc39bd8a 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -116,21 +116,21 @@ void testCreateCampaign() throws Exception { "campaignLabel":"An other campaign", "visibilities":[ { - "managementStartDate":1721683250, - "interviewerStartDate":1721683251, - "identificationPhaseStartDate":1721683252, - "collectionStartDate":1721683253, - "collectionEndDate":1721683254, - "endDate":1721683255, + "managementStartDate":1721683250000, + "interviewerStartDate":1721683251000, + "identificationPhaseStartDate":1721683252000, + "collectionStartDate":1721683253000, + "collectionEndDate":1721683254000, + "endDate":1721683255000, "organizationalUnit":"OU-NORTH" }, { - "managementStartDate":1721683260, - "interviewerStartDate":1721683261, - "identificationPhaseStartDate":1721683262, - "collectionStartDate":1721683263, - "collectionEndDate":1721683264, - "endDate":1721683265, + "managementStartDate":1721683260000, + "interviewerStartDate":1721683261000, + "identificationPhaseStartDate":1721683262000, + "collectionStartDate":1721683263000, + "collectionEndDate":1721683264000, + "endDate":1721683265000, "organizationalUnit":"OU-SOUTH" } ], @@ -171,11 +171,11 @@ void testCreateCampaign() throws Exception { assertThat(campaignCreated.getVisibilities()).hasSize(2); assertThat(campaignCreated.getVisibilities()) .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", - 1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L)) + 1721683250000L, 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L)) .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", - 1721683250L, 1721683251L, 1721683252L, - 1721683253L, 1721683254L, 1721683255L)); + 1721683250000L, 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L)); assertThat(campaignCreated.getReferents()).hasSize(2); assertThat(campaignCreated.getReferents()) .anySatisfy(referentToCheck -> assertReferent(referentToCheck, campaignId, "PRIMARY", @@ -195,21 +195,21 @@ void testUpdateCampaign() throws Exception { "campaignLabel":"An other campaign", "visibilities":[ { - "managementStartDate":1721683250, - "interviewerStartDate":1721683251, - "identificationPhaseStartDate":1721683252, - "collectionStartDate":1721683253, - "collectionEndDate":1721683254, - "endDate":1721683255, + "managementStartDate":1721683250000, + "interviewerStartDate":1721683251000, + "identificationPhaseStartDate":1721683252000, + "collectionStartDate":1721683253000, + "collectionEndDate":1721683254000, + "endDate":1721683255000, "organizationalUnit":"OU-NORTH" }, { - "managementStartDate":1721683260, - "interviewerStartDate":1721683261, - "identificationPhaseStartDate":1721683262, - "collectionStartDate":1721683263, - "collectionEndDate":1721683264, - "endDate":1721683265, + "managementStartDate":1721683260000, + "interviewerStartDate":1721683261000, + "identificationPhaseStartDate":1721683262000, + "collectionStartDate":1721683263000, + "collectionEndDate":1721683264000, + "endDate":1721683265000, "organizationalUnit":"OU-SOUTH" } ], @@ -250,13 +250,13 @@ void testUpdateCampaign() throws Exception { assertThat(campaignUpdated.getVisibilities()).hasSize(2); assertThat(campaignUpdated.getVisibilities()) .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", - 1721683250L, 1721683251L, - 1721683252L, 1721683253L, - 1721683254L, 1721683255L)) + 1721683250000L, 1721683251000L, + 1721683252000L, 1721683253000L, + 1721683254000L, 1721683255000L)) .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", - 1721683250L, 1721683251L, - 1721683252L, 1721683253L, - 1721683254L, 1721683255L)); + 1721683250000L, 1721683251000L, + 1721683252000L, 1721683253000L, + 1721683254000L, 1721683255000L)); assertThat(campaignUpdated.getReferents()).hasSize(2); assertThat(campaignUpdated.getReferents()) From e5964b5a92c7933ffe6952e108e8c3336615c503 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 20 Aug 2024 14:46:00 +0200 Subject: [PATCH 06/48] test: non ordering assert when checking visibility list --- .../domain/surveyunit/model/CommunicationRequestTest.java | 6 +++--- .../campaign/adapter/VisibilityDaoAdapterTest.java | 7 ++++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java index 39ae248d..1db96216 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java @@ -11,17 +11,17 @@ class CommunicationRequestTest { @Test void testCreateCommunicationRequest() { // Given - Long configurationId = 1L; + Long communicationTemplateId = 1L; Long creationDate = System.currentTimeMillis(); CommunicationRequestReason reason = CommunicationRequestReason.REFUSAL; // When - CommunicationRequest communicationRequest = CommunicationRequest.create(configurationId, creationDate, reason); + CommunicationRequest communicationRequest = CommunicationRequest.create(communicationTemplateId, creationDate, reason); // Then assertNotNull(communicationRequest); assertNull(communicationRequest.id()); - assertEquals(configurationId, communicationRequest.communicationTemplateId()); + assertEquals(communicationTemplateId, communicationRequest.communicationTemplateId()); assertEquals(reason, communicationRequest.reason()); assertEquals(CommunicationRequestEmitter.INTERVIEWER, communicationRequest.emitter()); assertNotNull(communicationRequest.status()); diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java index bad514b7..076ecd33 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java @@ -154,9 +154,10 @@ void testFindVisibilities() { List visibilities = visibilityDaoAdapter.findVisibilities(campaign.getId()); // Then - assertThat(visibilities).hasSize(2); - assertEquals(visibilities.getFirst(), visibilityDB1); - assertEquals(visibilities.getLast(), visibilityDB2); + assertThat(visibilities) + .hasSize(2) + .anySatisfy(visibility -> assertEquals(visibility, visibilityDB1)) + .anySatisfy(visibility -> assertEquals(visibility, visibilityDB2)); } @Test From ac57effc189b69fdd9f170dbace79d8c581da7b1 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 20 Aug 2024 14:46:58 +0200 Subject: [PATCH 07/48] fix: explicitly add json property order for visibility dates --- pom.xml | 2 +- .../api/campaign/dto/output/VisibilityCampaignDto.java | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3d43d39f..f3cde3ac 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ fr.insee.pearljam pearljam-back-office - 5.0.4 + 5.1.0 Pearl-Jam-Back-Office Back-office services for PearlJam diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java index 324fe9d9..5fd7f26f 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java @@ -1,10 +1,12 @@ package fr.insee.pearljam.api.campaign.dto.output; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; import fr.insee.pearljam.domain.campaign.model.Visibility; import java.util.List; - +@JsonPropertyOrder({ "organizationalUnit", "managementStartDate", "interviewerStartDate", + "identificationPhaseStartDate", "collectionStartDate", "collectionEndDate", "endDate"}) public record VisibilityCampaignDto( String organizationalUnit, Long managementStartDate, From 9c4f0c75aee2d4718501c651d60040f950ee8917 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 20 Aug 2024 15:04:14 +0200 Subject: [PATCH 08/48] fix: delete useless log --- .../fr/insee/pearljam/api/controller/CampaignController.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java b/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java index 24837315..1cf53d5d 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java @@ -260,8 +260,6 @@ public ResponseEntity isOngoing(@PathVariable(value = "id") String i @Operation(summary = "Get target campaign") @GetMapping(path = Constants.API_CAMPAIGN_ID) public CampaignResponseDto getCampaign(@NotBlank @PathVariable(value = "id") String campaignId) throws CampaignNotFoundException { - String userId = authenticatedUserService.getCurrentUserId(); - log.info("{} try to GET {}", userId, campaignId); return campaignService.getCampaignDtoById(campaignId); } From 1f4b7bdeac2db8364538d3f1bb66a4e0a1b9f9fb Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 21 Aug 2024 17:58:38 +0200 Subject: [PATCH 09/48] test: handle visibility unit tests --- .../input/VisibilityCampaignCreateDto.java | 21 +- .../input/VisibilityCampaignUpdateDto.java | 22 +- .../api/service/impl/CampaignServiceImpl.java | 71 ++-- .../port/serverside/VisibilityRepository.java | 2 +- .../service/VisibilityServiceImpl.java | 3 +- .../controller/VisibilityControllerTest.java | 29 +- .../dummy/VisibilityFakeService.java | 20 +- .../CommunicationTemplateTest.java | 5 - .../service/CampaignServiceImplTest.java | 315 ++++++++++++++++++ .../campaign/service/CampaignServiceTest.java | 5 - .../service/VisibilityServiceImplTest.java | 87 +++++ .../service/VisibilityServiceTest.java | 5 - .../service/dummy/CampaignFakeRepository.java | 248 ++++++++++++++ .../service/dummy/MessageFakeRepository.java | 232 +++++++++++++ .../dummy/OrganizationUnitFakeRepository.java | 209 ++++++++++++ .../service/dummy/PreferenceFakeService.java | 13 + .../dummy/SurveyUnitFakeRepository.java | 263 +++++++++++++++ .../service/dummy/UserFakeRepository.java | 180 ++++++++++ .../service/dummy/UserFakeService.java | 67 ++++ .../service/dummy/UtilsFakeService.java | 35 ++ .../dummy/VisibilityFakeRepository.java | 41 ++- 21 files changed, 1776 insertions(+), 97 deletions(-) delete mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java delete mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceTest.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java delete mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceTest.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CampaignFakeRepository.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/MessageFakeRepository.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/OrganizationUnitFakeRepository.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/PreferenceFakeService.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UserFakeRepository.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UserFakeService.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UtilsFakeService.java diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java index 458f7a60..ea724614 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java @@ -5,6 +5,7 @@ import fr.insee.pearljam.domain.campaign.model.Visibility; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; +import org.springframework.lang.NonNull; import java.util.List; @@ -37,16 +38,20 @@ public record VisibilityCampaignCreateDto( String organizationalUnit ) { + public static Visibility toModel(@NonNull VisibilityCampaignCreateDto visibility, String campaignId) { + return new Visibility(campaignId, + visibility.organizationalUnit(), + visibility.managementStartDate(), + visibility.interviewerStartDate(), + visibility.identificationPhaseStartDate(), + visibility.collectionStartDate(), + visibility.collectionEndDate(), + visibility.endDate()); + } + public static List toModel(List visibilities, String campaignId) { return visibilities.stream() - .map(visibility -> new Visibility(campaignId, - visibility.organizationalUnit(), - visibility.managementStartDate(), - visibility.interviewerStartDate(), - visibility.identificationPhaseStartDate(), - visibility.collectionStartDate(), - visibility.collectionEndDate(), - visibility.endDate())) + .map(visibility -> VisibilityCampaignCreateDto.toModel(visibility, campaignId)) .toList(); } } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java index db6ca486..2698af45 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java @@ -4,6 +4,7 @@ import fr.insee.pearljam.api.web.annotation.AtLeastOneDateValid; import fr.insee.pearljam.domain.campaign.model.Visibility; import jakarta.validation.constraints.NotBlank; +import org.springframework.lang.NonNull; import java.util.List; @@ -29,17 +30,20 @@ public record VisibilityCampaignUpdateDto( @NotBlank String organizationalUnit ) { + public static Visibility toModel(@NonNull VisibilityCampaignUpdateDto visibility, String campaignId) { + return new Visibility(campaignId, + visibility.organizationalUnit(), + visibility.managementStartDate(), + visibility.interviewerStartDate(), + visibility.identificationPhaseStartDate(), + visibility.collectionStartDate(), + visibility.collectionEndDate(), + visibility.endDate()); + } + public static List toModel(List visibilitiesDto, String campaignId) { return visibilitiesDto.stream() - .map(visibilityDto -> new Visibility(campaignId, - visibilityDto.organizationalUnit(), - visibilityDto.managementStartDate(), - visibilityDto.interviewerStartDate(), - visibilityDto.identificationPhaseStartDate(), - visibilityDto.collectionStartDate(), - visibilityDto.collectionEndDate(), - visibilityDto.endDate() - )) + .map(visibilityDto -> toModel(visibilityDto, campaignId)) .toList(); } } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index 65a4a94c..d62e6feb 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -1,50 +1,41 @@ package fr.insee.pearljam.api.service.impl; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; +import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignCreateDto; import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; import fr.insee.pearljam.api.campaign.dto.output.VisibilityCampaignDto; -import fr.insee.pearljam.api.domain.OrganizationUnit; -import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; -import fr.insee.pearljam.domain.exception.*; -import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; -import fr.insee.pearljam.domain.campaign.model.Visibility; -import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.api.domain.OrganizationUnit; import fr.insee.pearljam.api.domain.Referent; import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; import fr.insee.pearljam.api.dto.campaign.CampaignDto; import fr.insee.pearljam.api.dto.count.CountDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; import fr.insee.pearljam.api.dto.referent.ReferentDto; -import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignCreateDto; import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.api.repository.CampaignRepository; -import fr.insee.pearljam.api.repository.MessageRepository; -import fr.insee.pearljam.api.repository.OrganizationUnitRepository; -import fr.insee.pearljam.api.repository.SurveyUnitRepository; -import fr.insee.pearljam.api.repository.UserRepository; -import fr.insee.pearljam.api.service.CampaignService; -import fr.insee.pearljam.api.service.PreferenceService; -import fr.insee.pearljam.api.service.ReferentService; -import fr.insee.pearljam.api.service.SurveyUnitService; -import fr.insee.pearljam.api.service.UserService; -import fr.insee.pearljam.api.service.UtilsService; +import fr.insee.pearljam.api.repository.*; +import fr.insee.pearljam.api.service.*; +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; +import fr.insee.pearljam.domain.exception.*; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; +import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; /** * Implementation of the Service for the Interviewer entity @@ -181,7 +172,9 @@ public void createCampaign(CampaignCreateDto campaignDto) visibilitiesDBToCreate.add(VisibilityDB.fromModel(visibility, campaign, organizationUnit)); } campaign.setVisibilities(visibilitiesDBToCreate); - updateReferents(campaign, campaignDto.referents()); + if(campaignDto.referents() != null) { + updateReferents(campaign, campaignDto.referents()); + } campaignRepository.save(campaign); } @@ -219,9 +212,11 @@ public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate Campaign currentCampaign = campaignRepository.findByIdIgnoreCase(campaignId) .orElseThrow(CampaignNotFoundException::new); - List visibilitiesToUpdate = VisibilityCampaignUpdateDto.toModel(campaignToUpdate.visibilities(), campaignId); - for(Visibility visibilityToUpdate : visibilitiesToUpdate) { - visibilityService.updateVisibility(visibilityToUpdate); + if(campaignToUpdate.visibilities() != null) { + List visibilitiesToUpdate = VisibilityCampaignUpdateDto.toModel(campaignToUpdate.visibilities(), campaignId); + for (Visibility visibilityToUpdate : visibilitiesToUpdate) { + visibilityService.updateVisibility(visibilityToUpdate); + } } currentCampaign.setLabel(campaignToUpdate.campaignLabel()); @@ -230,7 +225,9 @@ public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate } updateConfiguration(currentCampaign, campaignToUpdate); - updateReferents(currentCampaign, campaignToUpdate.referents()); + if(campaignToUpdate.referents() != null) { + updateReferents(currentCampaign, campaignToUpdate.referents()); + } campaignRepository.save(currentCampaign); } @@ -281,7 +278,7 @@ public boolean isCampaignOngoing(String campaignId) throws CampaignNotFoundExcep .anyMatch(visibility -> visibility.endDate() > Instant.now().toEpochMilli()); } - private void updateReferents(Campaign campaign, List referentDtos) { + private void updateReferents(Campaign campaign, @NonNull List referentDtos) { List referents = campaign.getReferents(); referents.clear(); referentDtos.forEach(refDto -> { diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java index cf46ddba..3322764a 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/VisibilityRepository.java @@ -28,7 +28,7 @@ public interface VisibilityRepository { /** * * @param campaignId campaign id - * @return the visibilites of a campaign + * @return the visibilities of a campaign */ List findVisibilities(String campaignId); diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java b/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java index a2d9a33b..47949087 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java @@ -4,7 +4,6 @@ import fr.insee.pearljam.domain.campaign.model.Visibility; import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; import lombok.RequiredArgsConstructor; @@ -23,7 +22,7 @@ public class VisibilityServiceImpl implements VisibilityService { private final VisibilityRepository visibilityRepository; @Override - public List findVisibilities(String campaignId) throws CampaignNotFoundException { + public List findVisibilities(String campaignId) { return visibilityRepository.findVisibilities(campaignId); } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java index 3b2cc1e8..8a2fd84e 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java @@ -53,15 +53,17 @@ void setup() { @DisplayName("Should return not found when campaign does not exist") void testGetVisibilities01() throws Exception { // Given - List visibilities = List.of( + Visibility visibility1 = new Visibility(campaignId, organizationalUnitId, 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L), - new Visibility(campaignId, "ou-id2", 1721683250L, + 1721683253000L, 1721683254000L, 1721683255000L); + Visibility visibility2 = + new Visibility(campaignId, "ou-id2", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L) - ); - visibilityService.setVisibilitiesToFind(visibilities); + 1721683253000L, 1721683254000L, 1721683255000L); + List visibilities = List.of(visibility1, visibility2); + visibilityService.save(visibility1); + visibilityService.save(visibility2); // When & Then MvcResult result = mockMvc.perform(get(findPath) @@ -69,6 +71,7 @@ void testGetVisibilities01() throws Exception { .andExpect(status().isOk()) .andReturn(); + List visibilitiesExpected = VisibilityCampaignDto.fromModel(visibilities); String resultContent = result.getResponse().getContentAsString(); JSONAssert.assertEquals(resultContent, @@ -88,8 +91,16 @@ void testGetVisibilities02() throws Exception { @Test @DisplayName("Should update visibility") void testUpdateVisibility01() throws Exception { + // Given + Visibility visibility = + new Visibility(campaignId, organizationalUnitId, 1721683250000L, + 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L); + visibilityService.save(visibility); + VisibilityUpdateDto visibilityToUpdate = generateUpdateVisibility(); + // When & Then mockMvc.perform(put(updatePath) .content(JsonTestHelper.toJson(visibilityToUpdate)) .contentType(MediaType.APPLICATION_JSON)) @@ -104,12 +115,12 @@ void testUpdateVisibility01() throws Exception { @Test @DisplayName("Should return not found when visibility does not exist") void testUpdateVisibility02() throws Exception { - visibilityService.setShouldThrowVisibilityNotFoundException(true); + String updateInvalidPath = String.format("/api/campaign/%s/organizational-unit/%s/visibility", "campaign-with-no-visibility", organizationalUnitId); VisibilityUpdateDto visibilityToUpdate = generateUpdateVisibility(); - mockMvc.perform(put(updatePath) + mockMvc.perform(put(updateInvalidPath) .content(JsonTestHelper.toJson(visibilityToUpdate)) .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updatePath, VisibilityNotFoundException.MESSAGE)); + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updateInvalidPath, VisibilityNotFoundException.MESSAGE)); } @Test diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java index 689cab4f..170feb11 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java @@ -17,24 +17,20 @@ public class VisibilityFakeService implements VisibilityService { @Setter private boolean shouldThrowCampaignNotFoundException = false; - @Setter - private boolean shouldThrowVisibilityNotFoundException = false; - @Setter private boolean shouldThrowVisibilityMergingException = false; @Getter private Visibility visibilityUpdated = null; - @Setter - private List visibilitiesToFind = new ArrayList<>(); + private List visibilities = new ArrayList<>(); @Override public List findVisibilities(String campaignId) throws CampaignNotFoundException { if(shouldThrowCampaignNotFoundException) { throw new CampaignNotFoundException(); } - return visibilitiesToFind; + return visibilities; } @Override @@ -43,9 +39,11 @@ public void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNot throw new VisibilityHasInvalidDatesException(); } - if(shouldThrowVisibilityNotFoundException) { - throw new VisibilityNotFoundException(); - } + visibilities.stream() + .filter(visibility -> visibility.organizationalUnitId().equals(visibilityToUpdate.organizationalUnitId())) + .filter(visibility -> visibility.campaignId().equals(visibilityToUpdate.campaignId())) + .findFirst() + .orElseThrow(VisibilityNotFoundException::new); visibilityUpdated = visibilityToUpdate; } @@ -53,4 +51,8 @@ public void updateVisibility(Visibility visibilityToUpdate) throws VisibilityNot public CampaignVisibility getCampaignVisibility(String idCampaign, List ouIds) { return null; } + + public void save(Visibility visibility) { + visibilities.add(visibility); + } } diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java deleted file mode 100644 index f3e2ccd1..00000000 --- a/src/test/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplateTest.java +++ /dev/null @@ -1,5 +0,0 @@ -package fr.insee.pearljam.domain.campaign.model.communication; - -// TODO -class CommunicationTemplateTest { -} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java new file mode 100644 index 00000000..60888c75 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java @@ -0,0 +1,315 @@ +package fr.insee.pearljam.domain.campaign.service; + +import fr.insee.pearljam.api.campaign.controller.dummy.ReferentFakeService; +import fr.insee.pearljam.api.campaign.controller.dummy.VisibilityFakeService; +import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; +import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignCreateDto; +import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignUpdateDto; +import fr.insee.pearljam.api.domain.*; +import fr.insee.pearljam.api.service.impl.CampaignServiceImpl; +import fr.insee.pearljam.api.surveyunit.controller.dummy.SurveyUnitFakeService; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.service.dummy.*; +import fr.insee.pearljam.domain.exception.*; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class CampaignServiceImplTest { + + private CampaignFakeRepository campaignRepository; + private VisibilityFakeService visibilityService; + private CampaignServiceImpl campaignService; + private final OrganizationUnit existingOrganizationUnit = new OrganizationUnit("OU-NORTH", "label-ou", OrganizationUnitType.LOCAL); + private final Campaign existingCampaign = new Campaign( + "CAMPAIGN-ID", + "label-campaign", + IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + "email@email.com", + true); + + private final Visibility existingVisibility1 = + new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1721683250000L, + 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L); + private final Visibility existingVisibility2 = + new Visibility(existingCampaign.getId(), "OU2", 1721683250000L, + 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L); + + @BeforeEach + void setup() { + campaignRepository = new CampaignFakeRepository(); + campaignRepository.addCampaign(existingCampaign); + // add referents + existingCampaign.setReferents(new ArrayList<>()); + + visibilityService = new VisibilityFakeService(); + visibilityService.save(existingVisibility1); + visibilityService.save(existingVisibility2); + + List existingCampaignVisibilities = new ArrayList<>(); + existingCampaignVisibilities + .add(VisibilityDB.fromModel(existingVisibility1, existingCampaign, existingOrganizationUnit)); + existingCampaignVisibilities + .add(VisibilityDB.fromModel(existingVisibility2, existingCampaign, existingOrganizationUnit)); + existingCampaign.setVisibilities(existingCampaignVisibilities); + + UserFakeRepository userRepository = new UserFakeRepository(); + SurveyUnitFakeRepository surveyUnitRepository = new SurveyUnitFakeRepository(); + OrganizationUnitFakeRepository organizationUnitRepository = new OrganizationUnitFakeRepository(); + organizationUnitRepository.setOrganizationUnits(List.of(existingOrganizationUnit)); + MessageFakeRepository messageRepository = new MessageFakeRepository(); + UserFakeService userService = new UserFakeService(); + UtilsFakeService utilsService = new UtilsFakeService(); + SurveyUnitFakeService surveyUnitService = new SurveyUnitFakeService(); + PreferenceFakeService preferenceService = new PreferenceFakeService(); + ReferentFakeService referentService = new ReferentFakeService(); + + campaignService = new CampaignServiceImpl( + campaignRepository, userRepository, surveyUnitRepository, organizationUnitRepository, messageRepository, + userService, utilsService, surveyUnitService, preferenceService, referentService, visibilityService); + } + + // TODO : handle referent + @Test + @DisplayName("Should create a new campaign successfully") + void shouldCreateNewCampaign() throws CampaignAlreadyExistException, OrganizationalUnitNotFoundException, VisibilityHasInvalidDatesException { + String campaignId = "CAMP1"; + VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto(1721683250000L, 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId()); + CampaignCreateDto campaignCreateDto = new CampaignCreateDto( + campaignId, + "Campaign 1", + List.of(visibilityDto), + null, + null, + IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true + ); + + campaignService.createCampaign(campaignCreateDto); + + Campaign createdCampaign = campaignRepository.getSavedCampaign(); + assertThat(createdCampaign.getId()).isEqualTo(campaignCreateDto.campaign()); + assertThat(createdCampaign.getLabel()).isEqualTo(campaignCreateDto.campaignLabel()); + assertThat(createdCampaign.getEmail()).isEqualTo(campaignCreateDto.email()); + assertThat(createdCampaign.getCommunicationConfiguration()).isEqualTo(campaignCreateDto.communicationRequestConfiguration()); + assertThat(createdCampaign.getIdentificationConfiguration()).isEqualTo(campaignCreateDto.identificationConfiguration()); + assertThat(createdCampaign.getContactAttemptConfiguration()).isEqualTo(campaignCreateDto.contactAttemptConfiguration()); + assertThat(createdCampaign.getContactOutcomeConfiguration()).isEqualTo(campaignCreateDto.contactOutcomeConfiguration()); + assertThat(createdCampaign.getVisibilities()) + .hasSize(1) + .satisfiesExactly(visibility -> assertThat(VisibilityDB.toModel(visibility)).isEqualTo(VisibilityCampaignCreateDto.toModel(visibilityDto, campaignId))); + } + + @Test + @DisplayName("Should throw CampaignAlreadyExistException when creating a campaign that already exists") + void shouldThrowCampaignAlreadyExistExceptionWhenCreatingExistingCampaign() { + String campaignId = existingCampaign.getId(); + VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto(1721683250000L, 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId()); + CampaignCreateDto existingCampaignDto = new CampaignCreateDto( + campaignId, + "Existing campaign", + List.of(visibilityDto), + null, + null, + IdentificationConfiguration.IASCO, + ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true + ); + + assertThatThrownBy(() -> campaignService.createCampaign(existingCampaignDto)) + .isInstanceOf(CampaignAlreadyExistException.class) + .hasMessage(CampaignAlreadyExistException.MESSAGE); + } + + // TODO : handle referents + @Test + @DisplayName("Should update an existing campaign successfully") + void shouldUpdateExistingCampaign() throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { + String campaignId = existingCampaign.getId(); + + // Given + VisibilityCampaignUpdateDto visibilityDto = new VisibilityCampaignUpdateDto(1721683250000L, 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId()); + + CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", + List.of(visibilityDto), + null, "emailUpdated@email.com", + IdentificationConfiguration.NOIDENT, + ContactOutcomeConfiguration.TEL, + ContactAttemptConfiguration.TEL, + false); + + // When + campaignService.updateCampaign(campaignId, updateDto); + + // Then + Campaign updatedCampaign = campaignRepository.getSavedCampaign(); + assertThat(updatedCampaign.getId()).isEqualTo(campaignId); + assertThat(updatedCampaign.getLabel()).isEqualTo(updateDto.campaignLabel()); + assertThat(updatedCampaign.getEmail()).isEqualTo(updateDto.email()); + assertThat(updatedCampaign.getCommunicationConfiguration()).isEqualTo(updateDto.communicationRequestConfiguration()); + assertThat(updatedCampaign.getIdentificationConfiguration()).isEqualTo(updateDto.identificationConfiguration()); + assertThat(updatedCampaign.getContactAttemptConfiguration()).isEqualTo(updateDto.contactAttemptConfiguration()); + assertThat(updatedCampaign.getContactOutcomeConfiguration()).isEqualTo(updateDto.contactOutcomeConfiguration()); + assertThat(updatedCampaign.getVisibilities()) + .hasSize(2) + .anySatisfy(visibilityDB -> + assertThat(VisibilityDB.toModel(visibilityDB)).isEqualTo(VisibilityCampaignUpdateDto.toModel(visibilityDto, campaignId))) + .anySatisfy(visibilityDB -> + assertThat(VisibilityDB.toModel(visibilityDB)).isEqualTo(existingVisibility1)); + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + @NullSource + @DisplayName("Should not update email if empty") + void shouldNotUpdateEmailIfNull(String emailToUpdate) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { + String campaignId = existingCampaign.getId(); + + // Given + + CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", + null, + null, emailToUpdate, + IdentificationConfiguration.NOIDENT, + ContactOutcomeConfiguration.TEL, + ContactAttemptConfiguration.TEL, + false); + + // When + campaignService.updateCampaign(campaignId, updateDto); + + // Then + Campaign updatedCampaign = campaignRepository.getSavedCampaign(); + assertThat(updatedCampaign.getEmail()).isEqualTo(existingCampaign.getEmail()); + } + + @Test + @DisplayName("Should not update visibilities if null") + void shouldNotUpdateVisibilitiesIfNull() throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { + String campaignId = existingCampaign.getId(); + + // Given + + CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", + null, + null, null, + IdentificationConfiguration.NOIDENT, + ContactOutcomeConfiguration.TEL, + ContactAttemptConfiguration.TEL, + false); + + // When + campaignService.updateCampaign(campaignId, updateDto); + + // Then + Campaign updatedCampaign = campaignRepository.getSavedCampaign(); + assertThat(updatedCampaign.getVisibilities()).hasSize(2); + } + + // TODO : handle referents + @Test + @DisplayName("Should not update referents if null") + void shouldNotUpdateReferentsIfNull() throws VisibilityHasInvalidDatesException, CampaignNotFoundException, VisibilityNotFoundException { + String campaignId = existingCampaign.getId(); + + // Given + CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", + null, + null, null, + IdentificationConfiguration.NOIDENT, + ContactOutcomeConfiguration.TEL, + ContactAttemptConfiguration.TEL, + false); + + // When + campaignService.updateCampaign(campaignId, updateDto); + + // Then + Campaign updatedCampaign = campaignRepository.getSavedCampaign(); + assertThat(updatedCampaign.getReferents()).containsAll(existingCampaign.getReferents()); + } + + @Test + @DisplayName("Should throw CampaignNotFoundException when updating a non-existent campaign") + void shouldThrowCampaignNotFoundExceptionWhenUpdatingNonExistentCampaign() { + String campaignId = "invalid-campaign"; + + CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", + null, + null, null, + IdentificationConfiguration.NOIDENT, + ContactOutcomeConfiguration.TEL, + ContactAttemptConfiguration.TEL, + false); + + assertThatThrownBy(() -> campaignService.updateCampaign(campaignId, updateDto)) + .isInstanceOf(CampaignNotFoundException.class); + } + + @Test + @DisplayName("Should return true if the campaign is ongoing") + void shouldReturnTrueIfCampaignIsOngoing() throws CampaignNotFoundException { + Visibility ongoingVisibility = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), + 1627845600000L, 1627932000000L, + 1628018400000L, 1628104800000L, + 1628191200000L, Instant.now().plusSeconds(10000).toEpochMilli()); + Visibility closedVisibility = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), + 1627845600000L, 1627932000000L, + 1628018400000L, 1628104800000L, + 1628191200000L, Instant.now().toEpochMilli()); + + visibilityService.save(ongoingVisibility); + visibilityService.save(closedVisibility); + boolean isOngoing = campaignService.isCampaignOngoing(existingCampaign.getId()); + + assertThat(isOngoing).isTrue(); + } + + @Test + @DisplayName("Should return false if the campaign is not ongoing") + void shouldReturnFalseIfCampaignIsNotOngoing() throws CampaignNotFoundException { + Visibility closedVisibility1 = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), + 1627845600000L, 1627932000000L, + 1628018400000L, 1628104800000L, + 1628191200000L, Instant.now().minusSeconds(3600).toEpochMilli()); + Visibility closedVisibility2 = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), + 1627845600000L, 1627932000000L, + 1628018400000L, 1628104800000L, + 1628191200000L, Instant.now().toEpochMilli()); + + visibilityService.save(closedVisibility1); + visibilityService.save(closedVisibility2); + boolean isOngoing = campaignService.isCampaignOngoing(existingCampaign.getId()); + assertThat(isOngoing).isFalse(); + } + + @Test + @DisplayName("Should throw CampaignNotFoundException when checking if a non-existent campaign is ongoing") + void shouldThrowCampaignNotFoundExceptionWhenCheckingIfNonExistentCampaignIsOngoing() { + String campaignId = "notfound-campaign"; + assertThatThrownBy(() -> campaignService.isCampaignOngoing(campaignId)) + .isInstanceOf(CampaignNotFoundException.class); + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceTest.java deleted file mode 100644 index 42b55045..00000000 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceTest.java +++ /dev/null @@ -1,5 +0,0 @@ -package fr.insee.pearljam.domain.campaign.service; - -// TODO -class CampaignServiceTest { -} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java new file mode 100644 index 00000000..0d3b4327 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java @@ -0,0 +1,87 @@ +package fr.insee.pearljam.domain.campaign.service; + +import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.service.dummy.VisibilityFakeRepository; +import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class VisibilityServiceImplTest { + + private VisibilityFakeRepository visibilityRepository; + private VisibilityServiceImpl visibilityService; + private Visibility visibility1, visibility2, visibility3; + + @BeforeEach + void setUp() { + visibilityRepository = new VisibilityFakeRepository(); + visibilityService = new VisibilityServiceImpl(visibilityRepository); + visibility1 = new Visibility("campaign1", "OU1", + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + visibility2 = new Visibility("campaign2", "OU2", + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + visibility3 = new Visibility("campaign1", "OU2", + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + visibilityRepository.save(visibility1); + visibilityRepository.save(visibility2); + visibilityRepository.save(visibility3); + } + + @Test + @DisplayName("Should return visibilities") + void shouldReturnVisibilitiesForValidCampaignId() { + List visibilities = visibilityService.findVisibilities(visibility1.campaignId()); + + assertThat(visibilities) + .isNotEmpty() + .hasSize(2) + .containsExactlyInAnyOrder(visibility1, visibility3); + } + + @Test + @DisplayName("Should update visibility with valid data") + void shouldUpdateVisibilityWithValidData() throws VisibilityNotFoundException, VisibilityHasInvalidDatesException { + Visibility visibilityToUpdate = new Visibility(visibility1.campaignId(), visibility1.organizationalUnitId(), + 1627845600001L, 1627932000001L, 1628018400001L, 1628104800001L, 1628191200001L, 1628277600001L); + + visibilityService.updateVisibility(visibilityToUpdate); + + Optional mergedVisibility = visibilityRepository + .findVisibility(visibilityToUpdate.campaignId(), visibilityToUpdate.organizationalUnitId()); + assertThat(mergedVisibility) + .contains(visibilityToUpdate); + } + + @Test + @DisplayName("Should throw VisibilityNotFoundException if visibility to update does not exist") + void shouldThrowVisibilityNotFoundExceptionIfVisibilityToUpdateDoesNotExist() { + Visibility visibilityToUpdate = new Visibility("invalid-campaign", "invalid-ou", + 1627845600000L, 1627932000000L, 1628018400000L, + 1628104800000L, 1628191200000L, 1628277600000L); + + assertThatThrownBy(() -> visibilityService.updateVisibility(visibilityToUpdate)) + .isInstanceOf(VisibilityNotFoundException.class) + .hasMessage(VisibilityNotFoundException.MESSAGE); + } + + @Test + @DisplayName("Should return CampaignVisibility for valid campaignId and organizational unit ids") + void shouldReturnCampaignVisibilityForValidCampaignIdAndOuIds() { + String campaignId = "campaign1"; + List ouIds = List.of("ou1", "ou2"); + + CampaignVisibility campaignVisibility = visibilityService.getCampaignVisibility(campaignId, ouIds); + + assertThat(campaignVisibility) + .isEqualTo(VisibilityFakeRepository.CAMPAIGN_VISIBILITY); + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceTest.java deleted file mode 100644 index edc7dc38..00000000 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceTest.java +++ /dev/null @@ -1,5 +0,0 @@ -package fr.insee.pearljam.domain.campaign.service; - -// TODO -class VisibilityServiceTest { -} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CampaignFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CampaignFakeRepository.java new file mode 100644 index 00000000..3bf84ad4 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CampaignFakeRepository.java @@ -0,0 +1,248 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.api.dto.campaign.CampaignDto; +import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; +import fr.insee.pearljam.api.dto.message.VerifyNameResponseDto; +import fr.insee.pearljam.api.repository.CampaignRepository; +import lombok.Getter; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.repository.query.FluentQuery; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +public class CampaignFakeRepository implements CampaignRepository { + + private List campaigns = new ArrayList<>(); + + @Getter + private Campaign savedCampaign; + + @Override + public Optional findByIdIgnoreCase(String id) { + return campaigns.stream() + .filter(campaign -> campaign.getId().equalsIgnoreCase(id)) + .findFirst(); + } + + @Override + public List findAllIds() { + return List.of(); + } + + @Override + public List findAllIdsVisible(List ouIds, Long date) { + return List.of(); + } + + @Override + public List findAllCampaignIdsByOuIds(List ouIds) { + return List.of(); + } + + @Override + public List findIdsByOuId(String ouId) { + return List.of(); + } + + @Override + public CampaignDto findDtoById(String id) { + return null; + } + + @Override + public CampaignDto findDtoBySurveyUnitId(String id) { + return null; + } + + @Override + public List findAllDto() { + return List.of(); + } + + @Override + public List checkCampaignPreferences(String userId, String campaignId) { + return List.of(); + } + + @Override + public List findInterviewersDtoByCampaignIdAndOrganisationUnitId(String id, String organizationUnitId) { + return List.of(); + } + + @Override + public List findAllOrganistionUnitIdByCampaignId(String campaignId) { + return List.of(); + } + + @Override + public List findMatchingCampaigns(String text, List ouIds, Long date, Pageable pageable) { + return List.of(); + } + + @Override + public void flush() { + + } + + @Override + public S saveAndFlush(S entity) { + return null; + } + + @Override + public List saveAllAndFlush(Iterable entities) { + return List.of(); + } + + @Override + public void deleteAllInBatch(Iterable entities) { + + } + + @Override + public void deleteAllByIdInBatch(Iterable strings) { + + } + + @Override + public void deleteAllInBatch() { + + } + + @Override + public Campaign getOne(String s) { + return null; + } + + @Override + public Campaign getById(String s) { + return null; + } + + @Override + public Campaign getReferenceById(String s) { + return null; + } + + @Override + public Optional findOne(Example example) { + return Optional.empty(); + } + + @Override + public List findAll(Example example) { + return List.of(); + } + + @Override + public List findAll(Example example, Sort sort) { + return List.of(); + } + + @Override + public Page findAll(Example example, Pageable pageable) { + return null; + } + + @Override + public long count(Example example) { + return 0; + } + + @Override + public boolean exists(Example example) { + return false; + } + + @Override + public R findBy(Example example, Function, R> queryFunction) { + return null; + } + + @Override + public S save(S campaign) { + savedCampaign = campaign; + Optional campaignToUpdate = findById(campaign.getId()); + if(campaignToUpdate.isPresent()) { + campaigns.remove(campaignToUpdate); + } + campaigns.add(campaign); + return campaign; + } + + @Override + public List saveAll(Iterable entities) { + return List.of(); + } + + @Override + public Optional findById(String id) { + return findByIdIgnoreCase(id); + } + + @Override + public boolean existsById(String s) { + return false; + } + + @Override + public List findAll() { + return List.of(); + } + + @Override + public List findAllById(Iterable strings) { + return List.of(); + } + + @Override + public long count() { + return 0; + } + + @Override + public void deleteById(String s) { + + } + + @Override + public void delete(Campaign entity) { + + } + + @Override + public void deleteAllById(Iterable strings) { + + } + + @Override + public void deleteAll(Iterable entities) { + + } + + @Override + public void deleteAll() { + + } + + @Override + public List findAll(Sort sort) { + return List.of(); + } + + @Override + public Page findAll(Pageable pageable) { + return null; + } + + public void addCampaign(Campaign campaign) { + campaigns.add(campaign); + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/MessageFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/MessageFakeRepository.java new file mode 100644 index 00000000..220c4db3 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/MessageFakeRepository.java @@ -0,0 +1,232 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.api.domain.Message; +import fr.insee.pearljam.api.dto.message.MessageDto; +import fr.insee.pearljam.api.dto.message.VerifyNameResponseDto; +import fr.insee.pearljam.api.repository.MessageRepository; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.repository.query.FluentQuery; + +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +public class MessageFakeRepository implements MessageRepository { + @Override + public Optional findById(Long id) { + return Optional.empty(); + } + + @Override + public boolean existsById(Long aLong) { + return false; + } + + @Override + public List getMessageIdsByInterviewer(String interviewerId) { + return List.of(); + } + + @Override + public List getMessageIdsByOrganizationUnit(List organizationUnitIds) { + return List.of(); + } + + @Override + public List getAllOrganizationMessagesIds(List organizationUnitIds) { + return List.of(); + } + + @Override + public List findMessagesDtoByIds(List ids) { + return List.of(); + } + + @Override + public List getMessageStatus(Long messageId, String interviewerId) { + return List.of(); + } + + @Override + public List getCampaignRecipients(Long messageId) { + return List.of(); + } + + @Override + public List getOuRecipients(Long messageId) { + return List.of(); + } + + @Override + public void deleteCampaignMessageRecipientByCampaignId(String campaignId) { + + } + + @Override + public void deleteCampaignMessageRecipientByMessageId(Long messageId) { + + } + + @Override + public void deleteOUMessageRecipientByOrganizationUnitId(String organizationUnitId) { + + } + + @Override + public void deleteOUMessageRecipientByMessageId(Long messageId) { + + } + + @Override + public void deleteMessageStatusByMessageId(Long messageId) { + + } + + @Override + public List findAllBySenderId(String userId) { + return List.of(); + } + + @Override + public void flush() { + + } + + @Override + public S saveAndFlush(S entity) { + return null; + } + + @Override + public List saveAllAndFlush(Iterable entities) { + return List.of(); + } + + @Override + public void deleteAllInBatch(Iterable entities) { + + } + + @Override + public void deleteAllByIdInBatch(Iterable longs) { + + } + + @Override + public void deleteAllInBatch() { + + } + + @Override + public Message getOne(Long aLong) { + return null; + } + + @Override + public Message getById(Long aLong) { + return null; + } + + @Override + public Message getReferenceById(Long aLong) { + return null; + } + + @Override + public Optional findOne(Example example) { + return Optional.empty(); + } + + @Override + public List findAll(Example example) { + return List.of(); + } + + @Override + public List findAll(Example example, Sort sort) { + return List.of(); + } + + @Override + public Page findAll(Example example, Pageable pageable) { + return null; + } + + @Override + public long count(Example example) { + return 0; + } + + @Override + public boolean exists(Example example) { + return false; + } + + @Override + public R findBy(Example example, Function, R> queryFunction) { + return null; + } + + @Override + public S save(S entity) { + return null; + } + + @Override + public List saveAll(Iterable entities) { + return List.of(); + } + + @Override + public List findAll() { + return List.of(); + } + + @Override + public List findAllById(Iterable longs) { + return List.of(); + } + + @Override + public long count() { + return 0; + } + + @Override + public void deleteById(Long aLong) { + + } + + @Override + public void delete(Message entity) { + + } + + @Override + public void deleteAllById(Iterable longs) { + + } + + @Override + public void deleteAll(Iterable entities) { + + } + + @Override + public void deleteAll() { + + } + + @Override + public List findAll(Sort sort) { + return List.of(); + } + + @Override + public Page findAll(Pageable pageable) { + return null; + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/OrganizationUnitFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/OrganizationUnitFakeRepository.java new file mode 100644 index 00000000..2f118d95 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/OrganizationUnitFakeRepository.java @@ -0,0 +1,209 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.api.domain.OrganizationUnit; +import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; +import fr.insee.pearljam.api.repository.OrganizationUnitRepository; +import lombok.Setter; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.repository.query.FluentQuery; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +public class OrganizationUnitFakeRepository implements OrganizationUnitRepository { + + @Setter + private List organizationUnits = new ArrayList<>(); + + @Override + public Optional findByIdIgnoreCase(String ouId) { + return Optional.empty(); + } + + @Override + public Optional findDtoByIdIgnoreCase(String ouId) { + return Optional.empty(); + } + + @Override + public List findChildrenId(String orgUnitId) { + return List.of(); + } + + @Override + public List findNationalOUs() { + return List.of(); + } + + @Override + public List findChildren(String orgUnitId) { + return List.of(); + } + + @Override + public List findAllId() { + return List.of(); + } + + @Override + public String findLabel(String orgUnitId) { + return ""; + } + + @Override + public void flush() { + + } + + @Override + public S saveAndFlush(S entity) { + return null; + } + + @Override + public List saveAllAndFlush(Iterable entities) { + return List.of(); + } + + @Override + public void deleteAllInBatch(Iterable entities) { + + } + + @Override + public void deleteAllByIdInBatch(Iterable strings) { + + } + + @Override + public void deleteAllInBatch() { + + } + + @Override + public OrganizationUnit getOne(String s) { + return null; + } + + @Override + public OrganizationUnit getById(String s) { + return null; + } + + @Override + public OrganizationUnit getReferenceById(String s) { + return null; + } + + @Override + public Optional findOne(Example example) { + return Optional.empty(); + } + + @Override + public List findAll(Example example) { + return List.of(); + } + + @Override + public List findAll(Example example, Sort sort) { + return List.of(); + } + + @Override + public Page findAll(Example example, Pageable pageable) { + return null; + } + + @Override + public long count(Example example) { + return 0; + } + + @Override + public boolean exists(Example example) { + return false; + } + + @Override + public R findBy(Example example, Function, R> queryFunction) { + return null; + } + + @Override + public S save(S entity) { + return null; + } + + @Override + public List saveAll(Iterable entities) { + return List.of(); + } + + @Override + public Optional findById(String ouId) { + return organizationUnits.stream() + .filter(organizationUnit -> organizationUnit.getId().equals(ouId)) + .findFirst(); + } + + @Override + public boolean existsById(String s) { + return false; + } + + @Override + public List findAll() { + return List.of(); + } + + @Override + public List findAllById(Iterable strings) { + return List.of(); + } + + @Override + public long count() { + return 0; + } + + @Override + public void deleteById(String s) { + + } + + @Override + public void delete(OrganizationUnit entity) { + + } + + @Override + public void deleteAllById(Iterable strings) { + + } + + @Override + public void deleteAll(Iterable entities) { + + } + + @Override + public void deleteAll() { + + } + + @Override + public List findAll(Sort sort) { + return List.of(); + } + + @Override + public Page findAll(Pageable pageable) { + return null; + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/PreferenceFakeService.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/PreferenceFakeService.java new file mode 100644 index 00000000..77184e30 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/PreferenceFakeService.java @@ -0,0 +1,13 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.api.service.PreferenceService; +import org.springframework.http.HttpStatus; + +import java.util.List; + +public class PreferenceFakeService implements PreferenceService { + @Override + public HttpStatus setPreferences(List listPreference, String userId) { + return null; + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java new file mode 100644 index 00000000..8ca23f2b --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java @@ -0,0 +1,263 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.api.repository.SurveyUnitRepository; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.repository.query.FluentQuery; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; + +public class SurveyUnitFakeRepository implements SurveyUnitRepository { + @Override + public List findIdsByInterviewerId(String idInterviewer) { + return List.of(); + } + + @Override + public Integer findCountUeINATBRByInterviewerIdAndCampaignId(String idInterviewer, String idCampaign, String idSurveyUnit) { + return 0; + } + + @Override + public Optional findByIdAndInterviewerIdIgnoreCase(String id, String userId) { + return Optional.empty(); + } + + @Override + public List findAllIds() { + return List.of(); + } + + @Override + public List findIdsByCampaignIdAndOu(String id, String ouId) { + return List.of(); + } + + @Override + public List findAllSurveyUnitsInProcessingPhase(Long date) { + return List.of(); + } + + @Override + public List findSurveyUnitIdsOfOrganizationUnitsInProcessingPhaseByIdentificationConfiguration(Long date, List lstOuId, IdentificationConfiguration config) { + return List.of(); + } + + @Override + public List findClosableNoIdentSurveyUnitId(List ids) { + return List.of(); + } + + @Override + public List findClosableIascoSurveyUnitId(List ids) { + return List.of(); + } + + @Override + public Set findByCampaignIdAndOrganizationUnitIdIn(String id, List lstOuId) { + return Set.of(); + } + + @Override + public List findByInterviewerIdIgnoreCase(String id) { + return List.of(); + } + + @Override + public List getCampaignStats(String campaignId, List organizationalUnitIds) { + return List.of(); + } + + @Override + public List findByOrganizationUnitIdIn(List lstOuId) { + return List.of(); + } + + @Override + public void updateAllinterviewersToNull() { + + } + + @Override + public List findByIdInOrganizationalUnit(String id, List organizationalUnitIds) { + return List.of(); + } + + @Override + public Collection findByCampaignId(String id) { + return List.of(); + } + + @Override + public List findAllIdsByCampaignId(String campaignId) { + return List.of(); + } + + @Override + public List findAllIdsByInterviewerId(String interviewerId) { + return List.of(); + } + + @Override + public void setInterviewer(List surveyUnitIds, String interviewerId) { + + } + + @Override + public void flush() { + + } + + @Override + public S saveAndFlush(S entity) { + return null; + } + + @Override + public List saveAllAndFlush(Iterable entities) { + return List.of(); + } + + @Override + public void deleteAllInBatch(Iterable entities) { + + } + + @Override + public void deleteAllByIdInBatch(Iterable strings) { + + } + + @Override + public void deleteAllInBatch() { + + } + + @Override + public SurveyUnit getOne(String s) { + return null; + } + + @Override + public SurveyUnit getById(String s) { + return null; + } + + @Override + public SurveyUnit getReferenceById(String s) { + return null; + } + + @Override + public Optional findOne(Example example) { + return Optional.empty(); + } + + @Override + public List findAll(Example example) { + return List.of(); + } + + @Override + public List findAll(Example example, Sort sort) { + return List.of(); + } + + @Override + public Page findAll(Example example, Pageable pageable) { + return null; + } + + @Override + public long count(Example example) { + return 0; + } + + @Override + public boolean exists(Example example) { + return false; + } + + @Override + public R findBy(Example example, Function, R> queryFunction) { + return null; + } + + @Override + public S save(S entity) { + return null; + } + + @Override + public List saveAll(Iterable entities) { + return List.of(); + } + + @Override + public Optional findById(String s) { + return Optional.empty(); + } + + @Override + public boolean existsById(String s) { + return false; + } + + @Override + public List findAll() { + return List.of(); + } + + @Override + public List findAllById(Iterable strings) { + return List.of(); + } + + @Override + public long count() { + return 0; + } + + @Override + public void deleteById(String s) { + + } + + @Override + public void delete(SurveyUnit entity) { + + } + + @Override + public void deleteAllById(Iterable strings) { + + } + + @Override + public void deleteAll(Iterable entities) { + + } + + @Override + public void deleteAll() { + + } + + @Override + public List findAll(Sort sort) { + return List.of(); + } + + @Override + public Page findAll(Pageable pageable) { + return null; + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UserFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UserFakeRepository.java new file mode 100644 index 00000000..2185c6c6 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UserFakeRepository.java @@ -0,0 +1,180 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.api.domain.User; +import fr.insee.pearljam.api.repository.UserRepository; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.repository.query.FluentQuery; + +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +public class UserFakeRepository implements UserRepository { + @Override + public Optional findByIdIgnoreCase(String userId) { + return Optional.empty(); + } + + @Override + public boolean existsByIdIgnoreCase(String userId) { + return false; + } + + @Override + public List findAllByOrganizationUnitId(String id) { + return List.of(); + } + + @Override + public void flush() { + + } + + @Override + public S saveAndFlush(S entity) { + return null; + } + + @Override + public List saveAllAndFlush(Iterable entities) { + return List.of(); + } + + @Override + public void deleteAllInBatch(Iterable entities) { + + } + + @Override + public void deleteAllByIdInBatch(Iterable strings) { + + } + + @Override + public void deleteAllInBatch() { + + } + + @Override + public User getOne(String s) { + return null; + } + + @Override + public User getById(String s) { + return null; + } + + @Override + public User getReferenceById(String s) { + return null; + } + + @Override + public Optional findOne(Example example) { + return Optional.empty(); + } + + @Override + public List findAll(Example example) { + return List.of(); + } + + @Override + public List findAll(Example example, Sort sort) { + return List.of(); + } + + @Override + public Page findAll(Example example, Pageable pageable) { + return null; + } + + @Override + public long count(Example example) { + return 0; + } + + @Override + public boolean exists(Example example) { + return false; + } + + @Override + public R findBy(Example example, Function, R> queryFunction) { + return null; + } + + @Override + public S save(S entity) { + return null; + } + + @Override + public List saveAll(Iterable entities) { + return List.of(); + } + + @Override + public Optional findById(String s) { + return Optional.empty(); + } + + @Override + public boolean existsById(String s) { + return false; + } + + @Override + public List findAll() { + return List.of(); + } + + @Override + public List findAllById(Iterable strings) { + return List.of(); + } + + @Override + public long count() { + return 0; + } + + @Override + public void deleteById(String s) { + + } + + @Override + public void delete(User entity) { + + } + + @Override + public void deleteAllById(Iterable strings) { + + } + + @Override + public void deleteAll(Iterable entities) { + + } + + @Override + public void deleteAll() { + + } + + @Override + public List findAll(Sort sort) { + return List.of(); + } + + @Override + public Page findAll(Pageable pageable) { + return null; + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UserFakeService.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UserFakeService.java new file mode 100644 index 00000000..81cb5836 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UserFakeService.java @@ -0,0 +1,67 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.api.domain.OrganizationUnit; +import fr.insee.pearljam.api.domain.Response; +import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; +import fr.insee.pearljam.api.dto.user.UserContextDto; +import fr.insee.pearljam.api.dto.user.UserDto; +import fr.insee.pearljam.api.exception.NoOrganizationUnitException; +import fr.insee.pearljam.api.exception.NotFoundException; +import fr.insee.pearljam.api.exception.UserAlreadyExistsException; +import fr.insee.pearljam.api.service.UserService; +import org.springframework.http.HttpStatus; + +import java.util.List; +import java.util.Optional; + +public class UserFakeService implements UserService { + @Override + public Optional getUser(String userId) { + return Optional.empty(); + } + + @Override + public boolean userIsPresent(String userId) { + return false; + } + + @Override + public void getOrganizationUnits(List organizationUnits, OrganizationUnit currentOu, boolean saveAllLevels) { + + } + + @Override + public List getUserOUs(String userId, boolean saveAllLevels) { + return List.of(); + } + + @Override + public boolean isUserAssocitedToCampaign(String campaignId, String userId) { + return false; + } + + @Override + public Response createUsersByOrganizationUnit(List users, String organisationUnitId) throws UserAlreadyExistsException, NoOrganizationUnitException { + return null; + } + + @Override + public HttpStatus delete(String id) { + return null; + } + + @Override + public boolean checkValidity(UserDto user) { + return false; + } + + @Override + public UserDto createUser(UserDto user) throws NotFoundException { + return null; + } + + @Override + public UserDto updateUser(UserDto user) throws NotFoundException { + return null; + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UtilsFakeService.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UtilsFakeService.java new file mode 100644 index 00000000..d7991bf7 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/UtilsFakeService.java @@ -0,0 +1,35 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitOkNokDto; +import fr.insee.pearljam.api.service.UtilsService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.http.ResponseEntity; + +import java.util.List; + +public class UtilsFakeService implements UtilsService { + @Override + public boolean checkUserCampaignOUConstraints(String userId, String campaignId) { + return false; + } + + @Override + public List getRelatedOrganizationUnits(String userId) { + return List.of(); + } + + @Override + public boolean isDevProfile() { + return false; + } + + @Override + public boolean isTestProfile() { + return false; + } + + @Override + public ResponseEntity getQuestionnairesStateFromDataCollection(HttpServletRequest request, List id) { + return null; + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java index f68aea3b..621f84a6 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java @@ -5,32 +5,59 @@ import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; -import java.util.List; -import java.util.Optional; +import java.util.*; public class VisibilityFakeRepository implements VisibilityRepository { + + private final List visibilities = new ArrayList<>(); + public static final CampaignVisibility CAMPAIGN_VISIBILITY = + new CampaignVisibility(1627845600000L, 1627932000000L, + 1628018400000L, 1628104800000L, + 1628191200000L, 1628277600000L); + @Override public CampaignVisibility getCampaignVisibility(String idCampaign, List ouIds) { - throw new UnsupportedOperationException("not implemented yet"); + return CAMPAIGN_VISIBILITY; } @Override public Optional findVisibility(String campaignId, String organizationalUnitId) { - throw new UnsupportedOperationException("not implemented yet"); + return visibilities.stream() + .filter(visibility -> visibility.campaignId().equals(campaignId)) + .filter((visibility -> visibility.organizationalUnitId().equals(organizationalUnitId))) + .findFirst(); } @Override public List findVisibilities(String campaignId) { - throw new UnsupportedOperationException("not implemented yet"); + return visibilities.stream() + .filter(visibility -> visibility.campaignId().equals(campaignId)) + .toList(); } @Override public void updateDates(Visibility visibilityToUpdate) throws VisibilityNotFoundException { - throw new UnsupportedOperationException("not implemented yet"); + String campaignId = visibilityToUpdate.campaignId(); + String organizationalUnitId = visibilityToUpdate.organizationalUnitId(); + + Visibility visibilityToRemove = findVisibility(campaignId, organizationalUnitId) + .orElseThrow(VisibilityNotFoundException::new); + + visibilities.remove(visibilityToRemove); + visibilities.add(visibilityToUpdate); } @Override public Visibility getVisibilityBySurveyUnitId(String surveyUnitId) { - throw new UnsupportedOperationException("not implemented yet"); + return new Visibility("campaign1", "OU1", + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + } + + // Additional methods for testing purposes + + public void save(Visibility visibility) { + if(!visibilities.contains(visibility)) { + visibilities.add(visibility); + } } } From 254661874325ef2526259c6d26d70a6a2cfb6384 Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 21 Aug 2024 18:22:58 +0200 Subject: [PATCH 10/48] test: handle visibility integration tests --- .../resources/db/dataset/reinit-test-data.sql | 10 +- .../api/authKeycloak/TestAuthKeyCloak.java | 157 +++++------------- .../insee/pearljam/api/noAuth/TestNoAuth.java | 110 ++---------- .../integration/campaign/CampaignIT.java | 24 ++- .../integration/campaign/VisibilityIT.java | 26 +-- .../integration/surveyunit/SurveyUnitIT.java | 85 +++++++++- 6 files changed, 173 insertions(+), 239 deletions(-) diff --git a/src/main/resources/db/dataset/reinit-test-data.sql b/src/main/resources/db/dataset/reinit-test-data.sql index 6d5271fa..4e526ba2 100644 --- a/src/main/resources/db/dataset/reinit-test-data.sql +++ b/src/main/resources/db/dataset/reinit-test-data.sql @@ -29,6 +29,7 @@ TRUNCATE TABLE public.address; INSERT INTO public.address (dtype, l1, l2, l3, l4, l5, l6, l7, elevator, building, floor, door, staircase, city_priority_district) VALUES ('InseeAddress', 'Ted Farmer' ,'','','1 rue de la gare' ,'','29270 Carhaix' ,'France', true, 'Bat. C', 'Etg 4', 'Porte 48', 'Escalier B', true), ('InseeAddress', 'Cecilia Ortega' ,'','','2 place de la mairie' ,'','90000 Belfort' ,'France', false, null, null, null, null, false), + ('InseeAddress', 'Mylene Mikoton' ,'','','3 place de la mairie' ,'','90000 Belfort' ,'France', false, null, null, null, null, false), ('InseeAddress', 'Claude Watkins' ,'','','3 avenue de la République' ,'','32230 Marciac' ,'France', false, null, null, null, null, false), ('InseeAddress', 'Veronica Gill' ,'','','4 chemin du ruisseau' ,'','44190 Clisson' ,'France', false, null, null, null, null, false), ('InseeAddress', 'Christine Aguilar' ,'','','5 rue de l''école' ,'','59620 Aulnoye-Aimeries' ,'France', false, null, null, null, null, false), @@ -82,7 +83,6 @@ INSERT INTO public.preference (id_user, id_campaign) VALUES ('GUEST', 'ZCLOSEDX00'), ('GUEST', 'XCLOSEDX00'); - INSERT INTO visibility ( organization_unit_id, campaign_id, @@ -93,8 +93,8 @@ INSERT INTO visibility ( interviewer_start_date, management_start_date ) VALUES - ('OU-NORTH', 'SIMPSONS2020X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308), - ('OU-SOUTH', 'SIMPSONS2020X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308), + ('OU-NORTH', 'SIMPSONS2020X00',1721903754305, 1719225354304, 1724582154306, 1719138954303, 1719052554302, 1718966154301), + ('OU-SOUTH', 'SIMPSONS2020X00',1721903754315, 1719225354314, 1724582154316, 1719138954310, 1719052554309, 1718966154308), ('OU-NORTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308), ('OU-SOUTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308), ('OU-SOUTH', 'XCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308), @@ -105,6 +105,7 @@ INSERT INTO visibility ( INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; +INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '25', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-SOUTH' FROM address a, sample_identifier s WHERE a.l1='Mylene Mikoton' AND s.bs='25'; INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '13', FALSE, a.id, 'SIMPSONS2020X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Claude Watkins' AND s.bs='13'; INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '14', FALSE, a.id, 'SIMPSONS2020X00', 'INTW3', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Veronica Gill' AND s.bs='14'; INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '20', FALSE, a.id, 'VQS2021X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christine Aguilar' AND s.bs='20'; @@ -117,6 +118,7 @@ INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interview INSERT INTO public.person (email, favorite_email, first_name, last_name, birthdate, title, privileged, survey_unit_id) VALUES ('test@test.com',TRUE, 'Ted', 'Farmer', 11111111, 0, TRUE, '11'), ('test@test.com', TRUE,'Cecilia', 'Ortega', 11111111, 1, TRUE, '12'), + ('test@test.com', TRUE,'Mylene', 'Mikoton', 11111111, 1, TRUE, '25'), ('test@test.com', TRUE,'Claude', 'Watkins', 11111111, 0, TRUE, '13'), ('test@test.com', TRUE,'Veronica', 'Baker', 11111111, 1, TRUE, '14'), ('test@test.com', TRUE,'Christine', 'Aguilar', 11111111, 1, FALSE, '11'), @@ -134,6 +136,7 @@ INSERT INTO public.person (email, favorite_email, first_name, last_name, birthda INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Ted' and p.last_name='Farmer' and p.survey_unit_id='11'; INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT FALSE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Ted' and p.last_name='Farmer' and p.survey_unit_id='11'; INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Cecilia' and p.last_name='Ortega' and p.survey_unit_id='12'; +INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Mylene' and p.last_name='Mikoton' and p.survey_unit_id='25'; INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Claude' and p.last_name='Watkins' and p.survey_unit_id='13'; INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Veronica' and p.last_name='Baker' and p.survey_unit_id='14'; INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Christine' and p.last_name='Aguilar' and p.survey_unit_id='11'; @@ -150,6 +153,7 @@ INSERT INTO public.state (date, type, survey_unit_id) VALUES (111112111,'VIN', '11'), (110111111,'NNS', '11'), (111111111,'TBR', '12'), + (111111111,'TBR', '25'), (111111111,'TBR', '13'), (111111111,'TBR', '14'), (101111111,'TBR', '11'), diff --git a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java index f2d553ee..42a81d11 100644 --- a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java +++ b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java @@ -1,83 +1,12 @@ package fr.insee.pearljam.api.authKeycloak; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.oneOf; -import static org.junit.jupiter.api.Assertions.*; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; - -import java.time.Instant; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.temporal.ChronoUnit; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -import fr.insee.pearljam.api.service.*; -import fr.insee.pearljam.api.utils.MockMvcTestUtils; -import org.json.JSONException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.security.core.Authentication; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestConstructor; -import org.springframework.test.web.client.ExpectedCount; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultMatcher; -import org.springframework.web.client.RestTemplate; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; - import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.controller.WsText; -import fr.insee.pearljam.api.domain.ClosingCause; -import fr.insee.pearljam.api.domain.ClosingCauseType; -import fr.insee.pearljam.domain.surveyunit.model.CommentType; -import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; -import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; -import fr.insee.pearljam.api.domain.ContactOutcomeType; -import fr.insee.pearljam.api.domain.IdentificationConfiguration; -import fr.insee.pearljam.api.domain.Interviewer; -import fr.insee.pearljam.api.domain.Medium; -import fr.insee.pearljam.api.domain.Message; -import fr.insee.pearljam.api.domain.MessageStatusType; -import fr.insee.pearljam.api.domain.OrganizationUnit; -import fr.insee.pearljam.api.domain.OrganizationUnitType; -import fr.insee.pearljam.api.domain.Source; -import fr.insee.pearljam.api.domain.StateType; -import fr.insee.pearljam.api.domain.Status; -import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.api.domain.Title; -import fr.insee.pearljam.api.domain.User; -import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; +import fr.insee.pearljam.api.domain.*; import fr.insee.pearljam.api.dto.address.AddressDto; -import fr.insee.pearljam.api.surveyunit.dto.CommentDto; import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerContextDto; @@ -94,17 +23,50 @@ import fr.insee.pearljam.api.dto.user.UserContextDto; import fr.insee.pearljam.api.dto.user.UserDto; import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.api.repository.CampaignRepository; -import fr.insee.pearljam.api.repository.ClosingCauseRepository; -import fr.insee.pearljam.api.repository.InterviewerRepository; -import fr.insee.pearljam.api.repository.MessageRepository; -import fr.insee.pearljam.api.repository.OrganizationUnitRepository; -import fr.insee.pearljam.api.repository.StateRepository; -import fr.insee.pearljam.api.repository.SurveyUnitRepository; -import fr.insee.pearljam.api.repository.UserRepository; -import fr.insee.pearljam.infrastructure.campaign.jpa.VisibilityJpaRepository; +import fr.insee.pearljam.api.repository.*; +import fr.insee.pearljam.api.service.*; +import fr.insee.pearljam.api.surveyunit.dto.CommentDto; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.MockMvcTestUtils; +import fr.insee.pearljam.domain.surveyunit.model.CommentType; +import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; +import fr.insee.pearljam.infrastructure.campaign.jpa.VisibilityJpaRepository; import lombok.RequiredArgsConstructor; +import org.json.JSONException; +import org.junit.jupiter.api.*; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.security.core.Authentication; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestConstructor; +import org.springframework.test.web.client.ExpectedCount; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.web.client.RestTemplate; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /* Test class for Keycloak Authentication */ @ActiveProfiles("auth") @@ -589,41 +551,10 @@ void testGetSurveyUnitDetail() throws Exception { jsonPath("$.identification.occupant", equalTo("IDENTIFIED"))); } - /** - * Test that the GET endpoint "api/survey-unit/" - * return 200 - * - * @throws InterruptedException - * @throws JSONException - */ - @Test - @Order(12) - void testGetAllSurveyUnit() throws Exception { - mockMvc.perform(get("/api/survey-units") - .with(authentication(INTERVIEWER)) - .accept(MediaType.APPLICATION_JSON)) - .andExpectAll( - status().isOk(), - jsonPath("$.[?(@.id == '11')]").exists(), - jsonPath("$.[?(@.id == '11')].campaign").value("SIMPSONS2020X00"), - jsonPath("$.[?(@.id == '11')].campaignLabel").value("Survey on the Simpsons tv show 2020")); - - mockMvc.perform(get(Constants.API_CAMPAIGNS) - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) - .andExpectAll(status().isOk(), - expectValidManagementStartDate(), - expectValidIdentificationPhaseStartDate(), - expectValidInterviewerStartDate(), - expectValidCollectionStartDate(), - expectValidCollectionEndDate(), - expectValidEndDate()); - } - /** * Test that the GET endpoint "api/survey-unit/{id}" * return 404 when survey-unit is false - * + * * @throws InterruptedException * @throws JSONException */ diff --git a/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java b/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java index 39b97db4..442c6a9b 100644 --- a/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java +++ b/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java @@ -1,22 +1,14 @@ package fr.insee.pearljam.api.noAuth; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.text.ParseException; -import java.time.Instant; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.List; -import com.jayway.jsonpath.JsonPath; -import fr.insee.pearljam.api.utils.MockMvcTestUtils; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import fr.insee.pearljam.api.domain.ClosingCause; +import fr.insee.pearljam.api.domain.ClosingCauseType; +import fr.insee.pearljam.api.dto.message.MessageDto; +import fr.insee.pearljam.api.repository.ClosingCauseRepository; +import fr.insee.pearljam.api.repository.MessageRepository; import fr.insee.pearljam.api.utils.ScriptConstants; -import org.json.JSONException; +import lombok.RequiredArgsConstructor; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; @@ -29,16 +21,14 @@ import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MockMvc; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; -import fr.insee.pearljam.api.domain.ClosingCause; -import fr.insee.pearljam.api.domain.ClosingCauseType; -import fr.insee.pearljam.api.dto.message.MessageDto; -import fr.insee.pearljam.api.repository.ClosingCauseRepository; -import fr.insee.pearljam.api.repository.MessageRepository; -import lombok.RequiredArgsConstructor; -import org.springframework.test.web.servlet.ResultMatcher; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /* Test class for no Authentication */ @ActiveProfiles("noauth") @@ -54,76 +44,6 @@ class TestNoAuth { private final ClosingCauseRepository closingCauseRepository; private final MockMvc mockMvc; - private ResultMatcher expectValidManagementStartDate() { - return expectTimestampFromCurrentDate("$[0].managementStartDate", -4, ChronoUnit.DAYS); - } - - private ResultMatcher expectValidInterviewerStartDate() { - return expectTimestampFromCurrentDate("$[0].interviewerStartDate", -3, ChronoUnit.DAYS); - } - - private ResultMatcher expectValidIdentificationPhaseStartDate() { - return expectTimestampFromCurrentDate("$[0].identificationPhaseStartDate", -2, ChronoUnit.DAYS); - } - - private ResultMatcher expectValidCollectionStartDate() { - return expectTimestampFromCurrentDate("$[0].collectionStartDate", -1, ChronoUnit.DAYS); - } - - private ResultMatcher expectValidCollectionEndDate() { - return expectTimestampFromCurrentDate("$[0].collectionEndDate", 1, ChronoUnit.MONTHS); - } - - private ResultMatcher expectValidEndDate() { - return expectTimestampFromCurrentDate("$[0].endDate", 2, ChronoUnit.MONTHS); - } - - private ResultMatcher expectTimestampFromCurrentDate(String expression, int unitToAdd, ChronoUnit chronoUnit) { - - return mvcResult -> { - String content = mvcResult.getResponse().getContentAsString(); - long timestamp = JsonPath.read(content, expression); - LocalDate localDateNow = MockMvcTestUtils.getDate(); - Instant instant = Instant.ofEpochMilli(timestamp); - LocalDate dateToCheck = LocalDate.ofInstant(instant, ZoneId.systemDefault()); - assertEquals(dateToCheck, localDateNow.plus(unitToAdd, chronoUnit)); - }; - } - - /* CampaignController */ - - /** - * Test that the GET endpoint "api/campaigns" - * return 404 - * - * @throws InterruptedException - * @throws JSONException - * @throws ParseException - */ - - @Test - void testGetCampaign() throws Exception { - mockMvc.perform(get("/api/campaigns") - .accept(MediaType.APPLICATION_JSON)) - .andExpectAll( - status().isOk(), - jsonPath("$[0].id").value("SIMPSONS2020X00"), - jsonPath("$[0].label").value("Survey on the Simpsons tv show 2020"), - jsonPath("$[0].allocated").value(4), - jsonPath("$[0].toAffect").value(0), - jsonPath("$[0].toFollowUp").value(0), - jsonPath("$[0].toReview").value(3), - jsonPath("$[0].finalized").value(0), - jsonPath("$[0].toProcessInterviewer").value(0), - jsonPath("$[0].preference").value(true), - expectValidManagementStartDate(), - expectValidIdentificationPhaseStartDate(), - expectValidInterviewerStartDate(), - expectValidCollectionStartDate(), - expectValidCollectionEndDate(), - expectValidEndDate()); - } - @Test @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) void testPutClosingCauseNoPreviousClosingCause() throws Exception { diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index cc39bd8a..55248b1b 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -46,13 +46,11 @@ class CampaignIT { /** * Test that the GET endpoint "api/campaigns" - * return 404 * * @throws InterruptedException * @throws JSONException * @throws ParseException */ - @Test @DisplayName("Should retrieve campaign") void testGetCampaign() throws Exception { @@ -70,21 +68,21 @@ void testGetCampaign() throws Exception { "visibilities":[ { "organizationalUnit":"OU-NORTH", - "managementStartDate":1718966154308, - "interviewerStartDate":1719052554308, - "identificationPhaseStartDate":1719138954308, - "collectionStartDate":1719225354308, - "collectionEndDate":1721903754308, - "endDate":1724582154308 + "managementStartDate":1718966154301, + "interviewerStartDate":1719052554302, + "identificationPhaseStartDate":1719138954303, + "collectionStartDate":1719225354304, + "collectionEndDate":1721903754305, + "endDate":1724582154306 }, { "organizationalUnit":"OU-SOUTH", "managementStartDate":1718966154308, - "interviewerStartDate":1719052554308, - "identificationPhaseStartDate":1719138954308, - "collectionStartDate":1719225354308, - "collectionEndDate":1721903754308, - "endDate":1724582154308 + "interviewerStartDate":1719052554309, + "identificationPhaseStartDate":1719138954310, + "collectionStartDate":1719225354314, + "collectionEndDate":1721903754315, + "endDate":1724582154316 } ], "referents":[ diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java index 419f1b89..5f522c27 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java @@ -55,21 +55,21 @@ void testGetVisibilities() throws Exception { [ { "organizationalUnit":"OU-NORTH", - "managementStartDate":1718966154308, - "interviewerStartDate":1719052554308, - "identificationPhaseStartDate":1719138954308, - "collectionStartDate":1719225354308, - "collectionEndDate":1721903754308, - "endDate":1724582154308 + "managementStartDate":1718966154301, + "interviewerStartDate":1719052554302, + "identificationPhaseStartDate":1719138954303, + "collectionStartDate":1719225354304, + "collectionEndDate":1721903754305, + "endDate":1724582154306 }, { "organizationalUnit":"OU-SOUTH", "managementStartDate":1718966154308, - "interviewerStartDate":1719052554308, - "identificationPhaseStartDate":1719138954308, - "collectionStartDate":1719225354308, - "collectionEndDate":1721903754308, - "endDate":1724582154308 + "interviewerStartDate":1719052554309, + "identificationPhaseStartDate":1719138954310, + "collectionStartDate":1719225354314, + "collectionEndDate":1721903754315, + "endDate":1724582154316 } ] """; @@ -104,9 +104,9 @@ void testUpdateVisibility() throws Exception { assertThat(visibilityDBToCheck.getCampaign().getId()).isEqualTo(campaignId); assertThat(visibilityDBToCheck.getOrganizationUnit().getId()).isEqualTo(organizationalUnitId); assertThat(visibilityDBToCheck.getManagementStartDate()).isEqualTo(1718966200000L); - assertThat(visibilityDBToCheck.getInterviewerStartDate()).isEqualTo(1719052554308L); + assertThat(visibilityDBToCheck.getInterviewerStartDate()).isEqualTo(1719052554302L); assertThat(visibilityDBToCheck.getIdentificationPhaseStartDate()).isEqualTo(1719138954308L); - assertThat(visibilityDBToCheck.getCollectionStartDate()).isEqualTo(1719225354308L); + assertThat(visibilityDBToCheck.getCollectionStartDate()).isEqualTo(1719225354304L); assertThat(visibilityDBToCheck.getCollectionEndDate()).isEqualTo(1921903754308L); assertThat(visibilityDBToCheck.getEndDate()).isEqualTo(2024582154308L); } diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index 3dbde567..7cfc5863 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -1,11 +1,92 @@ package fr.insee.pearljam.integration.surveyunit; +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.core.Authentication; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.transaction.annotation.Transactional; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +@ActiveProfiles("auth") +@AutoConfigureMockMvc +@ContextConfiguration +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Transactional class SurveyUnitIT { + @Autowired + private MockMvc mockMvc; + + static Authentication INTERVIEWER = AuthenticatedUserTestHelper.AUTH_INTERVIEWER; + @Test - void testGetSurveyUnits() { - // TODO + void testGetAllSurveyUnits() throws Exception { + MvcResult mvcResult = mockMvc.perform(get("/api/survey-units") + .with(authentication(INTERVIEWER)) + .accept(MediaType.APPLICATION_JSON)) + .andReturn(); + + String contentResult = mvcResult.getResponse().getContentAsString(); + String expectedResult = """ + [ + { + "id":"11", + "campaign":"SIMPSONS2020X00", + "campaignLabel":"Survey on the Simpsons tv show 2020", + "managementStartDate":1718966154301, + "interviewerStartDate":1719052554302, + "identificationPhaseStartDate":1719138954303, + "collectionStartDate":1719225354304, + "collectionEndDate":1721903754305, + "endDate":1724582154306, + "identificationConfiguration":"IASCO", + "contactOutcomeConfiguration":"F2F", + "contactAttemptConfiguration":"F2F", + "communicationRequestConfiguration":false + }, + { + "id":"12", + "campaign":"SIMPSONS2020X00", + "campaignLabel":"Survey on the Simpsons tv show 2020", + "managementStartDate":1718966154301, + "interviewerStartDate":1719052554302, + "identificationPhaseStartDate":1719138954303, + "collectionStartDate":1719225354304, + "collectionEndDate":1721903754305, + "endDate":1724582154306, + "identificationConfiguration":"IASCO", + "contactOutcomeConfiguration":"F2F", + "contactAttemptConfiguration":"F2F", + "communicationRequestConfiguration":false + }, + { + "id":"20", + "campaign":"VQS2021X00", + "campaignLabel":"Everyday life and health survey 2021", + "managementStartDate":1718966154308, + "interviewerStartDate":1719052554308, + "identificationPhaseStartDate":1719138954308, + "collectionStartDate":1719225354308, + "collectionEndDate":1721903754308, + "endDate":1724582154308, + "identificationConfiguration":"IASCO", + "contactOutcomeConfiguration":"TEL", + "contactAttemptConfiguration":"TEL", + "communicationRequestConfiguration":false + } + ] + """; + JSONAssert.assertEquals(expectedResult, contentResult, JSONCompareMode.NON_EXTENSIBLE); } } From 1ec9cf3905a19a1c2bbc766273b1a8864ad6f9be Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 21 Aug 2024 18:52:40 +0200 Subject: [PATCH 11/48] test: complete visibility model tests --- .../domain/campaign/model/VisibilityTest.java | 63 +++++++++++++++++-- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java index b831e533..e8ca73c9 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java @@ -3,6 +3,8 @@ import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -17,7 +19,7 @@ void testMergeAndDateValidation() throws VisibilityHasInvalidDatesException { 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); Visibility updateVisibility = new Visibility("campaign1", "OU1", - null, 1627933000000L, null, null, null, 1628277601000L); + 1617933000000L, 1627933000000L, 1627934000000L, 1627935000000L, 1627936000000L, 1628277601000L); // When Visibility mergedVisibility = Visibility.merge(currentVisibility, updateVisibility); @@ -25,12 +27,36 @@ void testMergeAndDateValidation() throws VisibilityHasInvalidDatesException { // Then assertThat(mergedVisibility.campaignId()).isEqualTo("campaign1"); assertThat(mergedVisibility.organizationalUnitId()).isEqualTo("OU1"); - assertThat(mergedVisibility.managementStartDate()).isEqualTo(1627845600000L); + assertThat(mergedVisibility.managementStartDate()).isEqualTo(1617933000000L); assertThat(mergedVisibility.interviewerStartDate()).isEqualTo(1627933000000L); + assertThat(mergedVisibility.identificationPhaseStartDate()).isEqualTo(1627934000000L); + assertThat(mergedVisibility.collectionStartDate()).isEqualTo(1627935000000L); + assertThat(mergedVisibility.collectionEndDate()).isEqualTo(1627936000000L); + assertThat(mergedVisibility.endDate()).isEqualTo(1628277601000L); + } + + @Test + @DisplayName("Should merge 2 visibilities and keep original dates when updated dates are null") + void testMergeNullDates() throws VisibilityHasInvalidDatesException { + // Given + Visibility currentVisibility = new Visibility("campaign1", "OU1", + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + + Visibility updateVisibility = new Visibility("campaign1", "OU1", + null, null, null, null, null, null); + + // When + Visibility mergedVisibility = Visibility.merge(currentVisibility, updateVisibility); + + // Then + assertThat(mergedVisibility.campaignId()).isEqualTo("campaign1"); + assertThat(mergedVisibility.organizationalUnitId()).isEqualTo("OU1"); + assertThat(mergedVisibility.managementStartDate()).isEqualTo(1627845600000L); + assertThat(mergedVisibility.interviewerStartDate()).isEqualTo(1627932000000L); assertThat(mergedVisibility.identificationPhaseStartDate()).isEqualTo(1628018400000L); assertThat(mergedVisibility.collectionStartDate()).isEqualTo(1628104800000L); assertThat(mergedVisibility.collectionEndDate()).isEqualTo(1628191200000L); - assertThat(mergedVisibility.endDate()).isEqualTo(1628277601000L); + assertThat(mergedVisibility.endDate()).isEqualTo(1628277600000L); } @Test @@ -41,11 +67,40 @@ void testMergeThrowsExceptionForInvalidDates() { 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); Visibility updateVisibility = new Visibility("campaign1", "OU1", - 1427931000000L, 1327932000001L, null, null, null, null); + 1227845600000L, 1327932000001L, 1327932000002L, 1327932000003L, 1327932000004L, 1327932000004L); // When & Then assertThatThrownBy(() -> Visibility.merge(currentVisibility, updateVisibility)) .isInstanceOf(VisibilityHasInvalidDatesException.class) .hasMessage(VisibilityHasInvalidDatesException.MESSAGE); } + + @ParameterizedTest + @CsvSource({ + "1327932000000,1327932000001,1327932000002,1327932000003,1327932000004,1327932000004", + "1327932000000,1327932000001,1327932000002,1327932000003,1327932000003,1327932000004", + "1327932000000,1327932000001,1327932000002,1327932000002,1327932000003,1327932000004", + "1327932000000,1327932000001,1327932000001,1327932000002,1327932000003,1327932000004", + "1327932000000,1327932000000,1327932000001,1327932000002,1327932000003,1327932000004" + }) + @DisplayName("Should throw exception when merged visibilities dates are invalid") + void testMergeThrowsExceptionForInvalidDates2(String managementStartDate, String interviwerStartDate, String identificationPhaseStartDate, String collectionStartDate, String collectionEndDate, String endDate) { + // Given + Visibility currentVisibility = new Visibility("campaign1", "OU1", + 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + + Visibility updateVisibility = new Visibility("campaign1", "OU1", + getLong(managementStartDate), getLong(interviwerStartDate), + getLong(identificationPhaseStartDate), getLong(collectionStartDate), + getLong(collectionEndDate), getLong(endDate)); + + // When & Then + assertThatThrownBy(() -> Visibility.merge(currentVisibility, updateVisibility)) + .isInstanceOf(VisibilityHasInvalidDatesException.class) + .hasMessage(VisibilityHasInvalidDatesException.MESSAGE); + } + + private Long getLong(String date) { + return Long.parseLong(date); + } } From 2c4d8ab198a0f99ecb43ad76fc7596c8310eca06 Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 21 Aug 2024 19:00:47 +0200 Subject: [PATCH 12/48] test: fix sonar issue about interviewer field --- .../insee/pearljam/integration/surveyunit/SurveyUnitIT.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index 7cfc5863..642006ff 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -8,7 +8,6 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; -import org.springframework.security.core.Authentication; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.web.servlet.MockMvc; @@ -28,12 +27,10 @@ class SurveyUnitIT { @Autowired private MockMvc mockMvc; - static Authentication INTERVIEWER = AuthenticatedUserTestHelper.AUTH_INTERVIEWER; - @Test void testGetAllSurveyUnits() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/api/survey-units") - .with(authentication(INTERVIEWER)) + .with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)) .accept(MediaType.APPLICATION_JSON)) .andReturn(); From 42bc26f63435ea02574b31a09b827531a2010c1d Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 21 Aug 2024 19:10:36 +0200 Subject: [PATCH 13/48] fix: pass campaign deletion error message in the thrown exception --- .../fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java | 2 -- .../pearljam/domain/exception/CampaignOnGoingException.java | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index d62e6feb..3bfa7281 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -189,8 +189,6 @@ public void delete(String campaignId, boolean force) throws CampaignNotFoundExce .orElseThrow(CampaignNotFoundException::new); if (!force && isCampaignOngoing(campaignId)) { - String errorMessage = String.format("Campaign %s is on-going and can't be deleted", campaignId); - log.info(errorMessage); throw new CampaignOnGoingException(); } surveyUnitRepository.findByCampaignId(campaign.getId()).stream().forEach(surveyUnitService::delete); diff --git a/src/main/java/fr/insee/pearljam/domain/exception/CampaignOnGoingException.java b/src/main/java/fr/insee/pearljam/domain/exception/CampaignOnGoingException.java index 204bb72f..e66b9427 100644 --- a/src/main/java/fr/insee/pearljam/domain/exception/CampaignOnGoingException.java +++ b/src/main/java/fr/insee/pearljam/domain/exception/CampaignOnGoingException.java @@ -2,7 +2,7 @@ public class CampaignOnGoingException extends Exception { - public static final String MESSAGE = "Campaign is ongoing"; + public static final String MESSAGE = "Campaign is on-going and can't be deleted"; public CampaignOnGoingException() { super(MESSAGE); From a232fb97f10c2006067c9be1558ec94ad9f65e6a Mon Sep 17 00:00:00 2001 From: davdarras Date: Thu, 22 Aug 2024 11:00:52 +0200 Subject: [PATCH 14/48] chore: add swagger tryout button enabled by default --- src/main/resources/application.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 76cce0a9..5ddfc993 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -85,6 +85,7 @@ springdoc: activated: false tagsSorter: alpha doc-expansion: none + tryItOutEnabled: true logging: level: From e77fd32314f2d03fe3f964655e44b4077f880b49 Mon Sep 17 00:00:00 2001 From: davdarras Date: Thu, 22 Aug 2024 11:01:29 +0200 Subject: [PATCH 15/48] chore: handle log path differently to have the extension .log at the end --- src/main/resources/logback-spring.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml index 11528871..f6c07c3b 100644 --- a/src/main/resources/logback-spring.xml +++ b/src/main/resources/logback-spring.xml @@ -12,7 +12,7 @@ ${LOG_FILE} - ${LOG_FILE}.%d{yyyy-MM-dd}.gz + %d{yyyy-MM-dd}.${LOG_FILE}.gz ${LOGBACK_ROLLINGPOLICY_MAX_HISTORY} From bca240922cb221fa0a52554dd46dbb72edc5c8ea Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 4 Sep 2024 18:20:45 +0200 Subject: [PATCH 16/48] style: change typo for messhugah and communication medium --- .../dto/input/CommunicationTemplateCreateDto.java | 6 +++--- .../output/CommunicationTemplateResponseDto.java | 2 +- .../model/communication/CommunicationMedium.java | 2 +- .../model/communication/CommunicationTemplate.java | 4 ++-- .../campaign/entity/CommunicationTemplateDB.java | 6 +++--- .../changelog/541_add_communication_template.xml | 2 +- .../input/CommunicationTemplateCreateDtoTest.java | 8 ++++---- .../CommunicationTemplateResponseDtoTest.java | 4 ++-- .../entity/CommunicationTemplateDBTest.java | 14 +++++++------- 9 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java index 07d15389..efa2c9e1 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java @@ -10,13 +10,13 @@ /** * A class representing the communication template of a visibility. * - * @param messhugahId The identifier for Messhugah + * @param meshuggahId The identifier for Messhugah * @param medium The medium of communication * @param type The type of communication */ public record CommunicationTemplateCreateDto( @NotNull - String messhugahId, + String meshuggahId, @NotNull CommunicationMedium medium, @NotNull @@ -27,7 +27,7 @@ public static List toModel(List new CommunicationTemplate( null, - communicationTemplate.messhugahId(), + communicationTemplate.meshuggahId(), communicationTemplate.medium(), communicationTemplate.type())) .toList(); diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java index 860c3fa9..944d9b1c 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java @@ -17,7 +17,7 @@ public static List fromModel(List new CommunicationTemplateResponseDto( communicationTemplate.id(), - communicationTemplate.messhugahId(), + communicationTemplate.meshuggahId(), communicationTemplate.medium(), communicationTemplate.type())) .toList(); diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationMedium.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationMedium.java index c79534f4..0380e3e2 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationMedium.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationMedium.java @@ -1,5 +1,5 @@ package fr.insee.pearljam.domain.campaign.model.communication; public enum CommunicationMedium { - MAIL, EMAIL + LETTER, EMAIL } diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java index 75d5b24d..7e53bc9b 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java @@ -5,13 +5,13 @@ * A class representing the communication template of a visibility. * * @param id The unique identifier of the communication template - * @param messhugahId The identifier for Messhugah + * @param meshuggahId The identifier for Messhugah * @param medium The medium of communication * @param type The type of communication */ public record CommunicationTemplate( Long id, - String messhugahId, + String meshuggahId, CommunicationMedium medium, CommunicationType type ) { diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java index 910bfe3d..95893cec 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java @@ -30,7 +30,7 @@ public class CommunicationTemplateDB implements Serializable { private Long id; @Column - private String messhugahId; + private String meshuggahId; @Column @Enumerated(EnumType.STRING) @@ -48,7 +48,7 @@ public static List toModel(List return communicationTemplatesDB.stream() .map(communicationTemplateDB -> new CommunicationTemplate( communicationTemplateDB.getId(), - communicationTemplateDB.getMesshugahId(), + communicationTemplateDB.getMeshuggahId(), communicationTemplateDB.getMedium(), communicationTemplateDB.getType())) .toList(); @@ -57,7 +57,7 @@ public static List toModel(List public static List fromModel(List communicationTemplates, Campaign campaign) { return communicationTemplates.stream() .map(communicationTemplate -> new CommunicationTemplateDB(null, - communicationTemplate.messhugahId(), + communicationTemplate.meshuggahId(), communicationTemplate.medium(), communicationTemplate.type(), campaign)) diff --git a/src/main/resources/db/changelog/541_add_communication_template.xml b/src/main/resources/db/changelog/541_add_communication_template.xml index b90421ad..254fc569 100644 --- a/src/main/resources/db/changelog/541_add_communication_template.xml +++ b/src/main/resources/db/changelog/541_add_communication_template.xml @@ -8,7 +8,7 @@ - + diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java index fe40748e..9bdc8dc4 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java @@ -17,7 +17,7 @@ class CommunicationTemplateCreateDtoTest { void testToModel() { // Given CommunicationTemplateCreateDto dto1 = new CommunicationTemplateCreateDto("msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); - CommunicationTemplateCreateDto dto2 = new CommunicationTemplateCreateDto("msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER); + CommunicationTemplateCreateDto dto2 = new CommunicationTemplateCreateDto("msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER); List dtoList = List.of(dto1, dto2); // When @@ -28,14 +28,14 @@ void testToModel() { CommunicationTemplate firstTemplate = modelList.getFirst(); assertThat(firstTemplate.id()).isNull(); - assertThat(firstTemplate.messhugahId()).isEqualTo("msg1"); + assertThat(firstTemplate.meshuggahId()).isEqualTo("msg1"); assertThat(firstTemplate.medium()).isEqualTo(CommunicationMedium.EMAIL); assertThat(firstTemplate.type()).isEqualTo(CommunicationType.NOTICE); CommunicationTemplate lastTemplate = modelList.getLast(); assertThat(lastTemplate.id()).isNull(); - assertThat(lastTemplate.messhugahId()).isEqualTo("msg2"); - assertThat(lastTemplate.medium()).isEqualTo(CommunicationMedium.MAIL); + assertThat(lastTemplate.meshuggahId()).isEqualTo("msg2"); + assertThat(lastTemplate.medium()).isEqualTo(CommunicationMedium.LETTER); assertThat(lastTemplate.type()).isEqualTo(CommunicationType.REMINDER); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java index 1c4407d5..50361b25 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java @@ -17,7 +17,7 @@ class CommunicationTemplateResponseDtoTest { void testFromModel() { // Given CommunicationTemplate template1 = new CommunicationTemplate(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); - CommunicationTemplate template2 = new CommunicationTemplate(2L, "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER); + CommunicationTemplate template2 = new CommunicationTemplate(2L, "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER); List communicationTemplates = List.of(template1, template2); // When @@ -35,7 +35,7 @@ void testFromModel() { CommunicationTemplateResponseDto dto2 = communicationDtos.get(1); assertThat(dto2.id()).isEqualTo(2L); assertThat(dto2.messhugahId()).isEqualTo("msg2"); - assertThat(dto2.medium()).isEqualTo(CommunicationMedium.MAIL); + assertThat(dto2.medium()).isEqualTo(CommunicationMedium.LETTER); assertThat(dto2.type()).isEqualTo(CommunicationType.REMINDER); } } diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java index 9a3df298..110d40ff 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java @@ -24,7 +24,7 @@ void testToModel() { ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, "email@plop.com", true); CommunicationTemplateDB templateDB1 = new CommunicationTemplateDB(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE, campaign); - CommunicationTemplateDB templateDB2 = new CommunicationTemplateDB(2L, "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER, campaign); + CommunicationTemplateDB templateDB2 = new CommunicationTemplateDB(2L, "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER, campaign); List dbList = List.of(templateDB1, templateDB2); // When @@ -35,13 +35,13 @@ void testToModel() { .hasSize(2); assertThat(modelList.getFirst().id()).isEqualTo(1L); - assertThat(modelList.getFirst().messhugahId()).isEqualTo("msg1"); + assertThat(modelList.getFirst().meshuggahId()).isEqualTo("msg1"); assertThat(modelList.getFirst().medium()).isEqualTo(CommunicationMedium.EMAIL); assertThat(modelList.getFirst().type()).isEqualTo(CommunicationType.NOTICE); assertThat(modelList.getLast().id()).isEqualTo(2L); - assertThat(modelList.getLast().messhugahId()).isEqualTo("msg2"); - assertThat(modelList.getLast().medium()).isEqualTo(CommunicationMedium.MAIL); + assertThat(modelList.getLast().meshuggahId()).isEqualTo("msg2"); + assertThat(modelList.getLast().medium()).isEqualTo(CommunicationMedium.LETTER); assertThat(modelList.getLast().type()).isEqualTo(CommunicationType.REMINDER); } @@ -53,7 +53,7 @@ void testFromModel() { ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, "email@plop.com", true); CommunicationTemplate template1 = new CommunicationTemplate(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); - CommunicationTemplate template2 = new CommunicationTemplate(2L, "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER); + CommunicationTemplate template2 = new CommunicationTemplate(2L, "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER); List modelList = List.of(template1, template2); // When @@ -68,7 +68,7 @@ void testFromModel() { }) .anySatisfy(templateDB -> { verifyCommunicationTemplateDB(templateDB, null, - "msg2", CommunicationMedium.MAIL, CommunicationType.REMINDER, campaign); + "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER, campaign); }); } @@ -81,7 +81,7 @@ private void verifyCommunicationTemplateDB( Campaign expectedCampaign ) { assertThat(templateDB.getId()).isEqualTo(expectedId); - assertThat(templateDB.getMesshugahId()).isEqualTo(expectedMesshugahId); + assertThat(templateDB.getMeshuggahId()).isEqualTo(expectedMesshugahId); assertThat(templateDB.getMedium()).isEqualTo(expectedMedium); assertThat(templateDB.getType()).isEqualTo(expectedType); assertThat(templateDB.getCampaign()).isEqualTo(expectedCampaign); From 83441c3eed2a8a0617aa0f1671575029a92a1bcf Mon Sep 17 00:00:00 2001 From: davdarras Date: Thu, 5 Sep 2024 09:57:42 +0200 Subject: [PATCH 17/48] feat: create communication configurations when creating campaigns --- .../campaign/dto/input/CampaignCreateDto.java | 4 ++ .../input/CommunicationTemplateCreateDto.java | 22 +++++++--- .../insee/pearljam/api/domain/Campaign.java | 4 ++ .../api/service/impl/CampaignServiceImpl.java | 15 +++++-- .../CommunicationMediumTypeKey.java | 9 +++++ .../annotation/NoDuplicateMediumAndType.java | 18 +++++++++ .../NoDuplicateMediumAndTypeValidator.java | 23 +++++++++++ .../entity/CommunicationTemplateDB.java | 24 +++++++---- .../CampaignControllerCreateTest.java | 40 +++++++++++++++++-- .../service/CampaignServiceImplTest.java | 21 +++++++--- 10 files changed, 152 insertions(+), 28 deletions(-) create mode 100644 src/main/java/fr/insee/pearljam/api/web/annotation/CommunicationMediumTypeKey.java create mode 100644 src/main/java/fr/insee/pearljam/api/web/annotation/NoDuplicateMediumAndType.java create mode 100644 src/main/java/fr/insee/pearljam/api/web/annotation/NoDuplicateMediumAndTypeValidator.java diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java index 4049e257..2ab585ca 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java @@ -8,6 +8,7 @@ import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; import fr.insee.pearljam.api.domain.IdentificationConfiguration; import fr.insee.pearljam.api.dto.referent.ReferentDto; +import fr.insee.pearljam.api.web.annotation.NoDuplicateMediumAndType; import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty; @@ -21,6 +22,9 @@ public record CampaignCreateDto ( @NotEmpty @Valid List visibilities, + @Valid + @NoDuplicateMediumAndType + List communications, List referents, String email, IdentificationConfiguration identificationConfiguration, diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java index efa2c9e1..48868960 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java @@ -5,6 +5,7 @@ import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; import jakarta.validation.constraints.NotNull; +import java.util.ArrayList; import java.util.List; /** @@ -23,13 +24,22 @@ public record CommunicationTemplateCreateDto( CommunicationType type ) { public static List toModel(List communicationTemplates) { + if(communicationTemplates == null) { + return new ArrayList<>(); + } return communicationTemplates.stream() - .map(communicationTemplate -> - new CommunicationTemplate( - null, - communicationTemplate.meshuggahId(), - communicationTemplate.medium(), - communicationTemplate.type())) + .map(CommunicationTemplateCreateDto::toModel) .toList(); } + + public static CommunicationTemplate toModel(CommunicationTemplateCreateDto communicationTemplate) { + if(communicationTemplate == null) { + return null; + } + return new CommunicationTemplate( + null, + communicationTemplate.meshuggahId(), + communicationTemplate.medium(), + communicationTemplate.type()); + } } diff --git a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java index b4eecbd4..89a631b8 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Optional; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; @@ -75,6 +76,9 @@ public class Campaign implements Serializable { @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, orphanRemoval = true) private List referents; + @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, orphanRemoval = true) + private List communicationTemplates; + public Campaign(String id, String label, IdentificationConfiguration identConfig, ContactOutcomeConfiguration contOutConfig, ContactAttemptConfiguration contAttConfig, String email, Boolean communicationConfiguration) { diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index 3bfa7281..a8c0bb83 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -1,9 +1,6 @@ package fr.insee.pearljam.api.service.impl; -import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; -import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; -import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignCreateDto; -import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.input.*; import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; import fr.insee.pearljam.api.campaign.dto.output.VisibilityCampaignDto; import fr.insee.pearljam.api.domain.Campaign; @@ -20,8 +17,11 @@ import fr.insee.pearljam.api.service.*; import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.port.userside.DateService; import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; import fr.insee.pearljam.domain.exception.*; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import lombok.NonNull; import lombok.RequiredArgsConstructor; @@ -160,6 +160,7 @@ public void createCampaign(CampaignCreateDto campaignDto) campaignDto.email(), campaignDto.communicationRequestConfiguration()); campaign.setReferents(new ArrayList<>()); + campaign.setCommunicationTemplates(new ArrayList<>()); List visibilitiesDBToCreate = new ArrayList<>(); List visibilities = VisibilityCampaignCreateDto.toModel(campaignDto.visibilities(), campaignDto.campaign()); @@ -175,6 +176,12 @@ public void createCampaign(CampaignCreateDto campaignDto) if(campaignDto.referents() != null) { updateReferents(campaign, campaignDto.referents()); } + + List communicationTemplatesToCreate = CommunicationTemplateCreateDto.toModel(campaignDto.communications()); + if(communicationTemplatesToCreate != null) { + List communicationsDBToCreate = CommunicationTemplateDB.fromModel(communicationTemplatesToCreate, campaign); + campaign.setCommunicationTemplates(communicationsDBToCreate); + } campaignRepository.save(campaign); } diff --git a/src/main/java/fr/insee/pearljam/api/web/annotation/CommunicationMediumTypeKey.java b/src/main/java/fr/insee/pearljam/api/web/annotation/CommunicationMediumTypeKey.java new file mode 100644 index 00000000..5634a9c3 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/web/annotation/CommunicationMediumTypeKey.java @@ -0,0 +1,9 @@ +package fr.insee.pearljam.api.web.annotation; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; + +public record CommunicationMediumTypeKey( + CommunicationMedium medium, + CommunicationType type) { +} diff --git a/src/main/java/fr/insee/pearljam/api/web/annotation/NoDuplicateMediumAndType.java b/src/main/java/fr/insee/pearljam/api/web/annotation/NoDuplicateMediumAndType.java new file mode 100644 index 00000000..10db5b29 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/web/annotation/NoDuplicateMediumAndType.java @@ -0,0 +1,18 @@ +package fr.insee.pearljam.api.web.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Constraint(validatedBy = {NoDuplicateMediumAndTypeValidator.class}) +@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface NoDuplicateMediumAndType { + String message() default "Some communication configurations have same type and medium, that should not be possible"; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/src/main/java/fr/insee/pearljam/api/web/annotation/NoDuplicateMediumAndTypeValidator.java b/src/main/java/fr/insee/pearljam/api/web/annotation/NoDuplicateMediumAndTypeValidator.java new file mode 100644 index 00000000..1dbf05fb --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/web/annotation/NoDuplicateMediumAndTypeValidator.java @@ -0,0 +1,23 @@ +package fr.insee.pearljam.api.web.annotation; + +import fr.insee.pearljam.api.campaign.dto.input.CommunicationTemplateCreateDto; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class NoDuplicateMediumAndTypeValidator implements ConstraintValidator> { + @Override + public boolean isValid(List communicationTemplates, ConstraintValidatorContext context) { + if(communicationTemplates == null) { + return true; + } + + Set uniqueMediumTypePairs = new HashSet<>(); + return communicationTemplates.stream() + .map(template -> new CommunicationMediumTypeKey(template.medium(), template.type())) + .allMatch(uniqueMediumTypePairs::add); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java index 95893cec..842ee1ee 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java @@ -13,9 +13,10 @@ import java.io.Serializable; import java.util.List; -@Entity(name = "communication_template") -@Table(uniqueConstraints = { - @UniqueConstraint(columnNames = {"type", "medium", "campaign_id"}) +@Entity +@Table(name = "communication_template", + uniqueConstraints = { + @UniqueConstraint(columnNames = {"type", "medium", "campaign_id"}) }) @Getter @Setter @@ -46,14 +47,21 @@ public class CommunicationTemplateDB implements Serializable { public static List toModel(List communicationTemplatesDB) { return communicationTemplatesDB.stream() - .map(communicationTemplateDB -> new CommunicationTemplate( - communicationTemplateDB.getId(), - communicationTemplateDB.getMeshuggahId(), - communicationTemplateDB.getMedium(), - communicationTemplateDB.getType())) + .map(CommunicationTemplateDB::toModel) .toList(); } + public static CommunicationTemplate toModel(CommunicationTemplateDB communicationTemplate) { + if(communicationTemplate == null) { + return null; + } + return new CommunicationTemplate( + communicationTemplate.getId(), + communicationTemplate.getMeshuggahId(), + communicationTemplate.getMedium(), + communicationTemplate.getType()); + } + public static List fromModel(List communicationTemplates, Campaign campaign) { return communicationTemplates.stream() .map(communicationTemplate -> new CommunicationTemplateDB(null, diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java index 27ff7436..7c967680 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java @@ -1,6 +1,7 @@ package fr.insee.pearljam.api.campaign.controller; import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; +import fr.insee.pearljam.api.campaign.dto.input.CommunicationTemplateCreateDto; import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignCreateDto; import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.controller.CampaignController; @@ -13,6 +14,8 @@ import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; import fr.insee.pearljam.api.web.exception.ExceptionControllerAdvice; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; import fr.insee.pearljam.domain.exception.CampaignAlreadyExistException; import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; @@ -95,17 +98,19 @@ void testCreateCampaign04() throws Exception { VisibilityCampaignCreateDto visibility = generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, 1721683254000L, 1721683255000L); - CampaignCreateDto campaign1 = generateCampaign(" ", "An other campaign", + CampaignCreateDto campaign1 = generateCampaign(" ", "An other campaign", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, true, List.of(visibility), + List.of(), List.of()); - CampaignCreateDto campaign2 = generateCampaign("campId", " ", + CampaignCreateDto campaign2 = generateCampaign("campId", " ", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, true, List.of(visibility), + List.of(), List.of()); List campaigns = List.of(campaign1, campaign2); for(CampaignCreateDto campaign : campaigns) { @@ -151,6 +156,7 @@ void testCreateCampaign05() throws Exception { ContactAttemptConfiguration.F2F, true, invalidCampaignVisibilities, + List.of(), List.of()); mockMvc.perform(post(Constants.API_CAMPAIGN) .contentType(MediaType.APPLICATION_JSON) @@ -175,11 +181,34 @@ void testCreateCampaign06() throws Exception { .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.CONFLICT, Constants.API_CAMPAIGN, VisibilityHasInvalidDatesException.MESSAGE)); } + @Test + @DisplayName("Should return conflict when duplicate medium/type on communication configurations") + void testCreateCampaign07() throws Exception { + VisibilityCampaignCreateDto visibility = generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, + 1721683253000L, 1721683254000L, 1721683255000L); + CommunicationTemplateCreateDto communicationTemplate = new CommunicationTemplateCreateDto("messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplateCreateDto duplicatedCommunicationTemplate = new CommunicationTemplateCreateDto("messhId2", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CampaignCreateDto campaign = generateCampaign("campId", "label", + "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + ContactAttemptConfiguration.F2F, + true, + List.of(visibility), + List.of(), + List.of(communicationTemplate, duplicatedCommunicationTemplate)); + + mockMvc.perform(post(Constants.API_CAMPAIGN) + .contentType(MediaType.APPLICATION_JSON) + .content(JsonTestHelper.toJson(campaign))) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, Constants.API_CAMPAIGN, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); + } + /** * Generate a default campaign * @return a pair of json string and dto object for the campaign */ public CampaignCreateDto generateDefaultCampaign() { + CommunicationTemplateCreateDto communicationTemplate1 = new CommunicationTemplateCreateDto("messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplateCreateDto communicationTemplate2 = new CommunicationTemplateCreateDto("messhId2", CommunicationMedium.LETTER, CommunicationType.REMINDER); VisibilityCampaignCreateDto firstVisibility = generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, @@ -199,7 +228,8 @@ public CampaignCreateDto generateDefaultCampaign() { ContactAttemptConfiguration.TEL, true, List.of(firstVisibility, secondVisibility), - List.of(firstReferent, secondReferent)); + List.of(firstReferent, secondReferent), + List.of(communicationTemplate1, communicationTemplate2)); } private CampaignCreateDto generateCampaign( @@ -209,11 +239,13 @@ private CampaignCreateDto generateCampaign( ContactAttemptConfiguration contactAttemptConfiguration, Boolean communicationRequestConfiguration, List visibilities, - List referents) { + List referents, + List communicationTemplates) { return new CampaignCreateDto(campaignId, campaignLabel, visibilities, + communicationTemplates, referents, email, identificationConfiguration, diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java index 60888c75..8a2666f8 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java @@ -2,16 +2,16 @@ import fr.insee.pearljam.api.campaign.controller.dummy.ReferentFakeService; import fr.insee.pearljam.api.campaign.controller.dummy.VisibilityFakeService; -import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; -import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; -import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignCreateDto; -import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.input.*; import fr.insee.pearljam.api.domain.*; import fr.insee.pearljam.api.service.impl.CampaignServiceImpl; import fr.insee.pearljam.api.surveyunit.controller.dummy.SurveyUnitFakeService; import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; import fr.insee.pearljam.domain.campaign.service.dummy.*; import fr.insee.pearljam.domain.exception.*; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -90,12 +90,15 @@ void setup() { @DisplayName("Should create a new campaign successfully") void shouldCreateNewCampaign() throws CampaignAlreadyExistException, OrganizationalUnitNotFoundException, VisibilityHasInvalidDatesException { String campaignId = "CAMP1"; + + CommunicationTemplateCreateDto communicationTemplateDto = new CommunicationTemplateCreateDto("meshuggahId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto(1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId()); CampaignCreateDto campaignCreateDto = new CampaignCreateDto( campaignId, "Campaign 1", List.of(visibilityDto), + List.of(communicationTemplateDto), null, null, IdentificationConfiguration.IASCO, @@ -116,7 +119,13 @@ void shouldCreateNewCampaign() throws CampaignAlreadyExistException, Organizatio assertThat(createdCampaign.getContactOutcomeConfiguration()).isEqualTo(campaignCreateDto.contactOutcomeConfiguration()); assertThat(createdCampaign.getVisibilities()) .hasSize(1) - .satisfiesExactly(visibility -> assertThat(VisibilityDB.toModel(visibility)).isEqualTo(VisibilityCampaignCreateDto.toModel(visibilityDto, campaignId))); + .satisfiesExactly(visibility -> assertThat(VisibilityDB.toModel(visibility)) + .isEqualTo(VisibilityCampaignCreateDto.toModel(visibilityDto, campaignId))); + assertThat(createdCampaign.getCommunicationTemplates()) + .hasSize(1) + .satisfiesExactly(communicationTemplateDB -> + assertThat(CommunicationTemplateDB.toModel(communicationTemplateDB)) + .isEqualTo(CommunicationTemplateCreateDto.toModel(communicationTemplateDto))); } @Test @@ -131,6 +140,7 @@ void shouldThrowCampaignAlreadyExistExceptionWhenCreatingExistingCampaign() { List.of(visibilityDto), null, null, + null, IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, @@ -228,7 +238,6 @@ void shouldNotUpdateVisibilitiesIfNull() throws CampaignNotFoundException, Visib assertThat(updatedCampaign.getVisibilities()).hasSize(2); } - // TODO : handle referents @Test @DisplayName("Should not update referents if null") void shouldNotUpdateReferentsIfNull() throws VisibilityHasInvalidDatesException, CampaignNotFoundException, VisibilityNotFoundException { From 4c69d0b5e42069969a2e3996adf708f5e0bdeea8 Mon Sep 17 00:00:00 2001 From: davdarras Date: Thu, 5 Sep 2024 10:15:20 +0200 Subject: [PATCH 18/48] fix: allow implementations of date service This simplifies tests on dates --- .../api/service/impl/CampaignServiceImpl.java | 4 ++-- .../campaign/port/userside/DateService.java | 8 ++++++++ .../campaign/service/CurrentDateService.java | 15 +++++++++++++++ .../api/authKeycloak/TestAuthKeyCloak.java | 5 ++++- .../insee/pearljam/api/noAuth/TestNoAuth.java | 5 ++++- .../pearljam/api/utils/MockMvcTestUtils.java | 3 ++- .../config/DateServiceConfiguration.java | 19 +++++++++++++++++++ .../service/CampaignServiceImplTest.java | 3 ++- .../service/dummy/FixedDateService.java | 11 +++++++++++ 9 files changed, 67 insertions(+), 6 deletions(-) create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/port/userside/DateService.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/service/CurrentDateService.java create mode 100644 src/test/java/fr/insee/pearljam/config/DateServiceConfiguration.java create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/FixedDateService.java diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index a8c0bb83..4839692f 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -30,7 +30,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -62,6 +61,7 @@ public class CampaignServiceImpl implements CampaignService { private final PreferenceService preferenceService; private final ReferentService referentService; private final VisibilityService visibilityService; + private final DateService dateService; @Override public List getListCampaign(String userId) { @@ -280,7 +280,7 @@ public boolean isCampaignOngoing(String campaignId) throws CampaignNotFoundExcep .orElseThrow(CampaignNotFoundException::new); List visibilities = visibilityService.findVisibilities(campaign.getId()); return visibilities.stream() - .anyMatch(visibility -> visibility.endDate() > Instant.now().toEpochMilli()); + .anyMatch(visibility -> visibility.endDate() > dateService.getCurrentTimestamp()); } private void updateReferents(Campaign campaign, @NonNull List referentDtos) { diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/DateService.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/DateService.java new file mode 100644 index 00000000..4f492ed8 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/DateService.java @@ -0,0 +1,8 @@ +package fr.insee.pearljam.domain.campaign.port.userside; + +public interface DateService { + /** + * @return current timestamp + */ + long getCurrentTimestamp(); +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/service/CurrentDateService.java b/src/main/java/fr/insee/pearljam/domain/campaign/service/CurrentDateService.java new file mode 100644 index 00000000..e135c6ed --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/service/CurrentDateService.java @@ -0,0 +1,15 @@ +package fr.insee.pearljam.domain.campaign.service; + + +import fr.insee.pearljam.domain.campaign.port.userside.DateService; +import org.springframework.stereotype.Component; + +import java.time.Instant; + +@Component +public class CurrentDateService implements DateService { + @Override + public long getCurrentTimestamp() { + return Instant.now().toEpochMilli(); + } +} diff --git a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java index 42a81d11..2728c3fb 100644 --- a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java +++ b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java @@ -28,6 +28,7 @@ import fr.insee.pearljam.api.surveyunit.dto.CommentDto; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import fr.insee.pearljam.api.utils.MockMvcTestUtils; +import fr.insee.pearljam.config.DateServiceConfiguration; import fr.insee.pearljam.domain.surveyunit.model.CommentType; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import fr.insee.pearljam.infrastructure.campaign.jpa.VisibilityJpaRepository; @@ -36,6 +37,7 @@ import org.junit.jupiter.api.*; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -69,13 +71,14 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /* Test class for Keycloak Authentication */ -@ActiveProfiles("auth") +@ActiveProfiles(profiles = {"auth", "test"}) @AutoConfigureMockMvc @ContextConfiguration @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) @RequiredArgsConstructor +@Import(DateServiceConfiguration.class) class TestAuthKeyCloak { private final SurveyUnitService surveyUnitService; diff --git a/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java b/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java index 442c6a9b..69d79578 100644 --- a/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java +++ b/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java @@ -8,12 +8,14 @@ import fr.insee.pearljam.api.repository.ClosingCauseRepository; import fr.insee.pearljam.api.repository.MessageRepository; import fr.insee.pearljam.api.utils.ScriptConstants; +import fr.insee.pearljam.config.DateServiceConfiguration; import lombok.RequiredArgsConstructor; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; @@ -31,13 +33,14 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /* Test class for no Authentication */ -@ActiveProfiles("noauth") +@ActiveProfiles(profiles = {"noauth", "test"}) @AutoConfigureMockMvc @ContextConfiguration @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) @RequiredArgsConstructor @TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@Import(DateServiceConfiguration.class) class TestNoAuth { private final MessageRepository messageRepository; diff --git a/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java b/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java index fc5b7c17..e6e4dd05 100644 --- a/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java +++ b/src/test/java/fr/insee/pearljam/api/utils/MockMvcTestUtils.java @@ -2,6 +2,7 @@ import fr.insee.pearljam.api.utils.matcher.StructureDateMatcher; import fr.insee.pearljam.api.web.exception.ExceptionControllerAdvice; +import fr.insee.pearljam.domain.campaign.service.dummy.FixedDateService; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.test.web.servlet.ResultMatcher; @@ -30,7 +31,7 @@ public static ExceptionControllerAdvice createExceptionControllerAdvice() { } public static LocalDate getDate() { - Instant fixedInstant = Instant.ofEpochMilli(1719324512000L); + Instant fixedInstant = Instant.ofEpochMilli(FixedDateService.FIXED_TIMESTAMP); return LocalDate.ofInstant(fixedInstant, ZoneId.systemDefault()); } } \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/config/DateServiceConfiguration.java b/src/test/java/fr/insee/pearljam/config/DateServiceConfiguration.java new file mode 100644 index 00000000..e8c8cfd8 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/config/DateServiceConfiguration.java @@ -0,0 +1,19 @@ +package fr.insee.pearljam.config; + +import fr.insee.pearljam.domain.campaign.port.userside.DateService; +import fr.insee.pearljam.domain.campaign.service.dummy.FixedDateService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.Profile; +import org.springframework.boot.test.context.TestConfiguration; + +@TestConfiguration +@Profile("test") +public class DateServiceConfiguration { + + @Bean + @Primary + public DateService dateService() { + return new FixedDateService(); + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java index 8a2666f8..3d92ff1b 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java @@ -32,6 +32,7 @@ class CampaignServiceImplTest { private CampaignFakeRepository campaignRepository; private VisibilityFakeService visibilityService; private CampaignServiceImpl campaignService; + private CurrentDateService dateService = new CurrentDateService(); private final OrganizationUnit existingOrganizationUnit = new OrganizationUnit("OU-NORTH", "label-ou", OrganizationUnitType.LOCAL); private final Campaign existingCampaign = new Campaign( "CAMPAIGN-ID", @@ -82,7 +83,7 @@ void setup() { campaignService = new CampaignServiceImpl( campaignRepository, userRepository, surveyUnitRepository, organizationUnitRepository, messageRepository, - userService, utilsService, surveyUnitService, preferenceService, referentService, visibilityService); + userService, utilsService, surveyUnitService, preferenceService, referentService, visibilityService, dateService); } // TODO : handle referent diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/FixedDateService.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/FixedDateService.java new file mode 100644 index 00000000..bb0d8039 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/FixedDateService.java @@ -0,0 +1,11 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.domain.campaign.port.userside.DateService; + +public class FixedDateService implements DateService { + public static final long FIXED_TIMESTAMP = 1719324512000L; + @Override + public long getCurrentTimestamp() { + return FIXED_TIMESTAMP; + } +} From b00d4cee873515befd5ff581845aade253314d75 Mon Sep 17 00:00:00 2001 From: davdarras Date: Thu, 5 Sep 2024 10:16:30 +0200 Subject: [PATCH 19/48] feat: create communication requests when updating survey unit --- .../insee/pearljam/api/domain/SurveyUnit.java | 13 ----- .../impl/SurveyUnitUpdateServiceImpl.java | 21 ++++++- .../exception/ExceptionControllerAdvice.java | 10 ++-- ...ommunicationTemplateNotFoundException.java | 10 ++++ .../CommunicationRequestRepository.java | 15 +++++ .../CommunicationTemplateJpaRepository.java | 16 +++++ .../CommunicationRequestDaoAdapter.java | 41 +++++++++++++ .../entity/CommunicationRequestDB.java | 11 ++-- .../dto/SurveyUnitDetailDtoTest.java | 9 ++- .../SurveyUnitUpdateServiceImplTest.java | 58 ++++++++++--------- .../CommunicationRequestFakeRepository.java | 20 +++++++ .../entity/CommunicationRequestDBTest.java | 16 +++-- .../CommunicationRequestStatusDBTest.java | 4 +- 13 files changed, 185 insertions(+), 59 deletions(-) create mode 100644 src/main/java/fr/insee/pearljam/domain/exception/CommunicationTemplateNotFoundException.java create mode 100644 src/main/java/fr/insee/pearljam/domain/surveyunit/port/serverside/CommunicationRequestRepository.java create mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java create mode 100644 src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommunicationRequestDaoAdapter.java create mode 100644 src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationRequestFakeRepository.java diff --git a/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java b/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java index 08b41689..6f08a2a6 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java +++ b/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java @@ -243,19 +243,6 @@ public void updateComments(Set commentsToUpdate) { existingComments.addAll(commentsDBToUpdate); } - /** - * add a list of communication requests for a survey unit - * @param communicationRequestsToCreate the communication requests to add - */ - public void addCommunicationRequests(List communicationRequestsToCreate) { - Set newCommunicationsRequests = communicationRequestsToCreate.stream() - .map(newCommunicationRequest -> CommunicationRequestDB.fromModel(newCommunicationRequest, this)) - .collect(Collectors.toSet()); - - this.getCommunicationRequests() - .addAll(newCommunicationsRequests); - } - public Set getModelComments() { return CommentDB.toModel(this.getComments()); } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java index 0a151e90..134f9e47 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java @@ -9,6 +9,8 @@ import fr.insee.pearljam.domain.surveyunit.model.Identification; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; import fr.insee.pearljam.api.service.SurveyUnitUpdateService; +import fr.insee.pearljam.domain.surveyunit.port.serverside.CommunicationRequestRepository; +import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -22,6 +24,8 @@ @Slf4j public class SurveyUnitUpdateServiceImpl implements SurveyUnitUpdateService { + private final CommunicationRequestRepository communicationRequestRepository; + @Transactional @Override public void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto) { @@ -33,8 +37,21 @@ public void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitUpdateDto sur surveyUnit.updateComments(commentsToUpdate); } if(surveyUnitUpdateDto.communicationRequests() != null) { - List communicationRequests = CommunicationRequestCreateDto.toModel(surveyUnitUpdateDto.communicationRequests()); - surveyUnit.addCommunicationRequests(communicationRequests); + List communicationRequestsToCreate = CommunicationRequestCreateDto.toModel(surveyUnitUpdateDto.communicationRequests()); + Set currentCommunicationRequests = surveyUnit.getCommunicationRequests(); + List newCommunicationsRequests = communicationRequestsToCreate.stream() + .filter(newCommunicationRequest -> { + for (CommunicationRequestDB currentCommunicationRequest : currentCommunicationRequests) { + // if survey unit has already this communication request, skip it + if(currentCommunicationRequest.getCommunicationTemplate().getId() + .equals(newCommunicationRequest.communicationTemplateId())) { + return false; + } + } + return true; + }) + .toList(); + communicationRequestRepository.addCommunicationRequests(surveyUnit, newCommunicationsRequests); } Identification identification = IdentificationDto.toModel(surveyUnitUpdateDto.identification()); diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java index 6cd11690..0b7b1e1b 100644 --- a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java +++ b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java @@ -3,10 +3,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import fr.insee.pearljam.api.exception.NoOrganizationUnitException; -import fr.insee.pearljam.domain.exception.CampaignOnGoingException; -import fr.insee.pearljam.domain.exception.EntityAlreadyExistException; -import fr.insee.pearljam.domain.exception.EntityNotFoundException; -import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; +import fr.insee.pearljam.domain.exception.*; import fr.insee.pearljam.infrastructure.mail.exception.SendMailException; import jakarta.validation.ConstraintViolationException; import lombok.extern.slf4j.Slf4j; @@ -128,6 +125,11 @@ public ResponseEntity exceptions(NoOrganizationUnitException e, WebReq return generateResponseError(e, HttpStatus.BAD_REQUEST, request); } + @ExceptionHandler(CommunicationTemplateNotFoundException.class) + public ResponseEntity exceptions(CommunicationTemplateNotFoundException e, WebRequest request) { + return generateResponseError(e, HttpStatus.NOT_FOUND, request); + } + @ExceptionHandler(VisibilityHasInvalidDatesException.class) public ResponseEntity exceptions(VisibilityHasInvalidDatesException e, WebRequest request) { return generateResponseError(e, HttpStatus.CONFLICT, request); diff --git a/src/main/java/fr/insee/pearljam/domain/exception/CommunicationTemplateNotFoundException.java b/src/main/java/fr/insee/pearljam/domain/exception/CommunicationTemplateNotFoundException.java new file mode 100644 index 00000000..7d1c60b5 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/exception/CommunicationTemplateNotFoundException.java @@ -0,0 +1,10 @@ +package fr.insee.pearljam.domain.exception; + +public class CommunicationTemplateNotFoundException extends RuntimeException { + + public static final String MESSAGE = "Communication template not found"; + + public CommunicationTemplateNotFoundException() { + super(MESSAGE); + } +} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/port/serverside/CommunicationRequestRepository.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/port/serverside/CommunicationRequestRepository.java new file mode 100644 index 00000000..fdd5aa0b --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/port/serverside/CommunicationRequestRepository.java @@ -0,0 +1,15 @@ +package fr.insee.pearljam.domain.surveyunit.port.serverside; + +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; + +import java.util.List; + +public interface CommunicationRequestRepository { + /** + * Add communication requests to a survey unit + * @param surveyUnit survey unit to update + * @param communicationRequests communication requests to add + */ + void addCommunicationRequests(SurveyUnit surveyUnit, List communicationRequests); +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java new file mode 100644 index 00000000..d2131301 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java @@ -0,0 +1,16 @@ +package fr.insee.pearljam.infrastructure.campaign.jpa; + +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.Optional; + +public interface CommunicationTemplateJpaRepository extends JpaRepository { + + @Query(""" + SELECT c FROM CommunicationTemplateDB c + WHERE c.id = ?1 + AND c.campaign.id = ?2""") + Optional findCommunicationTemplate(Long communicationTemplateId, String campaignId); +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommunicationRequestDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommunicationRequestDaoAdapter.java new file mode 100644 index 00000000..2936446a --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommunicationRequestDaoAdapter.java @@ -0,0 +1,41 @@ +package fr.insee.pearljam.infrastructure.surveyunit.adapter; + +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.exception.CommunicationTemplateNotFoundException; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; +import fr.insee.pearljam.domain.surveyunit.port.serverside.CommunicationRequestRepository; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; +import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationTemplateJpaRepository; +import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; +import fr.insee.pearljam.api.repository.SurveyUnitRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +@Repository +@RequiredArgsConstructor +public class CommunicationRequestDaoAdapter implements CommunicationRequestRepository { + private final SurveyUnitRepository surveyUnitRepository; + private final CommunicationTemplateJpaRepository communicationTemplateRepository; + + @Override + @Transactional + public void addCommunicationRequests(SurveyUnit surveyUnit, List communicationRequests) { + List newCommunicationRequests = new ArrayList<>(); + for(CommunicationRequest communicationRequest: communicationRequests) { + CommunicationTemplateDB communicationTemplate = communicationTemplateRepository + .findCommunicationTemplate(communicationRequest.communicationTemplateId(), surveyUnit.getCampaign().getId()) + .orElseThrow(CommunicationTemplateNotFoundException::new); + CommunicationRequestDB newCommunicationRequest = CommunicationRequestDB.fromModel(communicationRequest, surveyUnit, communicationTemplate); + newCommunicationRequests.add(newCommunicationRequest); + } + + Set currentCommunicationRequests = surveyUnit.getCommunicationRequests(); + currentCommunicationRequests.addAll(newCommunicationRequests); + surveyUnitRepository.save(surveyUnit); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java index 9b91e54c..89015055 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java @@ -8,6 +8,7 @@ import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.domain.surveyunit.model.communication.*; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -37,8 +38,8 @@ public class CommunicationRequestDB implements Serializable { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @Column - private Long communicationTemplateId; + @ManyToOne(fetch = FetchType.LAZY) + private CommunicationTemplateDB communicationTemplate; @Enumerated(EnumType.STRING) @Column @@ -60,10 +61,10 @@ public class CommunicationRequestDB implements Serializable { * @param request model object * @return entity object */ - public static CommunicationRequestDB fromModel(CommunicationRequest request, SurveyUnit surveyUnit) { + public static CommunicationRequestDB fromModel(CommunicationRequest request, SurveyUnit surveyUnit, CommunicationTemplateDB communicationTemplate) { List status = new ArrayList<>(); - CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(request.id(), request.communicationTemplateId(), + CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(request.id(), communicationTemplate, request.reason(), request.emitter(), surveyUnit, status); if(request.status() != null) { @@ -87,7 +88,7 @@ public static CommunicationRequest toModel(CommunicationRequestDB request) { .map(CommunicationRequestStatusDB::toModel).toList(); } - return new CommunicationRequest(request.getId(), request.getCommunicationTemplateId(), + return new CommunicationRequest(request.getId(), request.getCommunicationTemplate().getId(), request.getReason(), request.getEmitter(), status); } diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java index 0250cdeb..b09784a7 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java @@ -5,6 +5,7 @@ import fr.insee.pearljam.domain.surveyunit.model.CommentType; import fr.insee.pearljam.domain.surveyunit.model.communication.*; import fr.insee.pearljam.domain.surveyunit.model.question.*; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommentDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestStatusDB; @@ -85,10 +86,14 @@ void testCreateCommunicationRequests01() { new CommunicationRequestStatusDB(4L, 123345678912L, CommunicationStatusType.CANCELLED, null) ); - communicationRequestDBs.add(new CommunicationRequestDB(10L, 1L, + CommunicationTemplateDB communicationTemplate1 = new CommunicationTemplateDB(1L, null, null, null, null); + CommunicationTemplateDB communicationTemplate2 = new CommunicationTemplateDB(2L, null, null, null, null); + + + communicationRequestDBs.add(new CommunicationRequestDB(10L, communicationTemplate1, CommunicationRequestReason.UNREACHABLE, CommunicationRequestEmitter.INTERVIEWER, surveyUnit, status1)); - communicationRequestDBs.add(new CommunicationRequestDB(11L, 2L, + communicationRequestDBs.add(new CommunicationRequestDB(11L, communicationTemplate2, CommunicationRequestReason.REFUSAL, CommunicationRequestEmitter.TOOL, surveyUnit, status2)); surveyUnit.setCommunicationRequests(communicationRequestDBs); diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java index 8bc7c8f8..ac632a5d 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java @@ -6,6 +6,8 @@ import fr.insee.pearljam.domain.surveyunit.model.CommentType; import fr.insee.pearljam.domain.surveyunit.model.communication.*; import fr.insee.pearljam.domain.surveyunit.model.question.*; +import fr.insee.pearljam.domain.surveyunit.service.dummy.CommunicationRequestFakeRepository; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommentDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.IdentificationDB; @@ -21,17 +23,22 @@ import static org.assertj.core.api.Assertions.tuple; class SurveyUnitUpdateServiceImplTest { + private CommunicationRequestFakeRepository communicationRequestFakeRepository; private SurveyUnitUpdateServiceImpl surveyUnitService; private SurveyUnit surveyUnit; private SurveyUnitUpdateDto surveyUnitDto; + private CommunicationTemplateDB communicationTemplate; @BeforeEach void setup() { - surveyUnitService = new SurveyUnitUpdateServiceImpl(); + communicationRequestFakeRepository = new CommunicationRequestFakeRepository(); + surveyUnitService = new SurveyUnitUpdateServiceImpl(communicationRequestFakeRepository); surveyUnit = new SurveyUnit("id", true, true, null, null, null, null, null, null); + + communicationTemplate = new CommunicationTemplateDB(3L, null, null, null, null); Set communicationRequestDBs = new HashSet<>(); - communicationRequestDBs.add(new CommunicationRequestDB(10L, 3L, + communicationRequestDBs.add(new CommunicationRequestDB(10L, communicationTemplate, CommunicationRequestReason.REFUSAL, CommunicationRequestEmitter.TOOL, surveyUnit, null)); @@ -51,16 +58,15 @@ void testUpdateCommunication01() { surveyUnitDto = createSurveyUnitDto(null, null, communicationRequests); surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); - Set communicationRequestResults = surveyUnit.getCommunicationRequests(); + List communicationRequestResults = communicationRequestFakeRepository.getCommunicationRequestsAdded(); assertThat(communicationRequestResults) - .hasSize(3) - .extracting(CommunicationRequestDB::getId, - CommunicationRequestDB::getCommunicationTemplateId, - CommunicationRequestDB::getReason, - CommunicationRequestDB::getEmitter, - CommunicationRequestDB::getSurveyUnit, - communicationRequestDB -> communicationRequestDB.getStatus() == null ? null : communicationRequestDB.getStatus().stream() - .map(status -> tuple(status.getId(), status.getDate(), status.getStatus())) + .hasSize(2) + .extracting(CommunicationRequest::id, + CommunicationRequest::communicationTemplateId, + CommunicationRequest::reason, + CommunicationRequest::emitter, + communicationRequest -> communicationRequest.status().stream() + .map(status -> tuple(status.id(), status.date(), status.status())) .toList() ) .containsExactlyInAnyOrder( @@ -68,30 +74,30 @@ void testUpdateCommunication01() { 1L, CommunicationRequestReason.UNREACHABLE, CommunicationRequestEmitter.INTERVIEWER, - surveyUnit, List.of(tuple(null, 12345678910L, CommunicationStatusType.INITIATED)) ), tuple(null, 2L, CommunicationRequestReason.REFUSAL, CommunicationRequestEmitter.INTERVIEWER, - surveyUnit, List.of(tuple(null, 1234567891011L, CommunicationStatusType.INITIATED)) - ), - tuple(10L, - 3L, - CommunicationRequestReason.REFUSAL, - CommunicationRequestEmitter.TOOL, - surveyUnit, - null) + ) ); + } + + @Test + @DisplayName("Should not add communication requests with duplicate communication configuration") + void testUpdateCommunication02() { + List communicationRequests = List.of( + new CommunicationRequestCreateDto(communicationTemplate.getId(), 12345678910L, + CommunicationRequestReason.UNREACHABLE) + ); + + surveyUnitDto = createSurveyUnitDto(null, null, communicationRequests); + surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); - // Check that CommunicationRequestStatusDB has the correct parent - communicationRequestResults.forEach(request -> { - if (request.getStatus() != null) { - request.getStatus().forEach(status -> assertThat(status.getCommunicationRequest()).isEqualTo(request)); - } - }); + List communicationRequestResults = communicationRequestFakeRepository.getCommunicationRequestsAdded(); + assertThat(communicationRequestResults).isEmpty(); } @Test diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationRequestFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationRequestFakeRepository.java new file mode 100644 index 00000000..cbb12925 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationRequestFakeRepository.java @@ -0,0 +1,20 @@ +package fr.insee.pearljam.domain.surveyunit.service.dummy; + +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; +import fr.insee.pearljam.domain.surveyunit.port.serverside.CommunicationRequestRepository; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +import java.util.List; + +@RequiredArgsConstructor +public class CommunicationRequestFakeRepository implements CommunicationRequestRepository { + @Getter + private List communicationRequestsAdded; + + @Override + public void addCommunicationRequests(SurveyUnit surveyUnit, List communicationRequests) { + communicationRequestsAdded = communicationRequests; + } +} diff --git a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java index 75102439..4faf5746 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java @@ -2,6 +2,7 @@ import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.domain.surveyunit.model.communication.*; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -14,11 +15,14 @@ class CommunicationRequestDBTest { private SurveyUnit surveyUnit; + private CommunicationTemplateDB communicationTemplate; @BeforeEach void setup() { surveyUnit = new SurveyUnit(); surveyUnit.setId("su-id"); + communicationTemplate = new CommunicationTemplateDB(); + communicationTemplate.setId(1L); } @Test @@ -26,9 +30,9 @@ void setup() { void testToModel01() { List statusDB = List.of( new CommunicationRequestStatusDB(null, 1233456789L, CommunicationStatusType.INITIATED, null), - new CommunicationRequestStatusDB(2L, 123345678910L, CommunicationStatusType.FAILED, null) + new CommunicationRequestStatusDB(communicationTemplate.getId(), 123345678910L, CommunicationStatusType.FAILED, null) ); - CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(1L, 2L, + CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(1L, communicationTemplate, CommunicationRequestReason.UNREACHABLE, CommunicationRequestEmitter.INTERVIEWER, surveyUnit, @@ -36,7 +40,7 @@ void testToModel01() { CommunicationRequest communicationRequest = CommunicationRequestDB.toModel(communicationRequestDB); assertThat(communicationRequest.id()).isEqualTo(communicationRequestDB.getId()); - assertThat(communicationRequest.communicationTemplateId()).isEqualTo(communicationRequestDB.getCommunicationTemplateId()); + assertThat(communicationRequest.communicationTemplateId()).isEqualTo(communicationRequestDB.getCommunicationTemplate().getId()); assertThat(communicationRequest.reason()).isEqualTo(communicationRequestDB.getReason()); List status = statusDB.stream() .map(CommunicationRequestStatusDB::toModel) @@ -53,14 +57,14 @@ void testFromModel01() { ); CommunicationRequest communicationRequest = new CommunicationRequest(1L, - 2L, + communicationTemplate.getId(), CommunicationRequestReason.UNREACHABLE, CommunicationRequestEmitter.INTERVIEWER, status); - CommunicationRequestDB communicationRequestDB = CommunicationRequestDB.fromModel(communicationRequest, surveyUnit); + CommunicationRequestDB communicationRequestDB = CommunicationRequestDB.fromModel(communicationRequest, surveyUnit, communicationTemplate); assertThat(communicationRequestDB.getId()).isEqualTo(communicationRequest.id()); - assertThat(communicationRequestDB.getCommunicationTemplateId()).isEqualTo(communicationRequest.communicationTemplateId()); + assertThat(communicationRequestDB.getCommunicationTemplate().getId()).isEqualTo(communicationRequest.communicationTemplateId()); assertThat(communicationRequestDB.getReason()).isEqualTo(communicationRequest.reason()); assertThat(communicationRequestDB.getStatus()) .extracting(CommunicationRequestStatusDB::getId, diff --git a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java index 123111a8..848fa601 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java @@ -1,6 +1,7 @@ package fr.insee.pearljam.infrastructure.surveyunit.entity; import fr.insee.pearljam.domain.surveyunit.model.communication.*; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -21,7 +22,8 @@ void testToModel01() { @Test @DisplayName("Should return entity object") void testFromModel01() { - CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(null, 1L, + CommunicationTemplateDB communicationTemplate = new CommunicationTemplateDB(1L, null, null, null, null); + CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(null, communicationTemplate, CommunicationRequestReason.UNREACHABLE, CommunicationRequestEmitter.INTERVIEWER, null, null); CommunicationRequestStatus communicationRequestStatus = new CommunicationRequestStatus(1L, 123456789L, CommunicationStatusType.INITIATED); From e9100b8772ac1ba071f691c4c7ce8ade5ef29a04 Mon Sep 17 00:00:00 2001 From: davdarras Date: Thu, 5 Sep 2024 11:02:56 +0200 Subject: [PATCH 20/48] fix: handle better data structure - add foreign key for communication template - reinit auto increment sequences in tests - fix SQL demo data - add dataset for communications --- .../entity/CommunicationTemplateDB.java | 1 - ...xml => 540_add_communication_template.xml} | 0 .../540_alter_communication_request.xml | 20 --------- .../541_alter_communication_request.xml | 27 ++++++++++++ .../resources/db/dataset/init-demo-data.sql | 30 ++++++++++++-- .../resources/db/dataset/reinit-test-data.sql | 41 +++++++++++++++++++ src/main/resources/db/master.xml | 8 ++-- 7 files changed, 98 insertions(+), 29 deletions(-) rename src/main/resources/db/changelog/{541_add_communication_template.xml => 540_add_communication_template.xml} (100%) delete mode 100644 src/main/resources/db/changelog/540_alter_communication_request.xml create mode 100644 src/main/resources/db/changelog/541_alter_communication_request.xml diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java index 842ee1ee..7b0919f0 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java @@ -42,7 +42,6 @@ public class CommunicationTemplateDB implements Serializable { private CommunicationType type; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "campaign_id", insertable = false, updatable = false) private Campaign campaign; public static List toModel(List communicationTemplatesDB) { diff --git a/src/main/resources/db/changelog/541_add_communication_template.xml b/src/main/resources/db/changelog/540_add_communication_template.xml similarity index 100% rename from src/main/resources/db/changelog/541_add_communication_template.xml rename to src/main/resources/db/changelog/540_add_communication_template.xml diff --git a/src/main/resources/db/changelog/540_alter_communication_request.xml b/src/main/resources/db/changelog/540_alter_communication_request.xml deleted file mode 100644 index 0a737ebc..00000000 --- a/src/main/resources/db/changelog/540_alter_communication_request.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/db/changelog/541_alter_communication_request.xml b/src/main/resources/db/changelog/541_alter_communication_request.xml new file mode 100644 index 00000000..9e99a7b7 --- /dev/null +++ b/src/main/resources/db/changelog/541_alter_communication_request.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/db/dataset/init-demo-data.sql b/src/main/resources/db/dataset/init-demo-data.sql index c2a8cbce..a9436d85 100644 --- a/src/main/resources/db/dataset/init-demo-data.sql +++ b/src/main/resources/db/dataset/init-demo-data.sql @@ -9,7 +9,7 @@ INSERT INTO public.address (dtype, l1, l2, l3, l4, l5, l6, l7, elevator, buildin ('InseeAddress', 'Louise Walker' ,'','','6 impasse du lac' ,'','38200 Vienne' ,'France', false, null, null, null, null, false), ('InseeAddress', 'Anthony Bennett' ,'','','7 avenue de la Liberté' ,'','62000 Arras' ,'France', false, null, null, null, null, false), ('InseeAddress', 'Christopher Lewis' ,'','','8 route du moulin' ,'','35000 Rennes' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Laurent Neville' ,'','','5 route du sapin' ,'','35000 Rennes' ,'France', false, null, null, null, null, false) + ('InseeAddress', 'Laurent Neville' ,'','','5 route du sapin' ,'','35000 Rennes' ,'France', false, null, null, null, null, false), ('InseeAddress', 'Alain Thé' ,'','','7 rue des Infusions' ,'','75001 Paris' ,'France', false, null, null, null, null, false), ('InseeAddress', 'Brie Savarin' ,'','','15 avenue des Fromages' ,'','69002 Lyon' ,'France', false, null, null, null, null, false), ('InseeAddress', 'Cécile Houte' ,'','','8 impasse des Aromates' ,'','13003 Marseille' ,'France', false, null, null, null, null, false), @@ -178,11 +178,11 @@ INSERT INTO public.person (email, favorite_email, first_name, last_name, birthda ('test@test.com', TRUE, 'Harry', 'Cover', 11111111, 1, FALSE, '25'), ('test@test.com', TRUE, 'Ella', 'Gance', 11111111, 0, FALSE, '25'), ('test@test.com', TRUE, 'Jean', 'Neige', 11111111, 0, FALSE, '26'), - ('test@test.com', TRUE, 'Phil', 'Harmonie', 11111111, 0, FALSE, '28') + ('test@test.com', TRUE, 'Phil', 'Harmonie', 11111111, 0, FALSE, '28'), ('test@test.com', TRUE, 'Alain', 'Thé', 11111111, 0, TRUE, '25'), ('test@test.com', TRUE, 'Brie', 'Savarin', 11111111, 1, TRUE, '26'), ('test@test.com', TRUE, 'Cécile', 'Houte', 11111111, 0, TRUE, '27'), - ('test@test.com', TRUE, 'Dan', 'Tifrice', 11111111, 1 TRUE, '28'), + ('test@test.com', TRUE, 'Dan', 'Tifrice', 11111111, 1, TRUE, '28'), ('test@test.com', TRUE, 'Émile', 'Pates', 11111111, 1, TRUE, '29'), ('test@test.com', TRUE, 'François', 'Appétit', 11111111, 1, TRUE, '30'), ('test@test.com', TRUE, 'Gérard', 'Dine', 11111111, 0, TRUE, '31'), @@ -260,4 +260,26 @@ INSERT INTO public.identification (survey_unit_id, identification,access,situati ('11', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), ('21', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), ('25', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), - ('30', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'); \ No newline at end of file + ('30', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'); + +INSERT INTO public.communication_template (meshuggah_id, medium, type, campaign_id) VALUES + ('mesh1', 'EMAIL', 'REMINDER', 'SIMPSONS2020X00'), + ('mesh2', 'LETTER', 'NOTICE', 'SIMPSONS2020X00'), + ('mesh3', 'EMAIL', 'REMINDER', 'VQS2021X00'), + ('mesh4', 'LETTER', 'NOTICE', 'VQS2021X00'), + ('mesh5', 'EMAIL', 'NOTICE', 'VQS2021X00'); + +INSERT INTO public.communication_request (survey_unit_id, emitter, reason, communication_template_id) VALUES + ('11', 'INTERVIEWER', 'REFUSAL', 1), + ('11', 'INTERVIEWER', 'UNREACHABLE', 2), + ('20', 'INTERVIEWER', 'REFUSAL', 3), + ('20', 'INTERVIEWER', 'UNREACHABLE', 4); + +INSERT INTO public.communication_request_status (communication_request_id, status, date) VALUES + (1, 'INITIATED', 1721903754305), + (1, 'READY', 1721903755305), + (1, 'SUBMITTED', 1721903756305), + (2, 'INITIATED', 1721903754305), + (2, 'READY', 1721903756310), + (3, 'INITIATED', 1721903754205), + (4, 'INITIATED', 1721903754205); \ No newline at end of file diff --git a/src/main/resources/db/dataset/reinit-test-data.sql b/src/main/resources/db/dataset/reinit-test-data.sql index 4e526ba2..8150428e 100644 --- a/src/main/resources/db/dataset/reinit-test-data.sql +++ b/src/main/resources/db/dataset/reinit-test-data.sql @@ -1,6 +1,9 @@ --changeset davdarras:reset-data context:test SET REFERENTIAL_INTEGRITY FALSE; +TRUNCATE TABLE public.communication_request_status; +TRUNCATE TABLE public.communication_request; +TRUNCATE TABLE public.communication_template; TRUNCATE TABLE public.campaign_message_recipient; TRUNCATE TABLE public.contact_attempt; TRUNCATE TABLE public.message_status; @@ -24,6 +27,22 @@ TRUNCATE TABLE public.closing_cause; TRUNCATE TABLE public.organization_unit; TRUNCATE TABLE public.address; +ALTER TABLE public.communication_request_status ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.communication_request ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.communication_template ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.contact_attempt ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.referent ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.message ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.sample_identifier ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.identification ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.person ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.phone_number ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.state ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.contact_outcome ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.comment ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.closing_cause ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.address ALTER COLUMN id RESTART WITH 1; + --changeset davdarras:init-data context:test INSERT INTO public.address (dtype, l1, l2, l3, l4, l5, l6, l7, elevator, building, floor, door, staircase, city_priority_district) VALUES @@ -180,4 +199,26 @@ INSERT INTO public.identification (survey_unit_id, identification,access,situati ('11', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), ('21', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'); +INSERT INTO public.communication_template (meshuggah_id, medium, type, campaign_id) VALUES + ('mesh1', 'EMAIL', 'REMINDER', 'SIMPSONS2020X00'), + ('mesh2', 'LETTER', 'NOTICE', 'SIMPSONS2020X00'), + ('mesh3', 'EMAIL', 'REMINDER', 'VQS2021X00'), + ('mesh4', 'LETTER', 'NOTICE', 'VQS2021X00'), + ('mesh5', 'EMAIL', 'NOTICE', 'VQS2021X00'); + +INSERT INTO public.communication_request (survey_unit_id, emitter, reason, communication_template_id) VALUES + ('11', 'INTERVIEWER', 'REFUSAL', 1), + ('11', 'INTERVIEWER', 'UNREACHABLE', 2), + ('20', 'INTERVIEWER', 'REFUSAL', 3), + ('20', 'INTERVIEWER', 'UNREACHABLE', 4); + +INSERT INTO public.communication_request_status (communication_request_id, status, date) VALUES + (1, 'INITIATED', 1721903754305), + (1, 'READY', 1721903755305), + (1, 'SUBMITTED', 1721903756305), + (2, 'INITIATED', 1721903754305), + (2, 'READY', 1721903756310), + (3, 'INITIATED', 1721903754205), + (4, 'INITIATED', 1721903754205); + SET REFERENTIAL_INTEGRITY TRUE; \ No newline at end of file diff --git a/src/main/resources/db/master.xml b/src/main/resources/db/master.xml index 384bd09a..e2ea6e21 100644 --- a/src/main/resources/db/master.xml +++ b/src/main/resources/db/master.xml @@ -42,10 +42,10 @@ - - - - + + + + \ No newline at end of file From 3979a8789150f91135fd96858a236cc43945265f Mon Sep 17 00:00:00 2001 From: davdarras Date: Fri, 6 Sep 2024 10:44:24 +0200 Subject: [PATCH 21/48] test: integration tests for communication configuration/requests - refactor and move tests from TestKeyCloakAuth - add configuration/requests checks - add IT to jacoco cover code --- pom.xml | 8 + .../dto/surveyunit/SurveyUnitDetailDto.java | 3 - .../api/authKeycloak/TestAuthKeyCloak.java | 131 +----- .../integration/campaign/CampaignIT.java | 39 +- .../integration/surveyunit/SurveyUnitIT.java | 442 ++++++++++++++++++ 5 files changed, 498 insertions(+), 125 deletions(-) diff --git a/pom.xml b/pom.xml index f3cde3ac..390262fb 100644 --- a/pom.xml +++ b/pom.xml @@ -251,6 +251,14 @@ org.apache.maven.plugins maven-surefire-plugin 3.2.5 + + + **/TestAuthKeyCloak + **/TestNoAuth + **/*Test + **/*IT + + diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java index 29c82cba..e4d15e69 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java @@ -4,7 +4,6 @@ import java.util.List; import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestResponseDto; -import jakarta.validation.Valid; import lombok.Data; import com.fasterxml.jackson.annotation.JsonInclude; @@ -30,14 +29,12 @@ public class SurveyUnitDetailDto { private Boolean priority; private Boolean move; private String campaign; - @Valid private List comments; private SampleIdentifiersDto sampleIdentifiers; private List states; private List contactAttempts; private ContactOutcomeDto contactOutcome; private IdentificationDto identification; - @Valid private List communicationRequests; public SurveyUnitDetailDto() { diff --git a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java index 2728c3fb..ffdf31b5 100644 --- a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java +++ b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java @@ -7,8 +7,6 @@ import fr.insee.pearljam.api.controller.WsText; import fr.insee.pearljam.api.domain.*; import fr.insee.pearljam.api.dto.address.AddressDto; -import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; -import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerContextDto; import fr.insee.pearljam.api.dto.message.MessageDto; import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitContextDto; @@ -16,9 +14,7 @@ import fr.insee.pearljam.api.dto.person.PersonDto; import fr.insee.pearljam.api.dto.phonenumber.PhoneNumberDto; import fr.insee.pearljam.api.dto.sampleidentifier.SampleIdentifiersDto; -import fr.insee.pearljam.api.dto.state.StateDto; import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitContextDto; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDetailDto; import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitInterviewerLinkDto; import fr.insee.pearljam.api.dto.user.UserContextDto; import fr.insee.pearljam.api.dto.user.UserDto; @@ -28,6 +24,7 @@ import fr.insee.pearljam.api.surveyunit.dto.CommentDto; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import fr.insee.pearljam.api.utils.MockMvcTestUtils; +import fr.insee.pearljam.api.utils.ScriptConstants; import fr.insee.pearljam.config.DateServiceConfiguration; import fr.insee.pearljam.domain.surveyunit.model.CommentType; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; @@ -45,6 +42,7 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestConstructor; +import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.client.ExpectedCount; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.servlet.MockMvc; @@ -62,6 +60,7 @@ import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; @@ -506,53 +505,6 @@ void testGetCampaignInterviewerStateCountNotFoundIntw() throws Exception { /* SurveyUnitController */ - /** - * Test that the GET endpoint "api/survey-unit/{id}" - * return 200. - * - * @throws InterruptedException - * @throws JSONException - */ - @Test - @Order(11) - void testGetSurveyUnitDetail() throws Exception { - String personJsonPath = "$.persons.[?(@.firstName == 'Christine')].%s"; - - mockMvc.perform(get("/api/survey-unit/11") - .with(authentication(INTERVIEWER)) - .accept(MediaType.APPLICATION_JSON)) - .andExpectAll(status().isOk(), - jsonPath("$.id").value("11"), - jsonPath("$.priority", equalTo(true)), - checkJsonPath(personJsonPath, "lastName", "Aguilar"), - checkJsonPath(personJsonPath, "favoriteEmail", true), - checkJsonPath(personJsonPath, "privileged", false), - checkJsonPath(personJsonPath, "birthdate", 11111111L), - checkJsonPath(personJsonPath, "phoneNumbers[0].number", "+33677542802"), - jsonPath("$.address.l1", equalTo("Ted Farmer")), - jsonPath("$.address.l2", equalTo("")), - jsonPath("$.address.l3", equalTo("")), - jsonPath("$.address.l4", equalTo("1 rue de la gare")), - jsonPath("$.address.l5", equalTo("")), - jsonPath("$.address.l6", equalTo("29270 Carhaix")), - jsonPath("$.address.l7", equalTo("France")), - jsonPath("$.address.elevator", equalTo(true)), - jsonPath("$.address.building", equalTo("Bat. C")), - jsonPath("$.address.floor", equalTo("Etg 4")), - jsonPath("$.address.door", equalTo("Porte 48")), - jsonPath("$.address.staircase", equalTo("Escalier B")), - jsonPath("$.address.cityPriorityDistrict", equalTo(true)), - jsonPath("$.campaign", equalTo("SIMPSONS2020X00")), - jsonPath("$.contactOutcome").doesNotHaveJsonPath(), - jsonPath("$.comments", empty()), - jsonPath("$.states[0].type", equalTo("VIN")), - jsonPath("$.contactAttempts", empty()), - jsonPath("$.identification.identification", equalTo("IDENTIFIED")), - jsonPath("$.identification.access", equalTo("ACC")), - jsonPath("$.identification.situation", equalTo("ORDINARY")), - jsonPath("$.identification.category", equalTo("PRIMARY")), - jsonPath("$.identification.occupant", equalTo("IDENTIFIED"))); - } /** * Test that the GET endpoint "api/survey-unit/{id}" @@ -570,71 +522,6 @@ void testGetSurveyUnitDetailNotFound() throws Exception { .andExpect(status().isNotFound()); } - /** - * Test that the PUT endpoint "api/survey-unit/{id}" - * return 200 - * - * @throws Exception - */ - @Test - @Order(14) - void testPutSurveyUnitDetail() throws Exception { - SurveyUnitDetailDto surveyUnitDetailDto = surveyUnitService.getSurveyUnitDetail("GUEST", "20"); - surveyUnitDetailDto.getPersons().get(0).getPhoneNumbers().get(0).setNumber("test"); - surveyUnitDetailDto.getAddress().setL1("test"); - surveyUnitDetailDto.getAddress().setL2("test"); - surveyUnitDetailDto.getAddress().setL3("test"); - surveyUnitDetailDto.getAddress().setL4("test"); - surveyUnitDetailDto.getAddress().setL5("test"); - surveyUnitDetailDto.getAddress().setL6("test"); - surveyUnitDetailDto.getAddress().setL7("test"); - surveyUnitDetailDto.getAddress().setBuilding("testBuilding"); - surveyUnitDetailDto.getAddress().setDoor("testDoor"); - surveyUnitDetailDto.getAddress().setFloor("testFloor"); - surveyUnitDetailDto.getAddress().setStaircase("testStaircase"); - surveyUnitDetailDto.getAddress().setElevator(true); - surveyUnitDetailDto.getAddress().setCityPriorityDistrict(true); - surveyUnitDetailDto.setComments(List.of(new CommentDto(CommentType.INTERVIEWER, "test"), - new CommentDto(CommentType.MANAGEMENT, "test"))); - surveyUnitDetailDto.setStates(List.of(new StateDto(1L, 1590504459838L, StateType.NNS))); - surveyUnitDetailDto.setContactAttempts(List.of(new ContactAttemptDto(1589268626000L, Status.NOC, Medium.TEL), - new ContactAttemptDto(1589268800000L, Status.INA, Medium.TEL))); - surveyUnitDetailDto.setContactOutcome(new ContactOutcomeDto(1589268626000L, ContactOutcomeType.IMP, 2)); - - mockMvc.perform(put("/api/survey-unit/20") - .with(authentication(INTERVIEWER)) - .accept(MediaType.APPLICATION_JSON) - .content(asJsonString(surveyUnitDetailDto)) - .contentType(MediaType.APPLICATION_JSON)) - .andExpectAll( - status().isOk(), - jsonPath("$.id", equalTo("20")), - jsonPath("$.persons[0].phoneNumbers[0].number", equalTo("test")), - jsonPath("$.address.l1", equalTo("test")), - jsonPath("$.address.l2", equalTo("test")), - jsonPath("$.address.l3", equalTo("test")), - jsonPath("$.address.l4", equalTo("test")), - jsonPath("$.address.l5", equalTo("test")), - jsonPath("$.address.l6", equalTo("test")), - jsonPath("$.address.l7", equalTo("test")), - jsonPath("$.address.building", equalTo("testBuilding")), - jsonPath("$.address.door", equalTo("testDoor")), - jsonPath("$.address.floor", equalTo("testFloor")), - jsonPath("$.address.staircase", equalTo("testStaircase")), - jsonPath("$.address.elevator", equalTo(true)), - jsonPath("$.address.cityPriorityDistrict", equalTo(true)), - jsonPath("$.contactOutcome.type", equalTo(ContactOutcomeType.IMP.toString())), - jsonPath("$.contactOutcome.date", equalTo(Long.valueOf(1589268626000L))), - jsonPath("$.contactOutcome.totalNumberOfContactAttempts", is(2)), - jsonPath("$.comments[1].value", equalTo("test")), - jsonPath("comments[1].type", - is(oneOf(CommentType.MANAGEMENT.toString(), CommentType.INTERVIEWER.toString()))), - jsonPath("contactAttempts[1].status", is(oneOf(Status.NOC.toString(), Status.INA.toString()))) - - ); - - } - /** * Test that the PUT endpoint "api/survey-unit/{id}/state/{state}" * return 200 @@ -643,6 +530,7 @@ void testPutSurveyUnitDetail() throws Exception { */ @Test @Order(15) + @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) void testPutSurveyUnitState() throws Exception { mockMvc.perform(put("/api/survey-unit/12/state/WFT") .with(authentication(LOCAL_USER)) @@ -731,8 +619,8 @@ void testGetCampaignInterviewerClosingCauseCount() throws Exception { .with(authentication(LOCAL_USER)) .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk(), - jsonPath("$.npaCount").value("1"), - jsonPath("$.npiCount").value("0"), + jsonPath("$.npaCount").value("0"), + jsonPath("$.npiCount").value("1"), jsonPath("$.rowCount").value("0"), jsonPath("$.npxCount").value("0"), jsonPath("$.total").value("2")); @@ -1072,7 +960,6 @@ void testGetInterviewer() throws Exception { * @throws InterruptedException */ @Test - @Disabled("Need Clock injection refactor") @Order(45) void testGetInterviewerRelatedCampaigns() throws Exception { mockMvc.perform(get("/api/interviewer/INTW1/campaigns") @@ -1080,8 +967,8 @@ void testGetInterviewerRelatedCampaigns() throws Exception { .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), - jsonPath("$.[?(@.id == 'SIMPSONS2020X00')").exists(), - jsonPath("$.[?(@.id == 'SIMPSONS2020X00' ).label").value("Survey on the Simpsons tv show 2020"), + jsonPath("$.[?(@.id == 'SIMPSONS2020X00')]").exists(), + jsonPath("$.[?(@.id == 'SIMPSONS2020X00')].label").value("Survey on the Simpsons tv show 2020"), expectValidManagementStartDate(), expectValidEndDate()); } @@ -1888,6 +1775,7 @@ void testDeleteSurveyUnitNotExist() throws Exception { @Test @Order(202) + @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) void testDeleteCampaign() throws Exception { mockMvc.perform(delete("/api/campaign/XCLOSEDX00") .with(authentication(ADMIN)) @@ -1945,6 +1833,7 @@ void testDeleteUserNotExist() throws Exception { @Test @Order(206) + @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) void testDeleteOrganizationUnit() throws Exception { // Delete all Survey Units before deleting Organization Unit surveyUnitRepository.findByOrganizationUnitIdIn(List.of("OU-NORTH")) diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index 55248b1b..d6a29032 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -5,6 +5,9 @@ import fr.insee.pearljam.api.repository.CampaignRepository; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import fr.insee.pearljam.api.utils.ScriptConstants; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import org.json.JSONException; import org.junit.jupiter.api.DisplayName; @@ -102,7 +105,6 @@ void testGetCampaign() throws Exception { JSONAssert.assertEquals(contentResult, expectedResult, JSONCompareMode.NON_EXTENSIBLE); } - @Test @DisplayName("Should create campaign") @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) @@ -146,6 +148,23 @@ void testCreateCampaign() throws Exception { "role":"PRIMARY" } ], + "communications": [ + { + "meshuggahId": "meshId1", + "medium": "LETTER", + "type": "REMINDER" + }, + { + "meshuggahId": "meshId2", + "medium": "EMAIL", + "type": "NOTICE" + }, + { + "meshuggahId": "meshId3", + "medium": "LETTER", + "type": "NOTICE" + } + ], "email": "test.email@plop.com", "identificationConfiguration":"IASCO", "contactOutcomeConfiguration":"F2F", @@ -174,7 +193,17 @@ void testCreateCampaign() throws Exception { .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, 1721683254000L, 1721683255000L)); + + assertThat(campaignCreated.getCommunicationTemplates()).hasSize(3); + assertThat(campaignCreated.getCommunicationTemplates()) + .anySatisfy(communicationTemplateToCheck -> assertCommunicationTemplate(communicationTemplateToCheck, campaignId, "meshId1", + CommunicationMedium.LETTER, CommunicationType.REMINDER)) + .anySatisfy(communicationTemplateToCheck -> assertCommunicationTemplate(communicationTemplateToCheck, campaignId, "meshId2", + CommunicationMedium.EMAIL, CommunicationType.NOTICE)) + .anySatisfy(communicationTemplateToCheck -> assertCommunicationTemplate(communicationTemplateToCheck, campaignId, "meshId3", + CommunicationMedium.LETTER, CommunicationType.NOTICE)); assertThat(campaignCreated.getReferents()).hasSize(2); + assertThat(campaignCreated.getReferents()) .anySatisfy(referentToCheck -> assertReferent(referentToCheck, campaignId, "PRIMARY", "Marley", "Bob", "0123456789")) @@ -182,6 +211,14 @@ void testCreateCampaign() throws Exception { "Mikoton", "Mylene", "2345678901")); } + private void assertCommunicationTemplate(CommunicationTemplateDB communicationTemplateToCheck, String campaignId, + String meshuggahId, CommunicationMedium medium, CommunicationType type) { + assertThat(communicationTemplateToCheck.getMeshuggahId()).isEqualTo(meshuggahId); + assertThat(communicationTemplateToCheck.getCampaign().getId()).isEqualTo(campaignId); + assertThat(communicationTemplateToCheck.getType()).isEqualTo(type); + assertThat(communicationTemplateToCheck.getMedium()).isEqualTo(medium); + } + @Test @DisplayName("Should update campaign") @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index 642006ff..921a56ea 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -1,6 +1,9 @@ package fr.insee.pearljam.integration.surveyunit; +import fr.insee.pearljam.api.service.SurveyUnitService; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.ScriptConstants; +import org.json.JSONException; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; @@ -10,12 +13,16 @@ import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.transaction.annotation.Transactional; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ActiveProfiles("auth") @AutoConfigureMockMvc @@ -27,6 +34,9 @@ class SurveyUnitIT { @Autowired private MockMvc mockMvc; + @Autowired + private SurveyUnitService surveyUnitService; + @Test void testGetAllSurveyUnits() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/api/survey-units") @@ -86,4 +96,436 @@ void testGetAllSurveyUnits() throws Exception { """; JSONAssert.assertEquals(expectedResult, contentResult, JSONCompareMode.NON_EXTENSIBLE); } + + /** + * Test that the GET endpoint "api/survey-unit/{id}" + * return 200. + * + * @throws InterruptedException + * @throws JSONException + */ + @Test + void testGetSurveyUnitDetail() throws Exception { + MvcResult result = mockMvc.perform(get("/api/survey-unit/11") + .with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)) + .accept(MediaType.APPLICATION_JSON)) + .andExpectAll(status().isOk()) + .andReturn(); + + String resultJson = result.getResponse().getContentAsString(); + String expectedJson = """ + { + "id":"11", + "persons":[ + { + "id":6, + "title":"MISS", + "firstName":"Christine", + "lastName":"Aguilar", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":false, + "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":true, + "number":"+33677542802" + } + ] + }, + { + "id":7, + "title":"MISS", + "firstName":"Louise", + "lastName":"Walker", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":false, + "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":true, + "number":"+33677542802" + } + ] + }, + { + "id":1, + "title":"MISTER", + "firstName":"Ted", + "lastName":"Farmer", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":true, + "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":false, + "number":"+33677542802" + }, + { + "source":"FISCAL", + "favorite":true, + "number":"+33677542802" + } + ] + } + ], + "address":{ + "l1":"Ted Farmer", + "l2":"", + "l3":"", + "l4":"1 rue de la gare", + "l5":"", + "l6":"29270 Carhaix", + "l7":"France", + "elevator":true, + "building":"Bat. C", + "floor":"Etg 4", + "door":"Porte 48", + "staircase":"Escalier B", + "cityPriorityDistrict":true + }, + "priority":true, + "campaign":"SIMPSONS2020X00", + "comments":[], + "sampleIdentifiers":{ + "bs":11, + "ec":"1", + "le":11, + "noi":11, + "numfa":11, + "rges":11, + "ssech":1, + "nolog":11, + "nole":11, + "autre":"11", + "nograp":"11" + }, + "states":[ + { + "id":1, + "date":111112111, + "type":"VIN" + }, + { + "id":7, + "date":101111111, + "type":"TBR" + } + ], + "contactAttempts":[], + "identification":{ + "identification":"IDENTIFIED", + "access":"ACC", + "situation":"ORDINARY", + "category":"PRIMARY", + "occupant":"IDENTIFIED" + }, + "communicationRequests":[ + { + "id":2, + "communicationTemplateId":2, + "reason":"UNREACHABLE", + "emitter":"INTERVIEWER", + "status":[ + { + "id":4, + "date":1721903754305, + "status":"INITIATED" + }, + { + "id":5, + "date":1721903756310, + "status":"READY" + } + ] + }, + { + "id":1, + "communicationTemplateId":1, + "reason":"REFUSAL", + "emitter":"INTERVIEWER", + "status":[ + { + "id":1, + "date":1721903754305, + "status":"INITIATED" + }, + { + "id":2, + "date":1721903755305, + "status":"READY" + }, + { + "id":3, + "date":1721903756305, + "status":"SUBMITTED" + } + ] + } + ] + }"""; + JSONAssert.assertEquals(expectedJson, resultJson, JSONCompareMode.NON_EXTENSIBLE); + } + + /** + * Test that the PUT endpoint "api/survey-unit/{id}" + * return 200 + * + * @throws Exception + */ + @Test + @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) + void testPutSurveyUnitDetail() throws Exception { + String updateJson = """ + { + "id":"20", + "persons":[ + { + "id":10, + "title":"MISTER", + "firstName":"Harriette", + "lastName":"Raymond", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":true, + "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":true, + "number":"test" + } + ] + } + ], + "address":{ + "l1":"test1", + "l2":"test2", + "l3":"test3", + "l4":"test4", + "l5":"test5", + "l6":"test6", + "l7":"test7", + "elevator":true, + "building":"testBuilding", + "floor":"testFloor", + "door":"testDoor", + "staircase":"testStaircase", + "cityPriorityDistrict":true + }, + "priority":false, + "campaign":"VQS2021X00", + "comments":[ + { + "type":"INTERVIEWER", + "value":"test-interviewer-comment" + }, + { + "type":"MANAGEMENT", + "value":"test-management-comment" + } + ], + "sampleIdentifiers":{ + "bs":20, + "ec":"2", + "le":20, + "noi":20, + "numfa":20, + "rges":20, + "ssech":1, + "nolog":20, + "nole":20, + "autre":"20", + "nograp":"20" + }, + "states":[ + { + "date":1590504459838, + "type":"AOC" + }, + { + "id":9, + "date":1590504478334, + "type":"VIC" + } + ], + "contactAttempts":[ + { + "date":1589268626000, + "status":"NOC", + "medium":"TEL" + }, + { + "date":1589268800000, + "status":"INA", + "medium":"TEL" + } + ], + "contactOutcome":{ + "date":1589268626000, + "type":"IMP", + "totalNumberOfContactAttempts":2 + }, + "communicationRequests":[ + { + "communicationTemplateId":4, + "reason":"REFUSAL", + "creationTimestamp": 1721903754305 + }, + { + "communicationTemplateId":5, + "reason":"UNREACHABLE", + "creationTimestamp": 1721903754405 + } + ] + }"""; + MvcResult result = mockMvc.perform(put("/api/survey-unit/20") + .with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)) + .accept(MediaType.APPLICATION_JSON) + .content(updateJson) + .contentType(MediaType.APPLICATION_JSON)) + .andReturn(); + + String resultJson = result.getResponse().getContentAsString(); + String expectedJson = """ + { + "id":"20", + "persons":[ + { + "id":10, + "title":"MISTER", + "firstName":"Harriette", + "lastName":"Raymond", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":true, + "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":true, + "number":"test" + } + ] + } + ], + "address":{ + "l1":"test1", + "l2":"test2", + "l3":"test3", + "l4":"test4", + "l5":"test5", + "l6":"test6", + "l7":"test7", + "elevator":true, + "building":"testBuilding", + "floor":"testFloor", + "door":"testDoor", + "staircase":"testStaircase", + "cityPriorityDistrict":true + }, + "priority":false, + "campaign":"VQS2021X00", + "comments":[ + { + "type":"MANAGEMENT", + "value":"test-management-comment" + }, + { + "type":"INTERVIEWER", + "value":"test-interviewer-comment" + } + ], + "sampleIdentifiers":{ + "bs":20, + "ec":"2", + "le":20, + "noi":20, + "numfa":20, + "rges":20, + "ssech":1, + "nolog":20, + "nole":20, + "autre":"20", + "nograp":"20" + }, + "states":[ + { + "id":9, + "date":1590504478334, + "type":"VIC" + }, + { + "id":13, + "date":1590504459838, + "type":"AOC" + } + ], + "contactAttempts":[ + { + "date":1589268626000, + "status":"NOC", + "medium":"TEL" + }, + { + "date":1589268800000, + "status":"INA", + "medium":"TEL" + } + ], + "contactOutcome":{ + "date":1589268626000, + "type":"IMP", + "totalNumberOfContactAttempts":2 + }, + "communicationRequests":[ + { + "id":4, + "communicationTemplateId":4, + "reason":"UNREACHABLE", + "emitter":"INTERVIEWER", + "status":[ + { + "id":7, + "date":1721903754205, + "status":"INITIATED" + } + ] + }, + { + "id":3, + "communicationTemplateId":3, + "reason":"REFUSAL", + "emitter":"INTERVIEWER", + "status":[ + { + "id":6, + "date":1721903754205, + "status":"INITIATED" + } + ] + }, + { + "id":5, + "communicationTemplateId":5, + "reason":"UNREACHABLE", + "emitter":"INTERVIEWER", + "status":[ + { + "id":8, + "date":1721903754405, + "status":"INITIATED" + } + ] + } + ] + } + """; + JSONAssert.assertEquals(expectedJson, resultJson, JSONCompareMode.NON_EXTENSIBLE); + } } From 0e611fad3091ad9b78974b4f8e9e02bed4f7ef4d Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 11 Sep 2024 14:59:57 +0200 Subject: [PATCH 22/48] fix: allow multiple communication requests to have same communication template id --- .../impl/SurveyUnitUpdateServiceImpl.java | 16 +--------------- .../service/SurveyUnitUpdateServiceImplTest.java | 15 --------------- 2 files changed, 1 insertion(+), 30 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java index 134f9e47..e89b59eb 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java @@ -10,7 +10,6 @@ import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; import fr.insee.pearljam.api.service.SurveyUnitUpdateService; import fr.insee.pearljam.domain.surveyunit.port.serverside.CommunicationRequestRepository; -import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -38,20 +37,7 @@ public void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitUpdateDto sur } if(surveyUnitUpdateDto.communicationRequests() != null) { List communicationRequestsToCreate = CommunicationRequestCreateDto.toModel(surveyUnitUpdateDto.communicationRequests()); - Set currentCommunicationRequests = surveyUnit.getCommunicationRequests(); - List newCommunicationsRequests = communicationRequestsToCreate.stream() - .filter(newCommunicationRequest -> { - for (CommunicationRequestDB currentCommunicationRequest : currentCommunicationRequests) { - // if survey unit has already this communication request, skip it - if(currentCommunicationRequest.getCommunicationTemplate().getId() - .equals(newCommunicationRequest.communicationTemplateId())) { - return false; - } - } - return true; - }) - .toList(); - communicationRequestRepository.addCommunicationRequests(surveyUnit, newCommunicationsRequests); + communicationRequestRepository.addCommunicationRequests(surveyUnit, communicationRequestsToCreate); } Identification identification = IdentificationDto.toModel(surveyUnitUpdateDto.identification()); diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java index ac632a5d..b0b51e15 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java @@ -85,21 +85,6 @@ void testUpdateCommunication01() { ); } - @Test - @DisplayName("Should not add communication requests with duplicate communication configuration") - void testUpdateCommunication02() { - List communicationRequests = List.of( - new CommunicationRequestCreateDto(communicationTemplate.getId(), 12345678910L, - CommunicationRequestReason.UNREACHABLE) - ); - - surveyUnitDto = createSurveyUnitDto(null, null, communicationRequests); - surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); - - List communicationRequestResults = communicationRequestFakeRepository.getCommunicationRequestsAdded(); - assertThat(communicationRequestResults).isEmpty(); - } - @Test @DisplayName("Should add comments for survey unit") void testUpdateComments01() { From 3bbe260b88b078f4c5d6838d86ddab9e10546a6d Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 11 Sep 2024 15:03:49 +0200 Subject: [PATCH 23/48] fix: delete id for comrequests and status from get requests --- .../dto/CommunicationRequestResponseDto.java | 4 +- .../dto/CommunicationRequestStatusDto.java | 14 +- .../dto/SurveyUnitDetailDtoTest.java | 12 +- .../integration/surveyunit/SurveyUnitIT.java | 253 +++++++++--------- 4 files changed, 133 insertions(+), 150 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java index d4e27354..560eb146 100644 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java @@ -7,14 +7,12 @@ /** * Record representing a CommunicationRequestResponseDto - * @param id The ID of the communication request * @param communicationTemplateId configuration id of the communication * @param reason The reason for the communication request * @param emitter The emitter of the communication request * @param status The status of the communication request */ public record CommunicationRequestResponseDto( - Long id, Long communicationTemplateId, CommunicationRequestReason reason, CommunicationRequestEmitter emitter, @@ -31,7 +29,7 @@ public static List fromModel(Set status = request.status().stream() .map(CommunicationRequestStatusDto::fromModel) .toList(); - return new CommunicationRequestResponseDto(request.id(), + return new CommunicationRequestResponseDto( request.communicationTemplateId(), request.reason(), request.emitter(), diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestStatusDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestStatusDto.java index 290ca6c7..1bf34a73 100644 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestStatusDto.java +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestStatusDto.java @@ -6,12 +6,10 @@ /** * Record representing a CommunicationRequestStatusDto * - * @param id The ID of the communication request status * @param date The date of the communication request status * @param status The status type of the communication request */ public record CommunicationRequestStatusDto( - Long id, Long date, CommunicationStatusType status) { @@ -22,16 +20,6 @@ public record CommunicationRequestStatusDto( * @return A new CommunicationRequestStatusDto instance. */ public static CommunicationRequestStatusDto fromModel(CommunicationRequestStatus requestStatus) { - return new CommunicationRequestStatusDto(requestStatus.id(), requestStatus.date(), requestStatus.status()); - } - - /** - * Converts a CommunicationRequestStatusDto to a CommunicationRequestStatus model. - * - * @param requestStatus The CommunicationRequestStatusDto to convert. - * @return A new CommunicationRequestStatus model instance. - */ - public static CommunicationRequestStatus toModel(CommunicationRequestStatusDto requestStatus) { - return new CommunicationRequestStatus(requestStatus.id(), requestStatus.date(), requestStatus.status()); + return new CommunicationRequestStatusDto(requestStatus.date(), requestStatus.status()); } } diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java index b09784a7..84662ff6 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java @@ -101,21 +101,21 @@ void testCreateCommunicationRequests01() { SurveyUnitDetailDto surveyUnitDetailDto = new SurveyUnitDetailDto(surveyUnit); List status1Expected = List.of( - new CommunicationRequestStatusDto(null, 1233456789L, CommunicationStatusType.INITIATED), - new CommunicationRequestStatusDto(2L, 123345678910L, CommunicationStatusType.FAILED) + new CommunicationRequestStatusDto(1233456789L, CommunicationStatusType.INITIATED), + new CommunicationRequestStatusDto(123345678910L, CommunicationStatusType.FAILED) ); List status2Expected = List.of( - new CommunicationRequestStatusDto(3L, 123345678911L, CommunicationStatusType.READY), - new CommunicationRequestStatusDto(4L, 123345678912L, CommunicationStatusType.CANCELLED) + new CommunicationRequestStatusDto(123345678911L, CommunicationStatusType.READY), + new CommunicationRequestStatusDto(123345678912L, CommunicationStatusType.CANCELLED) ); assertThat(surveyUnitDetailDto.getCommunicationRequests()) .containsExactlyInAnyOrder( - new CommunicationRequestResponseDto(10L, 1L, + new CommunicationRequestResponseDto(1L, CommunicationRequestReason.UNREACHABLE, CommunicationRequestEmitter.INTERVIEWER, status1Expected), - new CommunicationRequestResponseDto(11L, 2L, + new CommunicationRequestResponseDto(2L, CommunicationRequestReason.REFUSAL, CommunicationRequestEmitter.TOOL, status2Expected) ); diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index 921a56ea..2496e2a3 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -227,41 +227,34 @@ void testGetSurveyUnitDetail() throws Exception { }, "communicationRequests":[ { - "id":2, "communicationTemplateId":2, "reason":"UNREACHABLE", "emitter":"INTERVIEWER", "status":[ { - "id":4, "date":1721903754305, "status":"INITIATED" }, { - "id":5, "date":1721903756310, "status":"READY" } ] }, { - "id":1, "communicationTemplateId":1, "reason":"REFUSAL", "emitter":"INTERVIEWER", "status":[ { - "id":1, "date":1721903754305, "status":"INITIATED" }, { - "id":2, "date":1721903755305, "status":"READY" }, { - "id":3, "date":1721903756305, "status":"SUBMITTED" } @@ -393,139 +386,143 @@ void testPutSurveyUnitDetail() throws Exception { String resultJson = result.getResponse().getContentAsString(); String expectedJson = """ + { + "id":"20", + "persons":[ { - "id":"20", - "persons":[ + "id":10, + "title":"MISTER", + "firstName":"Harriette", + "lastName":"Raymond", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":true, + "phoneNumbers":[ { - "id":10, - "title":"MISTER", - "firstName":"Harriette", - "lastName":"Raymond", - "email":"test@test.com", - "birthdate":11111111, - "favoriteEmail":true, - "privileged":true, - "phoneNumbers":[ - { - "source":"FISCAL", - "favorite":true, - "number":"test" - } - ] + "source":"FISCAL", + "favorite":true, + "number":"test" } - ], - "address":{ - "l1":"test1", - "l2":"test2", - "l3":"test3", - "l4":"test4", - "l5":"test5", - "l6":"test6", - "l7":"test7", - "elevator":true, - "building":"testBuilding", - "floor":"testFloor", - "door":"testDoor", - "staircase":"testStaircase", - "cityPriorityDistrict":true - }, - "priority":false, - "campaign":"VQS2021X00", - "comments":[ - { - "type":"MANAGEMENT", - "value":"test-management-comment" - }, + ] + } + ], + "address":{ + "l1":"test1", + "l2":"test2", + "l3":"test3", + "l4":"test4", + "l5":"test5", + "l6":"test6", + "l7":"test7", + "elevator":true, + "building":"testBuilding", + "floor":"testFloor", + "door":"testDoor", + "staircase":"testStaircase", + "cityPriorityDistrict":true + }, + "priority":false, + "campaign":"VQS2021X00", + "comments":[ + { + "type":"INTERVIEWER", + "value":"test-interviewer-comment" + }, + { + "type":"MANAGEMENT", + "value":"test-management-comment" + } + ], + "sampleIdentifiers":{ + "bs":20, + "ec":"2", + "le":20, + "noi":20, + "numfa":20, + "rges":20, + "ssech":1, + "nolog":20, + "nole":20, + "autre":"20", + "nograp":"20" + }, + "states":[ + { + "id":9, + "date":1590504478334, + "type":"VIC" + }, + { + "id":13, + "date":1590504459838, + "type":"AOC" + } + ], + "contactAttempts":[ + { + "date":1589268626000, + "status":"NOC", + "medium":"TEL" + }, + { + "date":1589268800000, + "status":"INA", + "medium":"TEL" + } + ], + "contactOutcome":{ + "date":1589268626000, + "type":"IMP", + "totalNumberOfContactAttempts":2 + }, + "communicationRequests":[ + { + "communicationTemplateId":4, + "reason":"REFUSAL", + "emitter":"INTERVIEWER", + "status":[ { - "type":"INTERVIEWER", - "value":"test-interviewer-comment" + "date":1721903754305, + "status":"INITIATED" } - ], - "sampleIdentifiers":{ - "bs":20, - "ec":"2", - "le":20, - "noi":20, - "numfa":20, - "rges":20, - "ssech":1, - "nolog":20, - "nole":20, - "autre":"20", - "nograp":"20" - }, - "states":[ - { - "id":9, - "date":1590504478334, - "type":"VIC" - }, - { - "id":13, - "date":1590504459838, - "type":"AOC" - } - ], - "contactAttempts":[ - { - "date":1589268626000, - "status":"NOC", - "medium":"TEL" - }, + ] + }, + { + "communicationTemplateId":4, + "reason":"UNREACHABLE", + "emitter":"INTERVIEWER", + "status":[ { - "date":1589268800000, - "status":"INA", - "medium":"TEL" + "date":1721903754205, + "status":"INITIATED" } - ], - "contactOutcome":{ - "date":1589268626000, - "type":"IMP", - "totalNumberOfContactAttempts":2 - }, - "communicationRequests":[ - { - "id":4, - "communicationTemplateId":4, - "reason":"UNREACHABLE", - "emitter":"INTERVIEWER", - "status":[ - { - "id":7, - "date":1721903754205, - "status":"INITIATED" - } - ] - }, + ] + }, + { + "communicationTemplateId":5, + "reason":"UNREACHABLE", + "emitter":"INTERVIEWER", + "status":[ { - "id":3, - "communicationTemplateId":3, - "reason":"REFUSAL", - "emitter":"INTERVIEWER", - "status":[ - { - "id":6, - "date":1721903754205, - "status":"INITIATED" - } - ] - }, + "date":1721903754405, + "status":"INITIATED" + } + ] + }, + { + "communicationTemplateId":3, + "reason":"REFUSAL", + "emitter":"INTERVIEWER", + "status":[ { - "id":5, - "communicationTemplateId":5, - "reason":"UNREACHABLE", - "emitter":"INTERVIEWER", - "status":[ - { - "id":8, - "date":1721903754405, - "status":"INITIATED" - } - ] + "date":1721903754205, + "status":"INITIATED" } ] } - """; + ] + }"""; JSONAssert.assertEquals(expectedJson, resultJson, JSONCompareMode.NON_EXTENSIBLE); } } From 292c7d81a1d7bece4155e984d7273a824e0fdda1 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 10 Sep 2024 14:22:36 +0200 Subject: [PATCH 24/48] fix: delete request communication configuration parameter --- .../campaign/dto/input/CampaignCreateDto.java | 3 +-- .../campaign/dto/input/CampaignUpdateDto.java | 3 +-- .../dto/output/CampaignResponseDto.java | 7 ++--- .../api/controller/CampaignController.java | 2 +- .../insee/pearljam/api/domain/Campaign.java | 8 +----- .../api/dto/campaign/CampaignDto.java | 6 +---- .../api/dto/surveyunit/SurveyUnitDto.java | 6 ----- .../api/repository/CampaignRepository.java | 6 ++--- .../api/service/impl/CampaignServiceImpl.java | 6 +---- ...542_update_communication_configuration.xml | 10 +++++++ src/main/resources/db/master.xml | 3 +++ .../api/authKeycloak/TestAuthKeyCloak.java | 2 -- .../CampaignControllerCreateTest.java | 9 +------ .../controller/CampaignControllerTest.java | 2 +- .../CampaignControllerUpdateTest.java | 7 +---- .../dto/SurveyUnitDetailDtoTest.java | 2 +- .../service/CampaignServiceImplTest.java | 26 ++++++------------- .../adapter/VisibilityDaoAdapterTest.java | 2 +- .../entity/CommunicationTemplateDBTest.java | 4 +-- .../campaign/entity/VisibilityDBTest.java | 2 +- .../integration/campaign/CampaignIT.java | 13 ++++------ .../integration/surveyunit/SurveyUnitIT.java | 9 +++---- 22 files changed, 48 insertions(+), 90 deletions(-) create mode 100644 src/main/resources/db/changelog/542_update_communication_configuration.xml diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java index 2ab585ca..7bf4792b 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java @@ -29,6 +29,5 @@ public record CampaignCreateDto ( String email, IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, - ContactAttemptConfiguration contactAttemptConfiguration, - Boolean communicationRequestConfiguration) { + ContactAttemptConfiguration contactAttemptConfiguration) { } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java index 6adfbed5..31f6b4b1 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java @@ -29,6 +29,5 @@ public record CampaignUpdateDto( String email, IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, - ContactAttemptConfiguration contactAttemptConfiguration, - Boolean communicationRequestConfiguration + ContactAttemptConfiguration contactAttemptConfiguration ) {} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java index 4c0a6022..4f15a423 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java @@ -20,7 +20,6 @@ * @param identificationConfiguration The identification configuration of the campaign. * @param contactOutcomeConfiguration The contact outcome configuration of the campaign. * @param contactAttemptConfiguration The contact attempt configuration of the campaign. - * @param communicationRequestConfiguration The communication request configuration of the campaign. */ @JsonInclude(JsonInclude.Include.NON_NULL) public record CampaignResponseDto( @@ -31,8 +30,7 @@ public record CampaignResponseDto( String email, IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, - ContactAttemptConfiguration contactAttemptConfiguration, - Boolean communicationRequestConfiguration + ContactAttemptConfiguration contactAttemptConfiguration ) { public static CampaignResponseDto fromModel(Campaign campaignDB, List referents, List visibilities) { return new CampaignResponseDto(campaignDB.getId(), @@ -42,8 +40,7 @@ public static CampaignResponseDto fromModel(Campaign campaignDB, List communicationTemplates; public Campaign(String id, String label, IdentificationConfiguration identConfig, - ContactOutcomeConfiguration contOutConfig, ContactAttemptConfiguration contAttConfig, String email, - Boolean communicationConfiguration) { + ContactOutcomeConfiguration contOutConfig, ContactAttemptConfiguration contAttConfig, String email) { super(); this.id = id; this.label = label; @@ -89,6 +84,5 @@ public Campaign(String id, String label, IdentificationConfiguration identConfig this.contactOutcomeConfiguration = contOutConfig; this.identificationConfiguration = identConfig; this.email = email; - this.communicationConfiguration = Optional.ofNullable(communicationConfiguration).orElse(false); } } diff --git a/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java b/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java index 6b82ea40..5288ef13 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java @@ -1,7 +1,6 @@ package fr.insee.pearljam.api.dto.campaign; import java.util.List; -import java.util.Optional; import com.fasterxml.jackson.annotation.JsonInclude; @@ -38,7 +37,6 @@ public class CampaignDto { private IdentificationConfiguration identificationConfiguration; private ContactAttemptConfiguration contactAttemptConfiguration; private ContactOutcomeConfiguration contactOutcomeConfiguration; - private Boolean communicationRequestConfiguration; private List referents; public CampaignDto(String id, String label) { @@ -62,8 +60,7 @@ public CampaignDto(String id, String label, Long managementStartDate, Long endDa } public CampaignDto(String id, String label, String email, IdentificationConfiguration identConfig, - ContactOutcomeConfiguration contOutConfig, ContactAttemptConfiguration contAttConfig, - Boolean communicationRequestConfiguration) { + ContactOutcomeConfiguration contOutConfig, ContactAttemptConfiguration contAttConfig) { super(); this.id = id; this.label = label; @@ -71,7 +68,6 @@ public CampaignDto(String id, String label, String email, IdentificationConfigur this.identificationConfiguration = identConfig; this.contactOutcomeConfiguration = contOutConfig; this.contactAttemptConfiguration = contAttConfig; - this.communicationRequestConfiguration = Optional.ofNullable(communicationRequestConfiguration).orElse(false); } public void setCampaignStats(List obj) { diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java index 60569f8b..a8027300 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java @@ -1,7 +1,6 @@ package fr.insee.pearljam.api.dto.surveyunit; import java.util.List; -import java.util.Optional; import com.fasterxml.jackson.annotation.JsonInclude; @@ -68,7 +67,6 @@ public class SurveyUnitDto { private IdentificationConfiguration identificationConfiguration; private ContactOutcomeConfiguration contactOutcomeConfiguration; private ContactAttemptConfiguration contactAttemptConfiguration; - private boolean communicationRequestConfiguration; private List persons; @@ -90,8 +88,6 @@ public SurveyUnitDto(SurveyUnit su, SurveyUnitVisibilityDto visibility, Boolean this.identificationConfiguration = su.getCampaign().getIdentificationConfiguration(); this.contactAttemptConfiguration = su.getCampaign().getContactAttemptConfiguration(); this.contactOutcomeConfiguration = su.getCampaign().getContactOutcomeConfiguration(); - this.communicationRequestConfiguration = Optional.ofNullable(su.getCampaign().getCommunicationConfiguration()) - .orElse(false); if (Boolean.TRUE.equals(extended)) { this.persons = su.getPersons().stream() .map(PersonDto::new) @@ -113,7 +109,5 @@ public SurveyUnitDto(String idSurveyUnit, CampaignDto campaign, SurveyUnitVisibi this.identificationConfiguration = campaign.getIdentificationConfiguration(); this.contactAttemptConfiguration = campaign.getContactAttemptConfiguration(); this.contactOutcomeConfiguration = campaign.getContactOutcomeConfiguration(); - this.communicationRequestConfiguration = Optional.of(campaign.getCommunicationRequestConfiguration()) - .orElse(false); } } diff --git a/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java b/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java index 741bce07..41fb8a1b 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java @@ -44,19 +44,19 @@ public interface CampaignRepository extends JpaRepository { + "WHERE ou.id ILIKE ?1", nativeQuery = true) List findIdsByOuId(String ouId); - @Query(value = "SELECT new fr.insee.pearljam.api.dto.campaign.CampaignDto(camp.id, camp.label, camp.email, camp.identificationConfiguration, camp.contactOutcomeConfiguration, camp.contactAttemptConfiguration, camp.communicationConfiguration) " + @Query(value = "SELECT new fr.insee.pearljam.api.dto.campaign.CampaignDto(camp.id, camp.label, camp.email, camp.identificationConfiguration, camp.contactOutcomeConfiguration, camp.contactAttemptConfiguration) " + "FROM Campaign camp " + "WHERE camp.id=?1") CampaignDto findDtoById(String id); @Query("SELECT " - + "new fr.insee.pearljam.api.dto.campaign.CampaignDto(camp.id, camp.label, camp.email, camp.identificationConfiguration, camp.contactOutcomeConfiguration, camp.contactAttemptConfiguration, camp.communicationConfiguration) " + + "new fr.insee.pearljam.api.dto.campaign.CampaignDto(camp.id, camp.label, camp.email, camp.identificationConfiguration, camp.contactOutcomeConfiguration, camp.contactAttemptConfiguration) " + "FROM SurveyUnit su " + "JOIN su.campaign camp " + "WHERE su.id=?1") CampaignDto findDtoBySurveyUnitId(String id); - @Query(value = "SELECT new fr.insee.pearljam.api.dto.campaign.CampaignDto(camp.id, camp.label, camp.email, camp.identificationConfiguration, camp.contactOutcomeConfiguration, camp.contactAttemptConfiguration, camp.communicationConfiguration) " + @Query(value = "SELECT new fr.insee.pearljam.api.dto.campaign.CampaignDto(camp.id, camp.label, camp.email, camp.identificationConfiguration, camp.contactOutcomeConfiguration, camp.contactAttemptConfiguration) " + "FROM Campaign camp") List findAllDto(); diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index 4839692f..a0350546 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -157,8 +157,7 @@ public void createCampaign(CampaignCreateDto campaignDto) campaignDto.identificationConfiguration(), campaignDto.contactOutcomeConfiguration(), campaignDto.contactAttemptConfiguration(), - campaignDto.email(), - campaignDto.communicationRequestConfiguration()); + campaignDto.email()); campaign.setReferents(new ArrayList<>()); campaign.setCommunicationTemplates(new ArrayList<>()); @@ -248,9 +247,6 @@ private void updateConfiguration(Campaign currentCampaign, CampaignUpdateDto cam if (campDto.contactAttemptConfiguration() != null) { currentCampaign.setContactAttemptConfiguration(campDto.contactAttemptConfiguration()); } - if (campDto.communicationRequestConfiguration() != null) { - currentCampaign.setCommunicationConfiguration(campDto.communicationRequestConfiguration()); - } } @Override diff --git a/src/main/resources/db/changelog/542_update_communication_configuration.xml b/src/main/resources/db/changelog/542_update_communication_configuration.xml new file mode 100644 index 00000000..0882895a --- /dev/null +++ b/src/main/resources/db/changelog/542_update_communication_configuration.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/src/main/resources/db/master.xml b/src/main/resources/db/master.xml index e2ea6e21..0bd757fd 100644 --- a/src/main/resources/db/master.xml +++ b/src/main/resources/db/master.xml @@ -48,4 +48,7 @@ + + + \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java index ffdf31b5..c2e0d4b0 100644 --- a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java +++ b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java @@ -280,8 +280,6 @@ void testGetCampaign() throws Exception { checkJsonPath(campaignJsonPath, "email", "first.email@test.com"), checkJsonPath(campaignJsonPath, "toReview", 3L), checkJsonPath(campaignJsonPath, "preference", true), - checkJsonPath(campaignJsonPath, "communicationRequestConfiguration", - false), checkJsonPath(campaignJsonPath, "identificationConfiguration", IdentificationConfiguration.IASCO.name()), checkJsonPath(campaignJsonPath, "contactAttemptConfiguration", diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java index 7c967680..c696a4fc 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java @@ -101,14 +101,12 @@ void testCreateCampaign04() throws Exception { CampaignCreateDto campaign1 = generateCampaign(" ", "An other campaign", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - true, List.of(visibility), List.of(), List.of()); CampaignCreateDto campaign2 = generateCampaign("campId", " ", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - true, List.of(visibility), List.of(), List.of()); @@ -154,7 +152,6 @@ void testCreateCampaign05() throws Exception { CampaignCreateDto campaign = generateCampaign("campId", "campaignLabel", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - true, invalidCampaignVisibilities, List.of(), List.of()); @@ -191,7 +188,6 @@ void testCreateCampaign07() throws Exception { CampaignCreateDto campaign = generateCampaign("campId", "label", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - true, List.of(visibility), List.of(), List.of(communicationTemplate, duplicatedCommunicationTemplate)); @@ -226,7 +222,6 @@ public CampaignCreateDto generateDefaultCampaign() { return generateCampaign("campId", "An other campaign", "test.test@sdf.com", IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL, - true, List.of(firstVisibility, secondVisibility), List.of(firstReferent, secondReferent), List.of(communicationTemplate1, communicationTemplate2)); @@ -237,7 +232,6 @@ private CampaignCreateDto generateCampaign( String email, IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, ContactAttemptConfiguration contactAttemptConfiguration, - Boolean communicationRequestConfiguration, List visibilities, List referents, List communicationTemplates) { @@ -250,8 +244,7 @@ private CampaignCreateDto generateCampaign( email, identificationConfiguration, contactOutcomeConfiguration, - contactAttemptConfiguration, - communicationRequestConfiguration + contactAttemptConfiguration ); } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java index c318a13b..983d1d75 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java @@ -53,7 +53,7 @@ void setup() { @DisplayName("Should retrieve campaign") void testGetCampaign01() throws Exception { CampaignResponseDto campaign = new CampaignResponseDto("campaign-id", "label", null, null, "email", - IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.F2F, true); + IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.F2F); campaignService.setCampaignToRetrieve(campaign); MvcResult mvcResult = mockMvc.perform(get(getPath) diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java index 4ade19ee..b225b50b 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java @@ -70,7 +70,6 @@ void testUpdateCampaign02() throws Exception { CampaignUpdateDto campaign = generateCampaign(" ", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - true, List.of(), List.of()); mockMvc.perform(put(updatePath) @@ -133,7 +132,6 @@ private void testUpdateExceptions(VisibilityCampaignUpdateDto visibility, HttpSt CampaignUpdateDto campaign = generateCampaign("campaignLabel", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - true, List.of(visibility), List.of()); mockMvc.perform(put(updatePath) @@ -160,7 +158,6 @@ private CampaignUpdateDto generateDefaultCampaign() { return generateCampaign("An other campaign", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - true, List.of(firstVisibility, secondVisibility), List.of(firstReferent, secondReferent)); } @@ -169,7 +166,6 @@ private CampaignUpdateDto generateCampaign(String campaignLabel, String email, IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, ContactAttemptConfiguration contactAttemptConfiguration, - Boolean communicationRequestConfiguration, List visibilities, List referents) { return new CampaignUpdateDto( @@ -179,8 +175,7 @@ private CampaignUpdateDto generateCampaign(String campaignLabel, email, identificationConfiguration, contactOutcomeConfiguration, - contactAttemptConfiguration, - communicationRequestConfiguration + contactAttemptConfiguration ); } diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java index 84662ff6..8f6af3a4 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java @@ -30,7 +30,7 @@ void setup() { SampleIdentifier sampleIdentifier = new InseeSampleIdentifier(1, "ec", 2, 3, 4, 5, 6, 7, 8, "autre", "nograp"); Campaign campaign = new Campaign("id", "label", null, - null, null, "email", true); + null, null, "email"); surveyUnit = new SurveyUnit("id", true, true, address, sampleIdentifier, campaign, null, null, new HashSet<>()); diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java index 3d92ff1b..d85a260a 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java @@ -40,8 +40,7 @@ class CampaignServiceImplTest { IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - "email@email.com", - true); + "email@email.com"); private final Visibility existingVisibility1 = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1721683250000L, @@ -104,8 +103,7 @@ void shouldCreateNewCampaign() throws CampaignAlreadyExistException, Organizatio null, IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, - true + ContactAttemptConfiguration.F2F ); campaignService.createCampaign(campaignCreateDto); @@ -114,7 +112,6 @@ void shouldCreateNewCampaign() throws CampaignAlreadyExistException, Organizatio assertThat(createdCampaign.getId()).isEqualTo(campaignCreateDto.campaign()); assertThat(createdCampaign.getLabel()).isEqualTo(campaignCreateDto.campaignLabel()); assertThat(createdCampaign.getEmail()).isEqualTo(campaignCreateDto.email()); - assertThat(createdCampaign.getCommunicationConfiguration()).isEqualTo(campaignCreateDto.communicationRequestConfiguration()); assertThat(createdCampaign.getIdentificationConfiguration()).isEqualTo(campaignCreateDto.identificationConfiguration()); assertThat(createdCampaign.getContactAttemptConfiguration()).isEqualTo(campaignCreateDto.contactAttemptConfiguration()); assertThat(createdCampaign.getContactOutcomeConfiguration()).isEqualTo(campaignCreateDto.contactOutcomeConfiguration()); @@ -144,8 +141,7 @@ void shouldThrowCampaignAlreadyExistExceptionWhenCreatingExistingCampaign() { null, IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F, - true + ContactAttemptConfiguration.F2F ); assertThatThrownBy(() -> campaignService.createCampaign(existingCampaignDto)) @@ -168,8 +164,7 @@ void shouldUpdateExistingCampaign() throws CampaignNotFoundException, Visibility null, "emailUpdated@email.com", IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, - ContactAttemptConfiguration.TEL, - false); + ContactAttemptConfiguration.TEL); // When campaignService.updateCampaign(campaignId, updateDto); @@ -179,7 +174,6 @@ void shouldUpdateExistingCampaign() throws CampaignNotFoundException, Visibility assertThat(updatedCampaign.getId()).isEqualTo(campaignId); assertThat(updatedCampaign.getLabel()).isEqualTo(updateDto.campaignLabel()); assertThat(updatedCampaign.getEmail()).isEqualTo(updateDto.email()); - assertThat(updatedCampaign.getCommunicationConfiguration()).isEqualTo(updateDto.communicationRequestConfiguration()); assertThat(updatedCampaign.getIdentificationConfiguration()).isEqualTo(updateDto.identificationConfiguration()); assertThat(updatedCampaign.getContactAttemptConfiguration()).isEqualTo(updateDto.contactAttemptConfiguration()); assertThat(updatedCampaign.getContactOutcomeConfiguration()).isEqualTo(updateDto.contactOutcomeConfiguration()); @@ -205,8 +199,7 @@ void shouldNotUpdateEmailIfNull(String emailToUpdate) throws CampaignNotFoundExc null, emailToUpdate, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, - ContactAttemptConfiguration.TEL, - false); + ContactAttemptConfiguration.TEL); // When campaignService.updateCampaign(campaignId, updateDto); @@ -228,8 +221,7 @@ void shouldNotUpdateVisibilitiesIfNull() throws CampaignNotFoundException, Visib null, null, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, - ContactAttemptConfiguration.TEL, - false); + ContactAttemptConfiguration.TEL); // When campaignService.updateCampaign(campaignId, updateDto); @@ -250,8 +242,7 @@ void shouldNotUpdateReferentsIfNull() throws VisibilityHasInvalidDatesException, null, null, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, - ContactAttemptConfiguration.TEL, - false); + ContactAttemptConfiguration.TEL); // When campaignService.updateCampaign(campaignId, updateDto); @@ -271,8 +262,7 @@ void shouldThrowCampaignNotFoundExceptionWhenUpdatingNonExistentCampaign() { null, null, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, - ContactAttemptConfiguration.TEL, - false); + ContactAttemptConfiguration.TEL); assertThatThrownBy(() -> campaignService.updateCampaign(campaignId, updateDto)) .isInstanceOf(CampaignNotFoundException.class); diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java index 076ecd33..8effe521 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java @@ -60,7 +60,7 @@ class VisibilityDaoAdapterTest { void setup() { campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - "email@plop.com", true); + "email@plop.com"); organizationUnit = new OrganizationUnit("OU-SOUTHWEST", "South west", OrganizationUnitType.LOCAL); organizationUnit2 = new OrganizationUnit("OU-NORTHWEST", "North west", OrganizationUnitType.NATIONAL); diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java index 110d40ff..311963fa 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java @@ -22,7 +22,7 @@ void testToModel() { // Given Campaign campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - "email@plop.com", true); + "email@plop.com"); CommunicationTemplateDB templateDB1 = new CommunicationTemplateDB(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE, campaign); CommunicationTemplateDB templateDB2 = new CommunicationTemplateDB(2L, "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER, campaign); List dbList = List.of(templateDB1, templateDB2); @@ -51,7 +51,7 @@ void testFromModel() { // Given Campaign campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - "email@plop.com", true); + "email@plop.com"); CommunicationTemplate template1 = new CommunicationTemplate(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); CommunicationTemplate template2 = new CommunicationTemplate(2L, "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER); List modelList = List.of(template1, template2); diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java index 9f662f9d..ab45ff9f 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java @@ -16,7 +16,7 @@ class VisibilityDBTest { void setup() { campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - "email@plop.com", true); + "email@plop.com"); organizationUnit = new OrganizationUnit("OU-SOUTHWEST", "South west", OrganizationUnitType.LOCAL); } diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index d6a29032..b4f6d792 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -168,8 +168,7 @@ void testCreateCampaign() throws Exception { "email": "test.email@plop.com", "identificationConfiguration":"IASCO", "contactOutcomeConfiguration":"F2F", - "contactAttemptConfiguration":"F2F", - "communicationRequestConfiguration": null + "contactAttemptConfiguration":"F2F" } """; mockMvc.perform(post(Constants.API_CAMPAIGN) @@ -183,7 +182,7 @@ void testCreateCampaign() throws Exception { assertThat(campaignOptional).isPresent(); Campaign campaignCreated = campaignOptional.get(); assertCampaignInfos(campaignCreated, campaignId, "An other campaign", "test.email@plop.com", - false, ContactAttemptConfiguration.F2F, IdentificationConfiguration.IASCO, + ContactAttemptConfiguration.F2F, IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F); assertThat(campaignCreated.getVisibilities()).hasSize(2); assertThat(campaignCreated.getVisibilities()) @@ -265,8 +264,7 @@ void testUpdateCampaign() throws Exception { "email":"test.test@sdf.com", "identificationConfiguration":"NOIDENT", "contactOutcomeConfiguration":"TEL", - "contactAttemptConfiguration":"F2F", - "communicationRequestConfiguration":true + "contactAttemptConfiguration":"F2F" } """; mockMvc.perform(put("/api/campaign/" + campaignId) @@ -280,7 +278,7 @@ void testUpdateCampaign() throws Exception { assertThat(campaignOptional).isPresent(); Campaign campaignUpdated = campaignOptional.get(); assertCampaignInfos(campaignUpdated, campaignId, "An other campaign", "test.test@sdf.com", - true, ContactAttemptConfiguration.F2F, IdentificationConfiguration.NOIDENT, + ContactAttemptConfiguration.F2F, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL); assertThat(campaignUpdated.getVisibilities()).hasSize(2); assertThat(campaignUpdated.getVisibilities()) @@ -341,12 +339,11 @@ private void assertReferent(Referent referentToCheck, String campaignId, String } private void assertCampaignInfos(Campaign campaignToCheck, String campaignId, String label, String email, - boolean communicationConfiguration, ContactAttemptConfiguration contactAttemptConfig, + ContactAttemptConfiguration contactAttemptConfig, IdentificationConfiguration identificationConfig, ContactOutcomeConfiguration contactOutcomeConfig) { assertThat(campaignToCheck.getId()).isEqualTo(campaignId); assertThat(campaignToCheck.getLabel()).isEqualTo(label); assertThat(campaignToCheck.getEmail()).isEqualTo(email); - assertThat(campaignToCheck.getCommunicationConfiguration()).isEqualTo(communicationConfiguration); assertThat(campaignToCheck.getContactAttemptConfiguration()).isEqualTo(contactAttemptConfig); assertThat(campaignToCheck.getIdentificationConfiguration()).isEqualTo(identificationConfig); assertThat(campaignToCheck.getContactOutcomeConfiguration()).isEqualTo(contactOutcomeConfig); diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index 2496e2a3..f6b64464 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -59,8 +59,7 @@ void testGetAllSurveyUnits() throws Exception { "endDate":1724582154306, "identificationConfiguration":"IASCO", "contactOutcomeConfiguration":"F2F", - "contactAttemptConfiguration":"F2F", - "communicationRequestConfiguration":false + "contactAttemptConfiguration":"F2F" }, { "id":"12", @@ -74,8 +73,7 @@ void testGetAllSurveyUnits() throws Exception { "endDate":1724582154306, "identificationConfiguration":"IASCO", "contactOutcomeConfiguration":"F2F", - "contactAttemptConfiguration":"F2F", - "communicationRequestConfiguration":false + "contactAttemptConfiguration":"F2F" }, { "id":"20", @@ -89,8 +87,7 @@ void testGetAllSurveyUnits() throws Exception { "endDate":1724582154308, "identificationConfiguration":"IASCO", "contactOutcomeConfiguration":"TEL", - "contactAttemptConfiguration":"TEL", - "communicationRequestConfiguration":false + "contactAttemptConfiguration":"TEL" } ] """; From d12d232cd716ac48e79c0f757e1625087cf5c6b6 Mon Sep 17 00:00:00 2001 From: davdarras Date: Thu, 12 Sep 2024 14:00:41 +0200 Subject: [PATCH 25/48] feat: endpoint exposing communication templates for a campaign --- .../CommunicationTemplateController.java | 39 ++++++++++++++ .../CommunicationTemplateResponseDto.java | 2 - .../pearljam/api/constants/Constants.java | 1 + .../CommunicationTemplateRepository.java | 14 +++++ .../CommunicationTemplateService.java | 14 +++++ .../CommunicationTemplateServiceImpl.java | 20 +++++++ .../CommunicationTemplateDaoAdapter.java | 24 +++++++++ .../CommunicationTemplateJpaRepository.java | 6 +++ .../config/OidcSecurityConfiguration.java | 2 + .../CommunicationTemplateResponseDtoTest.java | 2 - .../campaign/CommunicationTemplateIT.java | 53 +++++++++++++++++++ 11 files changed, 173 insertions(+), 4 deletions(-) create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationTemplateController.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationTemplateService.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationTemplateServiceImpl.java create mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java create mode 100644 src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java diff --git a/src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationTemplateController.java b/src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationTemplateController.java new file mode 100644 index 00000000..141eb33c --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationTemplateController.java @@ -0,0 +1,39 @@ +package fr.insee.pearljam.api.campaign.controller; + +import fr.insee.pearljam.api.campaign.dto.output.CommunicationTemplateResponseDto; +import fr.insee.pearljam.api.constants.Constants; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.port.userside.CommunicationTemplateService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.constraints.NotBlank; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@Tag(name = "01. Campaigns", description = "Endpoints for campaigns") +@Slf4j +@RequiredArgsConstructor +@Validated +public class CommunicationTemplateController { + private final CommunicationTemplateService communicationTemplateService; + + /** + * This method returns the list of visibilities associated with the + * campaign {id} + * + * @param campaignId campaign id + * @return List of {@link CommunicationTemplateResponseDto} + */ + @Operation(summary = "Get campaign communication templates") + @GetMapping(path = Constants.API_CAMPAIGN_ID_COMMUNICATION_TEMPLATES) + public List getCommunicationTemplates( + @NotBlank @PathVariable(value = "id") String campaignId) { + List communicationTemplates = communicationTemplateService.findCommunicationTemplates(campaignId); + return CommunicationTemplateResponseDto.fromModel(communicationTemplates); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java index 944d9b1c..67a1ee10 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java @@ -8,7 +8,6 @@ public record CommunicationTemplateResponseDto( Long id, - String messhugahId, CommunicationMedium medium, CommunicationType type ) { @@ -17,7 +16,6 @@ public static List fromModel(List new CommunicationTemplateResponseDto( communicationTemplate.id(), - communicationTemplate.meshuggahId(), communicationTemplate.medium(), communicationTemplate.type())) .toList(); diff --git a/src/main/java/fr/insee/pearljam/api/constants/Constants.java b/src/main/java/fr/insee/pearljam/api/constants/Constants.java index e76a459b..b6b8409a 100644 --- a/src/main/java/fr/insee/pearljam/api/constants/Constants.java +++ b/src/main/java/fr/insee/pearljam/api/constants/Constants.java @@ -55,6 +55,7 @@ private Constants() { public static final String API_CAMPAIGN_ID_SU_INTERVIEWER_CLOSINGCAUSES = "/api/campaign/{id}/survey-units/interviewer/{idep}/closing-causes"; public static final String API_CAMPAIGN_ID_OU_ID_VISIBILITY = "/api/campaign/{idCampaign}/organizational-unit/{idOu}/visibility"; public static final String API_CAMPAIGN_ID_VISIBILITIES = "/api/campaign/{id}/visibilities"; + public static final String API_CAMPAIGN_ID_COMMUNICATION_TEMPLATES = "/api/campaign/{id}/communication-templates"; public static final String API_CAMPAIGN_ID_REFERENTS = "/api/campaigns/{id}/referents"; public static final String API_CAMPAIGNS_ID_ON_GOING = "/campaigns/{id}/ongoing"; diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java new file mode 100644 index 00000000..7e32604c --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java @@ -0,0 +1,14 @@ +package fr.insee.pearljam.domain.campaign.port.serverside; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; + +import java.util.List; + +public interface CommunicationTemplateRepository { + /** + * + * @param campaignId campaign id + * @return list of communication templates for a campaign + */ + List findCommunicationTemplates(String campaignId); +} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationTemplateService.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationTemplateService.java new file mode 100644 index 00000000..aa8bab7f --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationTemplateService.java @@ -0,0 +1,14 @@ +package fr.insee.pearljam.domain.campaign.port.userside; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; + +import java.util.List; + +public interface CommunicationTemplateService { + + /** + * @param campaignId campaign id + * @return the communication templates for a campaign + */ + List findCommunicationTemplates(String campaignId); +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationTemplateServiceImpl.java b/src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationTemplateServiceImpl.java new file mode 100644 index 00000000..85039ea3 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationTemplateServiceImpl.java @@ -0,0 +1,20 @@ +package fr.insee.pearljam.domain.campaign.service; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.port.serverside.CommunicationTemplateRepository; +import fr.insee.pearljam.domain.campaign.port.userside.CommunicationTemplateService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +@RequiredArgsConstructor +public class CommunicationTemplateServiceImpl implements CommunicationTemplateService { + private final CommunicationTemplateRepository communicationTemplateRepository; + + @Override + public List findCommunicationTemplates(String campaignId) { + return communicationTemplateRepository.findCommunicationTemplates(campaignId); + } +} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java new file mode 100644 index 00000000..8df10577 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java @@ -0,0 +1,24 @@ +package fr.insee.pearljam.infrastructure.campaign.adapter; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.port.serverside.CommunicationTemplateRepository; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; +import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationTemplateJpaRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +@RequiredArgsConstructor +public class CommunicationTemplateDaoAdapter implements CommunicationTemplateRepository { + + private final CommunicationTemplateJpaRepository communicationTemplateRepository; + + @Override + public List findCommunicationTemplates(String campaignId) { + List communicationTemplates = communicationTemplateRepository + .findCommunicationTemplates(campaignId); + return CommunicationTemplateDB.toModel(communicationTemplates); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java index d2131301..414373fb 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java @@ -4,6 +4,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; +import java.util.List; import java.util.Optional; public interface CommunicationTemplateJpaRepository extends JpaRepository { @@ -13,4 +14,9 @@ public interface CommunicationTemplateJpaRepository extends JpaRepository findCommunicationTemplate(Long communicationTemplateId, String campaignId); + + @Query(""" + SELECT c FROM CommunicationTemplateDB c + WHERE c.campaign.id = ?1""") + List findCommunicationTemplates(String campaignId); } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java b/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java index c561ed8f..08c7f3b8 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java @@ -176,6 +176,8 @@ private void authorizeRequests(HttpSecurity http) throws Exception { .hasAnyRole(adminRole, localUserRole, nationalUserRole) .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGN_ID_VISIBILITIES) .hasRole(adminRole) + .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGN_ID_COMMUNICATION_TEMPLATES) + .hasRole(adminRole) .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGN_ID_REFERENTS) .hasAnyRole(adminRole, localUserRole, nationalUserRole) .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGNS_ID_ON_GOING) diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java index 50361b25..54e74b9a 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java @@ -28,13 +28,11 @@ void testFromModel() { CommunicationTemplateResponseDto dto1 = communicationDtos.get(0); assertThat(dto1.id()).isEqualTo(1L); - assertThat(dto1.messhugahId()).isEqualTo("msg1"); assertThat(dto1.medium()).isEqualTo(CommunicationMedium.EMAIL); assertThat(dto1.type()).isEqualTo(CommunicationType.NOTICE); CommunicationTemplateResponseDto dto2 = communicationDtos.get(1); assertThat(dto2.id()).isEqualTo(2L); - assertThat(dto2.messhugahId()).isEqualTo("msg2"); assertThat(dto2.medium()).isEqualTo(CommunicationMedium.LETTER); assertThat(dto2.type()).isEqualTo(CommunicationType.REMINDER); } diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java new file mode 100644 index 00000000..a0c3aacb --- /dev/null +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java @@ -0,0 +1,53 @@ +package fr.insee.pearljam.integration.campaign; + +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.transaction.annotation.Transactional; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +@ActiveProfiles("auth") +@AutoConfigureMockMvc +@ContextConfiguration +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Transactional +class CommunicationTemplateIT { + @Autowired + private MockMvc mockMvc; + + @Test + void testGetCommunicationTemplates() throws Exception { + MvcResult mvcResult = mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/communication-templates") + .with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)) + .accept(MediaType.APPLICATION_JSON)) + .andReturn(); + + String contentResult = mvcResult.getResponse().getContentAsString(); + String expectedResult = """ + [ + { + "id":1, + "medium":"EMAIL", + "type":"REMINDER" + }, + { + "id":2, + "medium":"LETTER", + "type":"NOTICE" + } + ] + """; + JSONAssert.assertEquals(expectedResult, contentResult, JSONCompareMode.NON_EXTENSIBLE); + } +} From 6cf5fdf358f83241eb9b4a563a75effcf307eb82 Mon Sep 17 00:00:00 2001 From: davdarras Date: Thu, 12 Sep 2024 14:13:13 +0200 Subject: [PATCH 26/48] doc: fix documentation on survey unit controller --- .../api/controller/SurveyUnitController.java | 58 +++++++++---------- 1 file changed, 26 insertions(+), 32 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java b/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java index 89388001..eee320a3 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java @@ -62,7 +62,7 @@ public class SurveyUnitController { /** * This method is used to post the list of SurveyUnit defined in request body - * + * @param surveyUnits survey units to create * @return List of {@link SurveyUnit} if exist, {@link HttpStatus} NOT_FOUND, or * {@link HttpStatus} FORBIDDEN */ @@ -76,8 +76,8 @@ public ResponseEntity postSurveyUnits(@RequestBody List getSurveyUnitById(@PathVariable(value /** * This method is used to update a specific survey unit - * @param surveyUnitDetails survey unit informations to update + * @param surveyUnitUpdateDto survey unit informations to update * @param id survey unit id * @return {@link SurveyUnitDetailDto} * @throws EntityNotFoundException exception thrown if entity not found @@ -196,12 +196,10 @@ public ResponseEntity getSurveyUnitsInTempZone() { } /** - * This method is used to update the state of Survey Units listed in request - * body - * - * @param request - * @param listSU - * @param state + * This method is used to update the state of a survey unit + * + * @param surveyUnitId survey unit id + * @param state state to set * @return {@link HttpStatus} */ @Operation(summary = "Update the state of Survey Units listed in request body") @@ -219,9 +217,8 @@ public ResponseEntity updateSurveyUnitState( * This method closes the survey unit {id} with the closing cause {closingCause} * Updates the closing cause if the SU is already closed * - * @param request - * @param id - * @param closingCause + * @param surveyUnitId survey unit id + * @param closingCause closing cause to set/update * @return {@link HttpStatus} */ @Operation(summary = "Closes a survey unit") @@ -240,10 +237,9 @@ public ResponseEntity closeSurveyUnit( /** * This method adds or updates the closing cause of the survey unit {id} * but does not modify its state - * - * @param request - * @param id - * @param closingCause + * + * @param surveyUnitId survey unit id + * @param closingCause closing cause to add * @return {@link HttpStatus} */ @Operation(summary = "Add Closing cause") @@ -269,9 +265,8 @@ public ResponseEntity updateSurveyUnitViewed(@PathVariable(value = "id") /** * This method is used to get survey units of a specific campaign * - * @param request - * @param id - * @param state + * @param id campaign id + * @param state search survey unit with this state * @return list of {@link SurveyUnitCampaignDto} if exists, else * {@link HttpStatus} FORBIDDEN or NOT_FOUND */ @@ -292,11 +287,14 @@ public ResponseEntity> getSurveyUnitByCampaignId( /** * This method is used to check if a user has access to an SU + * @param surveyUnitId survey unit id + * @param role role to check + * @return {@link HabilitationDto} the habilitation object */ @Operation(summary = "Check habilitation") @GetMapping(path = "/check-habilitation") public ResponseEntity checkHabilitation( - @RequestParam(value = "id") String id, + @RequestParam(value = "id") String surveyUnitId, @RequestParam(value = "role", required = false) String role) { String userId = authenticatedUserService.getCurrentUserId(); @@ -306,7 +304,7 @@ public ResponseEntity checkHabilitation( if (role == null) { log.info( "Check habilitation of {} without role for accessing survey-unit {} is denied. Please provide a role in request.", - userId, id); + userId, surveyUnitId); return new ResponseEntity<>(resp, HttpStatus.OK); } if (authenticatedUserService.hasRole(AuthorityRole.ADMIN)) { @@ -314,30 +312,29 @@ public ResponseEntity checkHabilitation( log.info( "Check habilitation of {} as {} for accessing survey-unit {} resulted in {} : Admin habilitation override", userId, - role.isBlank() ? "interviewer" : role, id, resp.isHabilitated()); + role.isBlank() ? "interviewer" : role, surveyUnitId, resp.isHabilitated()); return new ResponseEntity<>(resp, HttpStatus.OK); } if (role.isBlank()) { // interviewer - boolean checkdataBase = surveyUnitService.checkHabilitationInterviewer(userId, id); + boolean checkdataBase = surveyUnitService.checkHabilitationInterviewer(userId, surveyUnitId); boolean checkToken = authenticatedUserService.hasRole(AuthorityRole.INTERVIEWER); resp.setHabilitated(checkdataBase && checkToken); } else if (role.equals(Constants.REVIEWER)) { // local or national user - boolean checkdataBase = surveyUnitService.checkHabilitationReviewer(userId, id); + boolean checkdataBase = surveyUnitService.checkHabilitationReviewer(userId, surveyUnitId); boolean checkToken = authenticatedUserService.hasAnyRole(AuthorityRole.LOCAL_USER, AuthorityRole.NATIONAL_USER); resp.setHabilitated(checkdataBase && checkToken); } log.info("Check habilitation of {} as {} for accessing survey-unit {} resulted in {}", userId, - role.isBlank() ? "interviewer" : role, id, resp.isHabilitated()); + role.isBlank() ? "interviewer" : role, surveyUnitId, resp.isHabilitated()); return new ResponseEntity<>(resp, HttpStatus.OK); } /** * This method is used to get the list of states for a specific survey unit * - * @param request - * @param id + * @param id survey unit it * @return List of {@link StateDto} if exists, else {@link HttpStatus} FORBIDDEN * or NOT_FOUND */ @@ -358,8 +355,7 @@ public ResponseEntity getStatesBySurveyUnitId( /** * This method returns the list of states for a specific survey unit * - * @param request - * @param id + * @param request http servlet request * @return List of {@link StateDto} if exists, else {@link HttpStatus} FORBIDDEN * or NOT_FOUND */ @@ -399,7 +395,6 @@ public ResponseEntity deleteSurveyUnit(@PathVariable(value = "id") Strin /** * This method returns the list of all survey-unit ids * - * @param request * @return List of {@link String} */ @Operation(summary = "Get survey units id") @@ -414,7 +409,6 @@ public ResponseEntity> getAllSurveyUnitsId() { /** * This method returns the list of all survey-unit ids for specified campaign * - * @param request * @param id the id of campaign * @return List of {@link String} */ From e2e74638d5c1964d839a3107ee926f69ddfdbf4b Mon Sep 17 00:00:00 2001 From: davdarras Date: Mon, 16 Sep 2024 10:24:41 +0200 Subject: [PATCH 27/48] refactor: simplify survey unit retrieval - return directly survey unit from service or throw exceptions - refactor survey unit exception to return the survey unit id - adapt the survey unit deletion with the above changes --- .../pearljam/api/constants/Constants.java | 2 +- .../api/controller/SurveyUnitController.java | 60 +++------------- .../api/repository/SurveyUnitRepository.java | 8 +-- .../api/service/SurveyUnitService.java | 28 ++++---- .../api/service/impl/CampaignServiceImpl.java | 3 +- .../service/impl/SurveyUnitServiceImpl.java | 68 ++++++++++-------- .../dto/SurveyUnitInterviewerResponseDto.java | 72 +++++++++++++++++++ .../exception/ExceptionControllerAdvice.java | 5 ++ .../SurveyUnitNotFoundException.java | 8 +-- .../model/SurveyUnitForInterviewer.java | 12 ++++ .../config/OidcSecurityConfiguration.java | 2 +- .../surveyunit/adapter/CommentDaoAdapter.java | 2 +- .../api/authKeycloak/TestAuthKeyCloak.java | 6 +- .../controller/CommentControllerTest.java | 2 +- .../controller/SurveyUnitControllerTest.java | 2 +- .../controller/dummy/CommentFakeService.java | 2 +- .../dummy/SurveyUnitFakeService.java | 27 +++---- .../dummy/SurveyUnitFakeRepository.java | 2 +- .../service/dummy/CommentFakeRepository.java | 2 +- .../adapter/CommentDaoAdapterTest.java | 5 +- .../integration/surveyunit/SurveyUnitIT.java | 70 ++++++++++-------- 21 files changed, 228 insertions(+), 160 deletions(-) create mode 100644 src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitInterviewerResponseDto.java create mode 100644 src/main/java/fr/insee/pearljam/domain/surveyunit/model/SurveyUnitForInterviewer.java diff --git a/src/main/java/fr/insee/pearljam/api/constants/Constants.java b/src/main/java/fr/insee/pearljam/api/constants/Constants.java index b6b8409a..bc8a37ad 100644 --- a/src/main/java/fr/insee/pearljam/api/constants/Constants.java +++ b/src/main/java/fr/insee/pearljam/api/constants/Constants.java @@ -21,7 +21,7 @@ private Constants() { public static final String API_SURVEYUNITS = "/api/survey-units"; public static final String API_SURVEYUNITS_INTERVIEWERS = "/api/survey-units/interviewers"; public static final String API_SURVEYUNITS_CLOSABLE = "/api/survey-units/closable"; - + public static final String API_SURVEYUNIT_ID_INTERVIEWER = "/api/interviewer/survey-unit/{id}"; public static final String API_SURVEYUNIT_ID = "/api/survey-unit/{id}"; public static final String API_SURVEYUNIT_ID_STATE = "/api/survey-unit/{id}/state/{state}"; public static final String API_SURVEYUNIT_ID_STATES = "/api/survey-unit/{id}/states"; diff --git a/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java b/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java index eee320a3..d9186014 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java @@ -1,15 +1,14 @@ package fr.insee.pearljam.api.controller; import java.util.List; -import java.util.Optional; import java.util.Set; import fr.insee.pearljam.api.dto.surveyunit.*; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitInterviewerResponseDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.domain.exception.EntityNotFoundException; import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; import jakarta.servlet.http.HttpServletRequest; - import com.fasterxml.jackson.databind.JsonNode; import fr.insee.pearljam.api.domain.*; import jakarta.validation.Valid; @@ -31,8 +30,6 @@ import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.dto.state.StateDto; import fr.insee.pearljam.api.dto.state.SurveyUnitStatesDto; -import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.api.exception.SurveyUnitException; import fr.insee.pearljam.api.service.SurveyUnitService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; @@ -54,12 +51,9 @@ @Validated public class SurveyUnitController { - private static final String GUEST = "GUEST"; private final SurveyUnitService surveyUnitService; private final AuthenticatedUserService authenticatedUserService; - public static final String GET_SURVEY_UNIT_WITH_ID = "{} : GET SurveyUnit with id {} resulting in {}"; - /** * This method is used to post the list of SurveyUnit defined in request body * @param surveyUnits survey units to create @@ -113,42 +107,17 @@ public ResponseEntity> getListSurveyUnit( } /** - * This method is used to get the detail of surveyUnit for current interviewer + * This method is used to get the detail of survey unit for current interviewer * - * @param id the id of reporting unit + * @param surveyUnitId the id of reporting unit * @return List of {@link SurveyUnit} if exist, {@link HttpStatus} NOT_FOUND, or * {@link HttpStatus} FORBIDDEN */ @Operation(summary = "Get detail of specific survey unit ") - @GetMapping(path = "/survey-unit/{id}") - public ResponseEntity getSurveyUnitById(@PathVariable(value = "id") String id) { + @GetMapping(path = "/interviewer/survey-unit/{id}") + public SurveyUnitInterviewerResponseDto getSurveyUnitById(@PathVariable(value = "id") String surveyUnitId) { String userId = authenticatedUserService.getCurrentUserId(); - Optional su = surveyUnitService.findById(id); - if (!su.isPresent()) { - log.error("{} : Survey unit with id {} was not found in database", userId, id); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - if (!userId.equals(GUEST) && !surveyUnitService.findByIdAndInterviewerIdIgnoreCase(id, userId).isPresent()) { - log.error("Survey unit with id {} is not associated to the interviewer {}", id, userId); - return new ResponseEntity<>(HttpStatus.FORBIDDEN); - } - SurveyUnitDetailDto surveyUnit; - try { - surveyUnit = surveyUnitService.getSurveyUnitDetail(userId, id); - } catch (NotFoundException | SurveyUnitException e) { - log.error(e.getMessage()); - log.info(GET_SURVEY_UNIT_WITH_ID, userId, id, HttpStatus.NOT_FOUND); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } catch (Exception e) { - log.error(e.getMessage()); - log.info(GET_SURVEY_UNIT_WITH_ID, userId, id, HttpStatus.INTERNAL_SERVER_ERROR); - return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); - } - - log.info(GET_SURVEY_UNIT_WITH_ID, userId, id, HttpStatus.OK); - - return new ResponseEntity<>(surveyUnit, HttpStatus.OK); - + return surveyUnitService.getSurveyUnitInterviewerDetail(userId, surveyUnitId); } /** @@ -373,23 +342,16 @@ public ResponseEntity> getClosableSurveyUnits(HttpSe /** * This method is used to delete a survey-unit * - * @param id the id of survey-unit + * @param surveyUnitId the id of survey-unit * @return {@link HttpStatus} */ @Operation(summary = "Delete survey-unit") @DeleteMapping(path = "/survey-unit/{id}") - public ResponseEntity deleteSurveyUnit(@PathVariable(value = "id") String id) { + public void deleteSurveyUnit(@PathVariable(value = "id") String surveyUnitId) { String userId = authenticatedUserService.getCurrentUserId(); - log.info("{} try to DELETE survey-unit {}", userId, id); - - Optional surveyUnitOptional = surveyUnitService.findById(id); - if (!surveyUnitOptional.isPresent()) { - log.error("DELETE survey-unit with id {} resulting in 404 because it does not exists", id); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - surveyUnitService.delete(surveyUnitOptional.get()); - log.info("DELETE survey-unit with id {} resulting in 200", id); - return ResponseEntity.ok().build(); + log.info("{} try to DELETE survey-unit {}", userId, surveyUnitId); + surveyUnitService.delete(surveyUnitId); + log.info("DELETE survey-unit with id {} resulting in 200", surveyUnitId); } /** diff --git a/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java b/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java index 882beeef..a1890274 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java @@ -46,11 +46,11 @@ public interface SurveyUnitRepository extends JpaRepository /** * This method retrieve the SurveyUnit in DB by Id and UserId - * @param id - * @param userId - * @return SurveyUnit + * @param surveyUnitId survey unit id + * @param userId user id + * @return the survey unit */ - Optional findByIdAndInterviewerIdIgnoreCase(String id, String userId); + Optional findByIdAndInterviewerIdIgnoreCase(String surveyUnitId, String userId); /** * This method retrieve all the Ids of the SurveyUnits in db diff --git a/src/main/java/fr/insee/pearljam/api/service/SurveyUnitService.java b/src/main/java/fr/insee/pearljam/api/service/SurveyUnitService.java index 7b9474c7..4fc67cd2 100644 --- a/src/main/java/fr/insee/pearljam/api/service/SurveyUnitService.java +++ b/src/main/java/fr/insee/pearljam/api/service/SurveyUnitService.java @@ -1,13 +1,14 @@ package fr.insee.pearljam.api.service; import java.util.List; -import java.util.Optional; import java.util.Set; import fr.insee.pearljam.api.dto.surveyunit.*; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitInterviewerResponseDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.domain.exception.PersonNotFoundException; import fr.insee.pearljam.domain.exception.SurveyUnitNotFoundException; +import fr.insee.pearljam.domain.surveyunit.model.SurveyUnitForInterviewer; import jakarta.servlet.http.HttpServletRequest; import com.fasterxml.jackson.databind.JsonNode; @@ -15,8 +16,6 @@ import org.springframework.http.HttpStatus; import fr.insee.pearljam.api.dto.state.StateDto; -import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.api.exception.SurveyUnitException; /** * Service for the SurveyUnit entity @@ -28,14 +27,12 @@ public interface SurveyUnitService { /** * Retrieve the SurveyUnitDetail entity by Id and UserId - * - * @param userId - * @param id - * @return {@link SurveyUnitDetailDto} - * @throws SurveyUnitException - * @throws NotFoundException + * + * @param userId user id + * @param surveyUnitId survey unit id + * @return {@link SurveyUnitForInterviewer} */ - SurveyUnitDetailDto getSurveyUnitDetail(String userId, String id) throws SurveyUnitException, NotFoundException; + SurveyUnitInterviewerResponseDto getSurveyUnitInterviewerDetail(String userId, String surveyUnitId); /** * Retrieve all the SurveyUnit entity by userId @@ -78,9 +75,12 @@ SurveyUnitDetailDto updateSurveyUnit(String userId, String id, */ List getListStatesBySurveyUnitId(String suId); - public Optional findByIdAndInterviewerIdIgnoreCase(String userId, String id); - - public Optional findById(String id); + /** + * + * @param surveyUnitId survey unit id + * @return {@link SurveyUnit} the survey unit + */ + SurveyUnit getSurveyUnit(String surveyUnitId); List getClosableSurveyUnits(HttpServletRequest request, String userId); @@ -100,7 +100,7 @@ SurveyUnitDetailDto updateSurveyUnit(String userId, String id, boolean checkHabilitationReviewer(String userId, String id); - void delete(SurveyUnit surveyUnit); + void delete(String surveyUnitId); void saveSurveyUnitToTempZone(String id, String userId, JsonNode surveyUnit); diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index a0350546..15bdfee9 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -197,7 +197,8 @@ public void delete(String campaignId, boolean force) throws CampaignNotFoundExce if (!force && isCampaignOngoing(campaignId)) { throw new CampaignOnGoingException(); } - surveyUnitRepository.findByCampaignId(campaign.getId()).stream().forEach(surveyUnitService::delete); + surveyUnitRepository.findByCampaignId(campaign.getId()) + .forEach(surveyunit -> surveyUnitService.delete(surveyunit.getId())); userRepository.findAll() .forEach(user -> { List lstCampaignId = new ArrayList<>(user.getCampaigns().stream().map(Campaign::getId) diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java index c5f4bcf5..b2be293a 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java @@ -12,13 +12,17 @@ import java.util.stream.Stream; import fr.insee.pearljam.api.dto.surveyunit.*; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitInterviewerResponseDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitVisibilityDto; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; +import fr.insee.pearljam.domain.campaign.port.userside.CommunicationTemplateService; import fr.insee.pearljam.domain.exception.PersonNotFoundException; import fr.insee.pearljam.domain.exception.SurveyUnitNotFoundException; import fr.insee.pearljam.domain.surveyunit.model.IdentificationState; import fr.insee.pearljam.api.service.SurveyUnitUpdateService; +import fr.insee.pearljam.domain.surveyunit.model.SurveyUnitForInterviewer; import jakarta.servlet.http.HttpServletRequest; import com.fasterxml.jackson.databind.JsonNode; @@ -38,8 +42,6 @@ import fr.insee.pearljam.api.dto.person.PersonDto; import fr.insee.pearljam.api.dto.state.StateDto; import fr.insee.pearljam.api.exception.BadRequestException; -import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.api.exception.SurveyUnitException; import fr.insee.pearljam.api.service.SurveyUnitService; import fr.insee.pearljam.api.service.UserService; import fr.insee.pearljam.api.service.UtilsService; @@ -75,6 +77,7 @@ public class SurveyUnitServiceImpl implements SurveyUnitService { private final UserService userService; private final UtilsService utilsService; private final SurveyUnitUpdateService surveyUnitUpdateService; + private final CommunicationTemplateService communicationTemplateService; @Override public boolean checkHabilitationInterviewer(String userId, String id) { @@ -90,25 +93,32 @@ public boolean checkHabilitationReviewer(String userId, String id) { return !surveyUnitRepository.findByIdInOrganizationalUnit(id, userOUs).isEmpty(); } - public Optional findById(String id) { - return surveyUnitRepository.findById(id); + @Override + public SurveyUnit getSurveyUnit(String surveyUnitId) { + return surveyUnitRepository + .findById(surveyUnitId) + .orElseThrow(() -> new SurveyUnitNotFoundException(surveyUnitId)); } - public Optional findByIdAndInterviewerIdIgnoreCase(String userId, String id) { - return surveyUnitRepository.findByIdAndInterviewerIdIgnoreCase(userId, id); - } + @Override + public SurveyUnitInterviewerResponseDto getSurveyUnitInterviewerDetail(String userId, String surveyUnitId) { + SurveyUnit surveyUnit = surveyUnitRepository + .findByIdAndInterviewerIdIgnoreCase(surveyUnitId, userId) + .orElseThrow(() -> { + log.error("Survey unit with id {} is not associated to the interviewer {}", surveyUnitId, userId); + return new SurveyUnitNotFoundException(surveyUnitId); + }); - public SurveyUnitDetailDto getSurveyUnitDetail(String userId, String id) - throws SurveyUnitException, NotFoundException { - Optional surveyUnit = surveyUnitRepository.findById(id); - if (!surveyUnit.isPresent()) { - throw new NotFoundException(String.format("Survey unit with id %s was not found in database", id)); + if (!canBeSeenByInterviewer(surveyUnit.getId())) { + log.error(String.format("Survey unit with id %s is not associated to the interviewer %s anymore", surveyUnitId, userId)); + throw new SurveyUnitNotFoundException(surveyUnitId); } - if (!canBeSeenByInterviewer(surveyUnit.get().getId())) { - throw new SurveyUnitException( - String.format("Survey unit with id %s is not associated to the interviewer %s", id, userId)); - } - return new SurveyUnitDetailDto(surveyUnit.get()); + + List communicationTemplates = communicationTemplateService.findCommunicationTemplates(surveyUnit.getCampaign().getId()); + SurveyUnitForInterviewer surveyUnitForInterviewer = new SurveyUnitForInterviewer(surveyUnit, communicationTemplates); + // TODO: when refacto survey unit, return model object instead of dto here + // cannot do this now as the hibernate session is not propagated to the controller + return SurveyUnitInterviewerResponseDto.fromModel(surveyUnitForInterviewer); } public List getSurveyUnitDto(String userId, Boolean extended) { @@ -138,17 +148,17 @@ public boolean canBeSeenByInterviewer(String suId) { } @Transactional - public SurveyUnitDetailDto updateSurveyUnit(String userId, String id, - SurveyUnitUpdateDto surveyUnitUpdate) throws SurveyUnitNotFoundException, PersonNotFoundException { - log.info("Update Survey Unit {}", id); + public SurveyUnitDetailDto updateSurveyUnit(String userId, String surveyUnitId, + SurveyUnitUpdateDto surveyUnitUpdate) throws PersonNotFoundException { + log.info("Update Survey Unit {}", surveyUnitId); Optional surveyUnitOpt; if (userId.equals(GUEST)) { - surveyUnitOpt = surveyUnitRepository.findById(id); + surveyUnitOpt = surveyUnitRepository.findById(surveyUnitId); } else { - surveyUnitOpt = surveyUnitRepository.findByIdAndInterviewerIdIgnoreCase(id, userId); + surveyUnitOpt = surveyUnitRepository.findByIdAndInterviewerIdIgnoreCase(surveyUnitId, userId); } - SurveyUnit surveyUnit = surveyUnitOpt.orElseThrow(SurveyUnitNotFoundException::new); + SurveyUnit surveyUnit = surveyUnitOpt.orElseThrow(() -> new SurveyUnitNotFoundException(surveyUnitId)); surveyUnit.setMove(surveyUnitUpdate.move()); updateAddress(surveyUnit, surveyUnitUpdate); updatePersons(surveyUnitUpdate); @@ -160,8 +170,8 @@ public SurveyUnitDetailDto updateSurveyUnit(String userId, String id, surveyUnitUpdateService.updateSurveyUnitInfos(surveyUnit, surveyUnitUpdate); surveyUnitRepository.save(surveyUnit); - log.info("Survey Unit {} - update complete", id); - return new SurveyUnitDetailDto(surveyUnitRepository.findById(id).get()); + log.info("Survey Unit {} - update complete", surveyUnitId); + return new SurveyUnitDetailDto(surveyUnitRepository.findById(surveyUnitId).get()); } private void updateContactOutcome(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto) { @@ -466,8 +476,7 @@ public HttpStatus updateClosingCause(String surveyUnitId, ClosingCauseType type) } } - @Transactional - public void addOrModifyClosingCause(SurveyUnit surveyUnit, ClosingCauseType type) { + private void addOrModifyClosingCause(SurveyUnit surveyUnit, ClosingCauseType type) { ClosingCause cc; if (surveyUnit.getClosingCause() != null) { cc = surveyUnit.getClosingCause(); @@ -602,9 +611,10 @@ public Response createSurveyUnitInterviewerLinks(List persons, + AddressDto address, + Boolean priority, + Boolean move, + String campaign, + List comments, + SampleIdentifiersDto sampleIdentifiers, + List states, + List contactAttempts, + ContactOutcomeDto contactOutcome, + IdentificationDto identification, + List communicationTemplates, + List communicationRequests) { + + public static SurveyUnitInterviewerResponseDto fromModel(SurveyUnitForInterviewer surveyUnitForInterviewer) { + SurveyUnit surveyUnit = surveyUnitForInterviewer.surveyUnit(); + List persons = surveyUnit.getPersons().stream() + .map(PersonDto::new) + .toList(); + + List comments = CommentDto.fromModel(surveyUnit.getModelComments()); + AddressDto address = new AddressDto(surveyUnit.getAddress()); + List contactAttempts = surveyUnit + .getContactAttempts() + .stream() + .map(ContactAttemptDto::new) + .toList(); + List states = surveyUnit + .getStates() + .stream() + .sorted(Comparator.comparing(State::getDate, Comparator.nullsLast(Comparator.reverseOrder()))) + .filter(s -> BussinessRules.stateCanBeSeenByInterviewerBussinessRules(s.getType())) + .map(StateDto::new) + .toList(); + ContactOutcomeDto contactOutcome = null; + if (surveyUnit.getContactOucome() != null) { + contactOutcome = new ContactOutcomeDto(surveyUnit.getContactOucome()); + } + + SampleIdentifiersDto sampleIdentifiers = null; + if (surveyUnit.getSampleIdentifier() != null) { + sampleIdentifiers = new SampleIdentifiersDto(surveyUnit.getSampleIdentifier()); + } + return new SurveyUnitInterviewerResponseDto(surveyUnit.getId(), persons, address, + surveyUnit.isPriority(), surveyUnit.getMove(), surveyUnit.getCampaign().getId(), + comments, sampleIdentifiers, states, contactAttempts, contactOutcome, + IdentificationDto.fromModel(surveyUnit.getModelIdentification()), + CommunicationTemplateResponseDto.fromModel(surveyUnitForInterviewer.communicationTemplates()), + CommunicationRequestResponseDto.fromModel(surveyUnit.getModelCommunicationRequests())); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java index 0b7b1e1b..0760524f 100644 --- a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java +++ b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java @@ -130,6 +130,11 @@ public ResponseEntity exceptions(CommunicationTemplateNotFoundExceptio return generateResponseError(e, HttpStatus.NOT_FOUND, request); } + @ExceptionHandler(SurveyUnitNotFoundException.class) + public ResponseEntity exceptions(SurveyUnitNotFoundException e, WebRequest request) { + return generateResponseError(e, HttpStatus.NOT_FOUND, request); + } + @ExceptionHandler(VisibilityHasInvalidDatesException.class) public ResponseEntity exceptions(VisibilityHasInvalidDatesException e, WebRequest request) { return generateResponseError(e, HttpStatus.CONFLICT, request); diff --git a/src/main/java/fr/insee/pearljam/domain/exception/SurveyUnitNotFoundException.java b/src/main/java/fr/insee/pearljam/domain/exception/SurveyUnitNotFoundException.java index 58391b09..0629c1d2 100644 --- a/src/main/java/fr/insee/pearljam/domain/exception/SurveyUnitNotFoundException.java +++ b/src/main/java/fr/insee/pearljam/domain/exception/SurveyUnitNotFoundException.java @@ -1,10 +1,10 @@ package fr.insee.pearljam.domain.exception; -public class SurveyUnitNotFoundException extends EntityNotFoundException { +public class SurveyUnitNotFoundException extends RuntimeException { - public static final String MESSAGE = "Survey unit not found"; + public static final String MESSAGE = "Survey unit %s not found"; - public SurveyUnitNotFoundException() { - super(MESSAGE); + public SurveyUnitNotFoundException(String id) { + super(String.format(MESSAGE, id)); } } diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/SurveyUnitForInterviewer.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/SurveyUnitForInterviewer.java new file mode 100644 index 00000000..430ad7ef --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/SurveyUnitForInterviewer.java @@ -0,0 +1,12 @@ +package fr.insee.pearljam.domain.surveyunit.model; + +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; + +import java.util.List; + +public record SurveyUnitForInterviewer( + SurveyUnit surveyUnit, + List communicationTemplates +) { +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java b/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java index 08c7f3b8..da4b5c35 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java @@ -110,7 +110,7 @@ private void authorizeRequests(HttpSecurity http) throws Exception { .hasRole(adminRole) .requestMatchers(HttpMethod.GET, Constants.API_SURVEYUNITS_CLOSABLE) .hasAnyRole(adminRole, localUserRole, nationalUserRole) - .requestMatchers(HttpMethod.GET, Constants.API_SURVEYUNIT_ID) + .requestMatchers(HttpMethod.GET, Constants.API_SURVEYUNIT_ID_INTERVIEWER) .hasAnyRole(adminRole, interviewerRole) .requestMatchers(HttpMethod.PUT, Constants.API_SURVEYUNIT_ID) .hasAnyRole(adminRole, interviewerRole) diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommentDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommentDaoAdapter.java index b05cb2b8..2580e10f 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommentDaoAdapter.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommentDaoAdapter.java @@ -23,7 +23,7 @@ public class CommentDaoAdapter implements CommentRepository { public void updateComment(Comment comment) throws SurveyUnitNotFoundException { SurveyUnit surveyUnit = surveyUnitRepository .findById(comment.surveyUnitId()) - .orElseThrow(SurveyUnitNotFoundException::new); + .orElseThrow(() -> new SurveyUnitNotFoundException(comment.surveyUnitId())); Set existingComments = surveyUnit.getComments(); diff --git a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java index c2e0d4b0..7f0ef5e0 100644 --- a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java +++ b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java @@ -513,8 +513,8 @@ void testGetCampaignInterviewerStateCountNotFoundIntw() throws Exception { */ @Test @Order(13) - void testGetSurveyUnitDetailNotFound() throws Exception { - mockMvc.perform(get("/api/survey-unit/123456789") + void testGetSurveyUnitInterviewerDetailNotFound() throws Exception { + mockMvc.perform(get("/api/interviewer/survey-unit/123456789") .with(authentication(ADMIN)) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); @@ -1148,7 +1148,7 @@ void testPutCommentOnSu() throws Exception { .content(comment)) .andExpect(status().isOk()); - mockMvc.perform(get("/api/survey-unit/11") + mockMvc.perform(get("/api/interviewer/survey-unit/11") .with(authentication(INTERVIEWER)) .accept(MediaType.APPLICATION_JSON)) .andExpectAll( diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java index ffbdf216..8be533d8 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/CommentControllerTest.java @@ -108,7 +108,7 @@ void updateComment04() throws Exception { .andExpectAll(status().isNotFound(), jsonPath("$.code").value(HttpStatus.NOT_FOUND.value()), jsonPath("$.path").value(updatePath), - jsonPath("$.message").value(SurveyUnitNotFoundException.MESSAGE), + jsonPath("$.message").value(String.format(SurveyUnitNotFoundException.MESSAGE, "1")), jsonPath("$.timestamp", new StructureDateMatcher())); assertThat(commentService.getCommentUpdated()).isNull(); } diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java index 2b0e103b..d4c8c32b 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java @@ -111,7 +111,7 @@ void updateSurveyUnit02() throws Exception { mockMvc.perform(put(updatePath) .contentType(MediaType.APPLICATION_JSON) .content(surveyUnitJson)) - .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updatePath, SurveyUnitNotFoundException.MESSAGE)); + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updatePath, String.format(SurveyUnitNotFoundException.MESSAGE,1))); assertThat(surveyUnitService.getSurveyUnitUpdated()).isNull(); } diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/CommentFakeService.java b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/CommentFakeService.java index 3158a3b1..c145e68f 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/CommentFakeService.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/CommentFakeService.java @@ -16,7 +16,7 @@ public class CommentFakeService implements CommentService { @Override public void updateSurveyUnitComment(Comment comment) throws SurveyUnitNotFoundException { if(shouldThrowException) { - throw new SurveyUnitNotFoundException(); + throw new SurveyUnitNotFoundException(comment.surveyUnitId()); } commentUpdated = comment; } diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/SurveyUnitFakeService.java b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/SurveyUnitFakeService.java index f62c48b1..bb505701 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/SurveyUnitFakeService.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/dummy/SurveyUnitFakeService.java @@ -4,9 +4,8 @@ import fr.insee.pearljam.api.domain.*; import fr.insee.pearljam.api.dto.state.StateDto; import fr.insee.pearljam.api.dto.surveyunit.*; -import fr.insee.pearljam.api.exception.NotFoundException; -import fr.insee.pearljam.api.exception.SurveyUnitException; import fr.insee.pearljam.api.service.SurveyUnitService; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitInterviewerResponseDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.domain.exception.PersonNotFoundException; import fr.insee.pearljam.domain.exception.SurveyUnitNotFoundException; @@ -16,7 +15,6 @@ import org.springframework.http.HttpStatus; import java.util.List; -import java.util.Optional; import java.util.Set; public class SurveyUnitFakeService implements SurveyUnitService { @@ -30,20 +28,15 @@ public class SurveyUnitFakeService implements SurveyUnitService { @Getter private SurveyUnitUpdateDto surveyUnitUpdated = null; - @Override - public SurveyUnitDetailDto getSurveyUnitDetail(String userId, String id) throws SurveyUnitException, NotFoundException { - throw new IllegalArgumentException("not implemented yet"); - } - @Override public List getSurveyUnitDto(String userId, Boolean extended) { throw new IllegalArgumentException("not implemented yet"); } @Override - public SurveyUnitDetailDto updateSurveyUnit(String userId, String id, SurveyUnitUpdateDto surveyUnitUpdateDto) throws SurveyUnitNotFoundException, PersonNotFoundException { + public SurveyUnitDetailDto updateSurveyUnit(String userId, String surveyUnitId, SurveyUnitUpdateDto surveyUnitUpdateDto) throws SurveyUnitNotFoundException, PersonNotFoundException { if(shouldThrowSurveyUnitException) { - throw new SurveyUnitNotFoundException(); + throw new SurveyUnitNotFoundException(surveyUnitId); } if(shouldThrowPersonException) { @@ -69,12 +62,7 @@ public List getListStatesBySurveyUnitId(String suId) { } @Override - public Optional findByIdAndInterviewerIdIgnoreCase(String userId, String id) { - throw new IllegalArgumentException("not implemented yet"); - } - - @Override - public Optional findById(String id) { + public SurveyUnit getSurveyUnit(String surveyUnitId) { throw new IllegalArgumentException("not implemented yet"); } @@ -124,7 +112,7 @@ public boolean checkHabilitationReviewer(String userId, String id) { } @Override - public void delete(SurveyUnit surveyUnit) { + public void delete(String surveyUnitId) { throw new IllegalArgumentException("not implemented yet"); } @@ -162,4 +150,9 @@ public List getAllIdsByInterviewerId(String interviewerId) { public void removeInterviewerLink(List ids) { throw new IllegalArgumentException("not implemented yet"); } + + @Override + public SurveyUnitInterviewerResponseDto getSurveyUnitInterviewerDetail(String userId, String surveyUnitId) { + return null; + } } diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java index 8ca23f2b..5357220a 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java @@ -27,7 +27,7 @@ public Integer findCountUeINATBRByInterviewerIdAndCampaignId(String idInterviewe } @Override - public Optional findByIdAndInterviewerIdIgnoreCase(String id, String userId) { + public Optional findByIdAndInterviewerIdIgnoreCase(String surveyUnitId, String userId) { return Optional.empty(); } diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommentFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommentFakeRepository.java index 4d13d72b..9666d696 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommentFakeRepository.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommentFakeRepository.java @@ -19,7 +19,7 @@ public class CommentFakeRepository implements CommentRepository { @Override public void updateComment(Comment comment) throws SurveyUnitNotFoundException { if(shouldThrowException) { - throw new SurveyUnitNotFoundException(); + throw new SurveyUnitNotFoundException(comment.surveyUnitId()); } commentUpdated = comment; } diff --git a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommentDaoAdapterTest.java b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommentDaoAdapterTest.java index 6582a454..c16bc4de 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommentDaoAdapterTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommentDaoAdapterTest.java @@ -79,10 +79,11 @@ void testUpdateComment01() throws SurveyUnitNotFoundException { @Test @DisplayName("Should throw exception when survey unit doesn't exist") void testUpdateComment02() { - Comment comment = new Comment(CommentType.INTERVIEWER, "value4", "marvelous-id"); + String invalidSurveyUnitId = "invalid-id"; + Comment comment = new Comment(CommentType.INTERVIEWER, "value4", invalidSurveyUnitId); assertThatThrownBy(() -> commentDaoAdapter.updateComment(comment)) .isInstanceOf(SurveyUnitNotFoundException.class) - .hasMessage(SurveyUnitNotFoundException.MESSAGE); + .hasMessage(String.format(SurveyUnitNotFoundException.MESSAGE, invalidSurveyUnitId)); } } diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index f6b64464..bb57cb16 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -103,7 +103,7 @@ void testGetAllSurveyUnits() throws Exception { */ @Test void testGetSurveyUnitDetail() throws Exception { - MvcResult result = mockMvc.perform(get("/api/survey-unit/11") + MvcResult result = mockMvc.perform(get("/api/interviewer/survey-unit/11") .with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)) .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk()) @@ -115,15 +115,20 @@ void testGetSurveyUnitDetail() throws Exception { "id":"11", "persons":[ { - "id":6, - "title":"MISS", - "firstName":"Christine", - "lastName":"Aguilar", + "id":1, + "title":"MISTER", + "firstName":"Ted", + "lastName":"Farmer", "email":"test@test.com", "birthdate":11111111, "favoriteEmail":true, - "privileged":false, + "privileged":true, "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":false, + "number":"+33677542802" + }, { "source":"FISCAL", "favorite":true, @@ -132,10 +137,10 @@ void testGetSurveyUnitDetail() throws Exception { ] }, { - "id":7, + "id":6, "title":"MISS", - "firstName":"Louise", - "lastName":"Walker", + "firstName":"Christine", + "lastName":"Aguilar", "email":"test@test.com", "birthdate":11111111, "favoriteEmail":true, @@ -149,20 +154,15 @@ void testGetSurveyUnitDetail() throws Exception { ] }, { - "id":1, - "title":"MISTER", - "firstName":"Ted", - "lastName":"Farmer", + "id":7, + "title":"MISS", + "firstName":"Louise", + "lastName":"Walker", "email":"test@test.com", "birthdate":11111111, "favoriteEmail":true, - "privileged":true, + "privileged":false, "phoneNumbers":[ - { - "source":"FISCAL", - "favorite":false, - "number":"+33677542802" - }, { "source":"FISCAL", "favorite":true, @@ -222,10 +222,22 @@ void testGetSurveyUnitDetail() throws Exception { "category":"PRIMARY", "occupant":"IDENTIFIED" }, + "communicationTemplates":[ + { + "id":1, + "medium":"EMAIL", + "type":"REMINDER" + }, + { + "id":2, + "medium":"LETTER", + "type":"NOTICE" + } + ], "communicationRequests":[ { - "communicationTemplateId":2, - "reason":"UNREACHABLE", + "communicationTemplateId":1, + "reason":"REFUSAL", "emitter":"INTERVIEWER", "status":[ { @@ -233,14 +245,18 @@ void testGetSurveyUnitDetail() throws Exception { "status":"INITIATED" }, { - "date":1721903756310, + "date":1721903755305, "status":"READY" + }, + { + "date":1721903756305, + "status":"SUBMITTED" } ] }, { - "communicationTemplateId":1, - "reason":"REFUSAL", + "communicationTemplateId":2, + "reason":"UNREACHABLE", "emitter":"INTERVIEWER", "status":[ { @@ -248,12 +264,8 @@ void testGetSurveyUnitDetail() throws Exception { "status":"INITIATED" }, { - "date":1721903755305, + "date":1721903756310, "status":"READY" - }, - { - "date":1721903756305, - "status":"SUBMITTED" } ] } From 58734aa8e3f93e5d4a5e33b812a439acc77c7f74 Mon Sep 17 00:00:00 2001 From: davdarras Date: Mon, 16 Sep 2024 10:46:36 +0200 Subject: [PATCH 28/48] fix: keep old survey unit endpoint for retrocompatibility --- .../fr/insee/pearljam/api/controller/SurveyUnitController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java b/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java index d9186014..9e7053b5 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java @@ -114,7 +114,7 @@ public ResponseEntity> getListSurveyUnit( * {@link HttpStatus} FORBIDDEN */ @Operation(summary = "Get detail of specific survey unit ") - @GetMapping(path = "/interviewer/survey-unit/{id}") + @GetMapping(path = {"/interviewer/survey-unit/{id}", "/survey-unit/{id}"}) public SurveyUnitInterviewerResponseDto getSurveyUnitById(@PathVariable(value = "id") String surveyUnitId) { String userId = authenticatedUserService.getCurrentUserId(); return surveyUnitService.getSurveyUnitInterviewerDetail(userId, surveyUnitId); From 4569d4e0e3c9581cfb3a7f601f5e0ffddfb30770 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 17 Sep 2024 10:40:21 +0200 Subject: [PATCH 29/48] fix: keep acl for the old su endpoint --- .../security/config/OidcSecurityConfiguration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java b/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java index da4b5c35..01c845be 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java @@ -110,7 +110,7 @@ private void authorizeRequests(HttpSecurity http) throws Exception { .hasRole(adminRole) .requestMatchers(HttpMethod.GET, Constants.API_SURVEYUNITS_CLOSABLE) .hasAnyRole(adminRole, localUserRole, nationalUserRole) - .requestMatchers(HttpMethod.GET, Constants.API_SURVEYUNIT_ID_INTERVIEWER) + .requestMatchers(HttpMethod.GET, Constants.API_SURVEYUNIT_ID_INTERVIEWER, Constants.API_SURVEYUNIT_ID) .hasAnyRole(adminRole, interviewerRole) .requestMatchers(HttpMethod.PUT, Constants.API_SURVEYUNIT_ID) .hasAnyRole(adminRole, interviewerRole) From 24e4587dcd99296206a8483fca5f7c2086d05332 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 17 Sep 2024 10:36:31 +0200 Subject: [PATCH 30/48] feat: handle communication informations for campaign/ou link - create communication informations from campaign creation endpoint - recreate communication informations from campaign update endpoint - update a communication information from a new endpoint (all fields are mandatory) - get communication informations from the get campaign endpoint --- .../CommunicationInformationController.java | 72 +++++++++++++ .../campaign/dto/input/CampaignCreateDto.java | 2 + .../campaign/dto/input/CampaignUpdateDto.java | 2 + ...unicationInformationCampaignCreateDto.java | 35 ++++++ ...unicationInformationCampaignUpdateDto.java | 36 +++++++ .../CommunicationInformationUpdateDto.java | 38 +++++++ .../dto/output/CampaignResponseDto.java | 7 +- .../CommunicationInformationResponseDto.java | 23 ++++ .../pearljam/api/constants/Constants.java | 2 + .../api/controller/CampaignController.java | 10 +- .../insee/pearljam/api/domain/Campaign.java | 4 + .../pearljam/api/service/CampaignService.java | 2 +- .../api/service/impl/CampaignServiceImpl.java | 31 +++++- .../exception/ExceptionControllerAdvice.java | 5 + .../CommunicationInformation.java | 10 ++ .../CommunicationInformationRepository.java | 39 +++++++ .../CommunicationInformationService.java | 35 ++++++ .../CommunicationInformationServiceImpl.java | 38 +++++++ ...unicationInformationNotFoundException.java | 10 ++ .../CommunicationInformationDaoAdapter.java | 78 ++++++++++++++ .../entity/CommunicationInformationDB.java | 67 ++++++++++++ .../entity/CommunicationInformationDBId.java | 41 +++++++ ...CommunicationInformationJpaRepository.java | 20 ++++ .../config/OidcSecurityConfiguration.java | 4 + .../543_create_communication_information.xml | 23 ++++ .../resources/db/dataset/init-demo-data.sql | 11 ++ .../resources/db/dataset/reinit-test-data.sql | 11 ++ src/main/resources/db/master.xml | 5 +- .../CampaignControllerCreateTest.java | 16 ++- .../controller/CampaignControllerTest.java | 2 +- .../CampaignControllerUpdateTest.java | 15 +++ .../service/CampaignServiceImplTest.java | 33 ++++-- .../CommunicationInformationFakeService.java | 27 +++++ .../integration/campaign/CampaignIT.java | 102 +++++++++++++++--- .../campaign/CommunicationInformationIT.java | 92 ++++++++++++++++ 35 files changed, 908 insertions(+), 40 deletions(-) create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationController.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java create mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationInformationService.java create mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationInformationServiceImpl.java create mode 100644 src/main/java/fr/insee/pearljam/domain/exception/CommunicationInformationNotFoundException.java create mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java create mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java create mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDBId.java create mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java create mode 100644 src/main/resources/db/changelog/543_create_communication_information.xml create mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java create mode 100644 src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java diff --git a/src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationController.java b/src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationController.java new file mode 100644 index 00000000..534e850f --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationController.java @@ -0,0 +1,72 @@ +package fr.insee.pearljam.api.campaign.controller; + +import fr.insee.pearljam.api.campaign.dto.input.CommunicationInformationUpdateDto; +import fr.insee.pearljam.api.campaign.dto.output.CommunicationInformationResponseDto; +import fr.insee.pearljam.api.campaign.dto.output.VisibilityCampaignDto; +import fr.insee.pearljam.api.constants.Constants; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; +import fr.insee.pearljam.domain.campaign.port.userside.CommunicationInformationService; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@Tag(name = "01. Campaigns", description = "Endpoints for campaigns") +@Slf4j +@RequiredArgsConstructor +@Validated +public class CommunicationInformationController { + private final CommunicationInformationService communicationInformationService; + private final AuthenticatedUserService authenticatedUserService; + + /** + * This method returns the list of communication informations associated with the + * campaign {id} + * + * @param campaignId campaign id + * @return List of {@link VisibilityCampaignDto} + */ + @Operation(summary = "Get campaign communication informations") + @GetMapping(path = Constants.API_CAMPAIGN_ID_COMMUNICATION_INFORMATIONS) + public List getCommunicationInformations(@NotBlank @PathVariable(value = "id") String campaignId) throws CampaignNotFoundException { + String userId = authenticatedUserService.getCurrentUserId(); + log.info("{} try to get campaign[{}] communication informations ", userId, campaignId); + + List communicationInformations = communicationInformationService.findCommunicationInformations(campaignId); + return CommunicationInformationResponseDto.fromModel(communicationInformations); + } + + /** + * Update the communication information for a given campaign and organizational unit + * + * @param communicationInformationToUpdate the communication information to update + * @param idCampaign campaign identifier + * @param idOu organizational unit id + */ + @Operation(summary = "Update the communication information of a campaign for an organizational unit") + @PutMapping(path = Constants.API_CAMPAIGN_ID_OU_ID_COMMUNICATION_INFORMATION) + public void updateCommunicationInformation( + @Valid @NotNull @RequestBody CommunicationInformationUpdateDto communicationInformationToUpdate, + @NotBlank @PathVariable(value = "idCampaign") String idCampaign, + @NotBlank @PathVariable(value = "idOu") String idOu) { + String userId = authenticatedUserService.getCurrentUserId(); + log.info("{} try to change OU[{}] communication information on campaign[{}] ", userId, idOu, idCampaign); + communicationInformationService + .updateCommunicationInformation(CommunicationInformationUpdateDto.toModel( + communicationInformationToUpdate, + idCampaign, + idOu)); + log.info("Communication information with CampaignId {} for Organizational Unit {} updated", idCampaign, + idOu); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java index 7bf4792b..5ed65423 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java @@ -23,6 +23,8 @@ public record CampaignCreateDto ( @Valid List visibilities, @Valid + List communicationInformations, + @Valid @NoDuplicateMediumAndType List communications, List referents, diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java index 31f6b4b1..48ac2c15 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java @@ -25,6 +25,8 @@ public record CampaignUpdateDto( String campaignLabel, @Valid List visibilities, + @Valid + List communicationInformations, List referents, String email, IdentificationConfiguration identificationConfiguration, diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java new file mode 100644 index 00000000..d2561706 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java @@ -0,0 +1,35 @@ +package fr.insee.pearljam.api.campaign.dto.input; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; +import jakarta.validation.constraints.NotBlank; +import org.springframework.lang.NonNull; + +import java.util.ArrayList; +import java.util.List; + +public record CommunicationInformationCampaignCreateDto( + @NotBlank + String organizationalUnit, + String address, + String mail, + String tel) { + public static CommunicationInformation toModel(@NonNull CommunicationInformationCampaignCreateDto communicationInformation, + String campaignId) { + return new CommunicationInformation(campaignId, + communicationInformation.organizationalUnit(), + communicationInformation.address(), + communicationInformation.mail(), + communicationInformation.tel()); + } + + public static List toModel(List communicationInformations, + String campaignId) { + if(communicationInformations == null) { + return new ArrayList<>(); + } + + return communicationInformations.stream() + .map(communicationInformation -> CommunicationInformationCampaignCreateDto.toModel(communicationInformation, campaignId)) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java new file mode 100644 index 00000000..8ea2528c --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java @@ -0,0 +1,36 @@ +package fr.insee.pearljam.api.campaign.dto.input; + +import com.fasterxml.jackson.annotation.JsonProperty; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; +import jakarta.validation.constraints.NotBlank; + +import java.util.List; + +public record CommunicationInformationCampaignUpdateDto( + @NotBlank + String organizationalUnit, + @JsonProperty(required = true) + String address, + @JsonProperty(required = true) + String mail, + @JsonProperty(required = true) + String tel) { + + public static CommunicationInformation toModel(CommunicationInformationCampaignUpdateDto communicationInformation, String campaignId) { + if(communicationInformation == null) { + return null; + } + return new CommunicationInformation( + campaignId, + communicationInformation.organizationalUnit(), + communicationInformation.address(), + communicationInformation.mail(), + communicationInformation.tel()); + } + + public static List toModel(List communicationsInformations, String campaignId) { + return communicationsInformations.stream() + .map(communicationInformations -> toModel(communicationInformations, campaignId)) + .toList(); + } + } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java new file mode 100644 index 00000000..54552a5d --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java @@ -0,0 +1,38 @@ +package fr.insee.pearljam.api.campaign.dto.input; + +import com.fasterxml.jackson.annotation.JsonProperty; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; +import lombok.NonNull; + +import java.util.List; + +public record CommunicationInformationUpdateDto( + @JsonProperty(required = true) + String address, + @JsonProperty(required = true) + String mail, + @JsonProperty(required = true) + String tel) { + + public static CommunicationInformation toModel(CommunicationInformationUpdateDto communicationInformation, + @NonNull String campaignId, + @NonNull String ouId) { + if(communicationInformation == null) { + return null; + } + return new CommunicationInformation( + campaignId, + ouId, + communicationInformation.address(), + communicationInformation.mail(), + communicationInformation.tel()); + } + + public static List toModel(List communicationsInformations, + @NonNull String campaignId, + @NonNull String ouId) { + return communicationsInformations.stream() + .map(communicationInformations -> toModel(communicationInformations, campaignId, ouId)) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java index 4f15a423..bb1f4727 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java @@ -26,16 +26,21 @@ public record CampaignResponseDto( String campaign, String campaignLabel, List visibilities, + List communicationInformations, List referents, String email, IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, ContactAttemptConfiguration contactAttemptConfiguration ) { - public static CampaignResponseDto fromModel(Campaign campaignDB, List referents, List visibilities) { + public static CampaignResponseDto fromModel(Campaign campaignDB, + List referents, + List visibilities, + List communicationInformations) { return new CampaignResponseDto(campaignDB.getId(), campaignDB.getLabel(), visibilities, + communicationInformations, referents, campaignDB.getEmail(), campaignDB.getIdentificationConfiguration(), diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java new file mode 100644 index 00000000..1927b513 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java @@ -0,0 +1,23 @@ +package fr.insee.pearljam.api.campaign.dto.output; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; + +import java.util.List; + +public record CommunicationInformationResponseDto( + String organizationalUnit, + String address, + String mail, + String tel) { + + public static List fromModel(List communications) { + return communications.stream() + .map(communicationInformation -> new CommunicationInformationResponseDto( + communicationInformation.organizationalUnitId(), + communicationInformation.address(), + communicationInformation.mail(), + communicationInformation.tel() + )) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/constants/Constants.java b/src/main/java/fr/insee/pearljam/api/constants/Constants.java index bc8a37ad..3a7ff0d0 100644 --- a/src/main/java/fr/insee/pearljam/api/constants/Constants.java +++ b/src/main/java/fr/insee/pearljam/api/constants/Constants.java @@ -54,8 +54,10 @@ private Constants() { public static final String API_CAMPAIGN_ID_SU_NOT_ATTRIBUTED_CONTACTOUTCOMES = "/api/campaign/{id}/survey-units/not-attributed/contact-outcomes"; public static final String API_CAMPAIGN_ID_SU_INTERVIEWER_CLOSINGCAUSES = "/api/campaign/{id}/survey-units/interviewer/{idep}/closing-causes"; public static final String API_CAMPAIGN_ID_OU_ID_VISIBILITY = "/api/campaign/{idCampaign}/organizational-unit/{idOu}/visibility"; + public static final String API_CAMPAIGN_ID_OU_ID_COMMUNICATION_INFORMATION = "/api/campaign/{idCampaign}/organizational-unit/{idOu}/communication-information"; public static final String API_CAMPAIGN_ID_VISIBILITIES = "/api/campaign/{id}/visibilities"; public static final String API_CAMPAIGN_ID_COMMUNICATION_TEMPLATES = "/api/campaign/{id}/communication-templates"; + public static final String API_CAMPAIGN_ID_COMMUNICATION_INFORMATIONS = "/api/campaign/{id}/communication-informations"; public static final String API_CAMPAIGN_ID_REFERENTS = "/api/campaigns/{id}/referents"; public static final String API_CAMPAIGNS_ID_ON_GOING = "/campaigns/{id}/ongoing"; diff --git a/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java b/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java index 07692f2d..d4ea37cf 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java @@ -119,7 +119,7 @@ public ResponseEntity> getInterviewerCampaigns() { * This method is used to get the list of interviewers associated with the * campaign {id} for current user * - * @param id + * @param id campaign id * @return List of {@link Interviewer} if exist, {@link HttpStatus} NOT_FOUND, * or {@link HttpStatus} FORBIDDEN */ @@ -146,7 +146,7 @@ public ResponseEntity> getListInterviewers(@PathVariable(va * This method is used to count survey units that are abandoned by campaign * Return the sum of survey units states by campaign as a list * - * @param id + * @param id campaign id * @return */ @Operation(summary = "Get numberSUAbandoned") @@ -216,10 +216,10 @@ public void deleteCampaignById( * @param id campaign id * @param campaign campaign to update */ - @Operation(summary = "Update campaign (label, email, configurations, visibilities, referents)") + @Operation(summary = "Update campaign (label, email, configurations, visibilities, communication-informations, referents)") @PutMapping(path = Constants.API_CAMPAIGN_ID) public void updateCampaign(@NotBlank @PathVariable(value = "id") String id, - @Valid @NotNull @RequestBody CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { + @Valid @NotNull @RequestBody CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException, OrganizationalUnitNotFoundException { String userId = authenticatedUserService.getCurrentUserId(); log.info("{} try to update campaign {} collection dates", userId, id); @@ -230,7 +230,7 @@ public void updateCampaign(@NotBlank @PathVariable(value = "id") String id, /** * This method returns campaign ongoing status * - * @param id + * @param id campaign id * @return {@link OngoingDto} , {@link HttpStatus} NOT_FOUND, * or {@link HttpStatus} FORBIDDEN */ diff --git a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java index 8cf5163b..04a1d57c 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java @@ -3,6 +3,7 @@ import java.io.Serializable; import java.util.List; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import jakarta.persistence.CascadeType; @@ -75,6 +76,9 @@ public class Campaign implements Serializable { @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, orphanRemoval = true) private List communicationTemplates; + @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, orphanRemoval = true) + private List communicationInformations; + public Campaign(String id, String label, IdentificationConfiguration identConfig, ContactOutcomeConfiguration contOutConfig, ContactAttemptConfiguration contAttConfig, String email) { super(); diff --git a/src/main/java/fr/insee/pearljam/api/service/CampaignService.java b/src/main/java/fr/insee/pearljam/api/service/CampaignService.java index d450654c..3541d158 100644 --- a/src/main/java/fr/insee/pearljam/api/service/CampaignService.java +++ b/src/main/java/fr/insee/pearljam/api/service/CampaignService.java @@ -58,7 +58,7 @@ public interface CampaignService { void delete(String campaignId, boolean force) throws CampaignNotFoundException, CampaignOnGoingException; - void updateCampaign(String id, CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException; + void updateCampaign(String id, CampaignUpdateDto campaign) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException, OrganizationalUnitNotFoundException; boolean isCampaignOngoing(String id) throws CampaignNotFoundException; diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index 15bdfee9..9e8ad4f6 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -1,7 +1,9 @@ package fr.insee.pearljam.api.service.impl; import fr.insee.pearljam.api.campaign.dto.input.*; +import fr.insee.pearljam.api.campaign.dto.input.CommunicationTemplateCreateDto; import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; +import fr.insee.pearljam.api.campaign.dto.output.CommunicationInformationResponseDto; import fr.insee.pearljam.api.campaign.dto.output.VisibilityCampaignDto; import fr.insee.pearljam.api.domain.Campaign; import fr.insee.pearljam.api.domain.OrganizationUnit; @@ -17,10 +19,13 @@ import fr.insee.pearljam.api.service.*; import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.port.userside.CommunicationInformationService; import fr.insee.pearljam.domain.campaign.port.userside.DateService; import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; import fr.insee.pearljam.domain.exception.*; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import lombok.NonNull; @@ -62,6 +67,7 @@ public class CampaignServiceImpl implements CampaignService { private final ReferentService referentService; private final VisibilityService visibilityService; private final DateService dateService; + private final CommunicationInformationService communicationInformationService; @Override public List getListCampaign(String userId) { @@ -172,6 +178,17 @@ public void createCampaign(CampaignCreateDto campaignDto) visibilitiesDBToCreate.add(VisibilityDB.fromModel(visibility, campaign, organizationUnit)); } campaign.setVisibilities(visibilitiesDBToCreate); + + List communicationInformations = CommunicationInformationCampaignCreateDto.toModel(campaignDto.communicationInformations(), campaignDto.campaign()); + List communicationInformationsDBToCreate = new ArrayList<>(); + for (CommunicationInformation communicationInformation : communicationInformations) { + OrganizationUnit organizationUnit = organizationUnitRepository.findById(communicationInformation.organizationalUnitId()) + .orElseThrow(OrganizationalUnitNotFoundException::new); + communicationInformationsDBToCreate.add(CommunicationInformationDB.fromModel(communicationInformation, campaign, organizationUnit)); + } + campaign.setCommunicationInformations(communicationInformationsDBToCreate); + + if(campaignDto.referents() != null) { updateReferents(campaign, campaignDto.referents()); } @@ -213,7 +230,7 @@ public void delete(String campaignId, boolean force) throws CampaignNotFoundExce } @Override - public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { + public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate) throws CampaignNotFoundException, OrganizationalUnitNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { Campaign currentCampaign = campaignRepository.findByIdIgnoreCase(campaignId) .orElseThrow(CampaignNotFoundException::new); @@ -224,6 +241,13 @@ public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate } } + if(campaignToUpdate.communicationInformations() != null) { + List communicationInformations = CommunicationInformationCampaignUpdateDto.toModel( + campaignToUpdate.communicationInformations(), + campaignId); + communicationInformationService.setCommunicationInformations(communicationInformations, currentCampaign); + } + currentCampaign.setLabel(campaignToUpdate.campaignLabel()); if (!StringUtils.isBlank(campaignToUpdate.email())) { currentCampaign.setEmail(campaignToUpdate.email()); @@ -302,6 +326,9 @@ public CampaignResponseDto getCampaignDtoById(String campaignId) throws Campaign List visibilities = VisibilityCampaignDto.fromModel( visibilityService.findVisibilities(campaignId) ); - return CampaignResponseDto.fromModel(campaignDB, referents, visibilities); + List communicationInformations = CommunicationInformationResponseDto.fromModel( + communicationInformationService.findCommunicationInformations(campaignId) + ); + return CampaignResponseDto.fromModel(campaignDB, referents, visibilities, communicationInformations); } } diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java index 0760524f..d23ded74 100644 --- a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java +++ b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java @@ -135,6 +135,11 @@ public ResponseEntity exceptions(SurveyUnitNotFoundException e, WebReq return generateResponseError(e, HttpStatus.NOT_FOUND, request); } + @ExceptionHandler(CommunicationInformationNotFoundException.class) + public ResponseEntity exceptions(CommunicationInformationNotFoundException e, WebRequest request) { + return generateResponseError(e, HttpStatus.NOT_FOUND, request); + } + @ExceptionHandler(VisibilityHasInvalidDatesException.class) public ResponseEntity exceptions(VisibilityHasInvalidDatesException e, WebRequest request) { return generateResponseError(e, HttpStatus.CONFLICT, request); diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java new file mode 100644 index 00000000..a81db0cd --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java @@ -0,0 +1,10 @@ +package fr.insee.pearljam.domain.campaign.model.communication; + +public record CommunicationInformation( + String campaignId, + String organizationalUnitId, + String address, + String mail, + String tel +) { +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java new file mode 100644 index 00000000..c4825747 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java @@ -0,0 +1,39 @@ +package fr.insee.pearljam.domain.campaign.port.serverside; + +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; + +import java.util.List; +import java.util.Optional; + +public interface CommunicationInformationRepository { + + /** + * + * @param campaignId campaign id + * @param organizationalUnitId organizational unit id + * @return the communication information for a campaign and an organizational unit + */ + Optional findCommunicationInformation(String campaignId, String organizationalUnitId); + + /** + * + * @param campaignId campaign id + * @return the communication informations of a campaign + */ + List findCommunicationInformations(String campaignId); + + /** + * Update a communication information + * @param communicatioInformationToUpdate the communication information to update + */ + void update(CommunicationInformation communicatioInformationToUpdate); + + /** + * set the communication informations to a campaign + * @param communicationInformations list of communication informations to set + * @param campaign campaign + */ + void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException; +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationInformationService.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationInformationService.java new file mode 100644 index 00000000..bbc95957 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationInformationService.java @@ -0,0 +1,35 @@ +package fr.insee.pearljam.domain.campaign.port.userside; + +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; + +import java.util.List; + +public interface CommunicationInformationService { + + /** + * + * @param campaignId campaign id + * @return the visibilities for the campaign + * @throws CampaignNotFoundException if campaign not found + */ + List findCommunicationInformations(String campaignId) throws CampaignNotFoundException; + + + /** + * + * @param communicationInformations List of communication informations to set + * @param campaign campaign where the list should be set + * @throws OrganizationalUnitNotFoundException exception when no ou found + * @throws CampaignNotFoundException exception when no campaign found + */ + void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException, CampaignNotFoundException; + + /** + * update a communication information + * @param communicationInformationToUpdate informationToUpdate communication information to update + */ + void updateCommunicationInformation(CommunicationInformation communicationInformationToUpdate); +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationInformationServiceImpl.java b/src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationInformationServiceImpl.java new file mode 100644 index 00000000..17b14cc0 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationInformationServiceImpl.java @@ -0,0 +1,38 @@ +package fr.insee.pearljam.domain.campaign.service; + +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; +import fr.insee.pearljam.domain.campaign.port.serverside.CommunicationInformationRepository; +import fr.insee.pearljam.domain.campaign.port.userside.CommunicationInformationService; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@RequiredArgsConstructor +@Transactional(rollbackFor = Exception.class) +@Slf4j +public class CommunicationInformationServiceImpl implements CommunicationInformationService { + + private final CommunicationInformationRepository communicationInformationRepository; + + @Override + public List findCommunicationInformations(String campaignId) { + return communicationInformationRepository.findCommunicationInformations(campaignId); + } + + @Override + public void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException, CampaignNotFoundException { + communicationInformationRepository.setCommunicationInformations(communicationInformations, campaign); + } + + @Override + public void updateCommunicationInformation(CommunicationInformation communicationInformationToUpdate) { + communicationInformationRepository.update(communicationInformationToUpdate); + } +} diff --git a/src/main/java/fr/insee/pearljam/domain/exception/CommunicationInformationNotFoundException.java b/src/main/java/fr/insee/pearljam/domain/exception/CommunicationInformationNotFoundException.java new file mode 100644 index 00000000..ac4d1eae --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/exception/CommunicationInformationNotFoundException.java @@ -0,0 +1,10 @@ +package fr.insee.pearljam.domain.exception; + +public class CommunicationInformationNotFoundException extends RuntimeException { + + public static final String MESSAGE = "Communication Information not found"; + + public CommunicationInformationNotFoundException() { + super(MESSAGE); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java new file mode 100644 index 00000000..401cf5d5 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java @@ -0,0 +1,78 @@ +package fr.insee.pearljam.infrastructure.campaign.adapter; + +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.api.domain.OrganizationUnit; +import fr.insee.pearljam.api.repository.CampaignRepository; +import fr.insee.pearljam.api.repository.OrganizationUnitRepository; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; +import fr.insee.pearljam.domain.campaign.port.serverside.CommunicationInformationRepository; +import fr.insee.pearljam.domain.exception.CommunicationInformationNotFoundException; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; +import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationInformationJpaRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; + + import java.util.List; +import java.util.Optional; + +@RequiredArgsConstructor +@Repository +public class CommunicationInformationDaoAdapter implements CommunicationInformationRepository { + private final CommunicationInformationJpaRepository crudRepository; + private final OrganizationUnitRepository organizationUnitRepository; + private final CampaignRepository campaignRepository; + + @Override + public Optional findCommunicationInformation(String campaignId, String organizationalUnitId) { + return crudRepository + .findCommunicationInformation(campaignId, organizationalUnitId) + .map(CommunicationInformationDB::toModel); + } + + @Override + public List findCommunicationInformations(String campaignId) { + return CommunicationInformationDB.toModel( + crudRepository.findByCampaignId(campaignId) + ); + } + + @Override + public void update(CommunicationInformation communicationInformationToUpdate) { + CommunicationInformationDB currentCommunicationInformationDB = crudRepository.findCommunicationInformation( + communicationInformationToUpdate.campaignId(), communicationInformationToUpdate.organizationalUnitId()) + .orElseThrow(CommunicationInformationNotFoundException::new); + currentCommunicationInformationDB.setMail(communicationInformationToUpdate.mail()); + currentCommunicationInformationDB.setTel(communicationInformationToUpdate.tel()); + currentCommunicationInformationDB.setAddress(communicationInformationToUpdate.address()); + crudRepository.save(currentCommunicationInformationDB); + } + + @Override + public void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException { + List currentCommunicationInformations = campaign.getCommunicationInformations(); + currentCommunicationInformations.clear(); + for(CommunicationInformation communicationInformationToUpdate : communicationInformations) { + OrganizationUnit organizationUnit = organizationUnitRepository + .findById(communicationInformationToUpdate.organizationalUnitId()) + .orElseThrow(OrganizationalUnitNotFoundException::new); + + CommunicationInformationDB communicationConfigurationDB = + crudRepository + .findCommunicationInformation( + communicationInformationToUpdate.campaignId(), + communicationInformationToUpdate.organizationalUnitId() + ) + .map(communicationInformationDB -> { + communicationInformationDB.setMail(communicationInformationToUpdate.mail()); + communicationInformationDB.setTel(communicationInformationToUpdate.tel()); + communicationInformationDB.setAddress(communicationInformationToUpdate.address()); + return communicationInformationDB; + }) + .orElse(CommunicationInformationDB.fromModel(communicationInformationToUpdate, campaign, organizationUnit)); + + currentCommunicationInformations.add(communicationConfigurationDB); + } + campaignRepository.save(campaign); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java new file mode 100644 index 00000000..1e413c74 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java @@ -0,0 +1,67 @@ +package fr.insee.pearljam.infrastructure.campaign.entity; + +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.api.domain.OrganizationUnit; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + +import java.io.Serial; +import java.io.Serializable; +import java.util.List; + +@Entity +@Table(name = "communication_information") +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@Slf4j +public class CommunicationInformationDB implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @EmbeddedId + private CommunicationInformationDBId communicationInformationId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "organization_unit_id", insertable = false, updatable = false) + private OrganizationUnit organizationUnit; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "campaign_id", insertable = false, updatable = false) + private Campaign campaign; + + private String mail; + private String address; + private String tel; + + public static CommunicationInformationDB fromModel(CommunicationInformation communicationInformation, Campaign campaign, OrganizationUnit organizationUnit) { + CommunicationInformationDBId id = new CommunicationInformationDBId(organizationUnit.getId(), campaign.getId()); + return new CommunicationInformationDB(id, + organizationUnit, campaign, + communicationInformation.mail(), + communicationInformation.address(), + communicationInformation.tel()); + } + + public static CommunicationInformation toModel(CommunicationInformationDB communicationInformationDB) { + return new CommunicationInformation( + communicationInformationDB.getCommunicationInformationId().getCampaignId(), + communicationInformationDB.getCommunicationInformationId().getOrganizationUnitId(), + communicationInformationDB.getAddress(), + communicationInformationDB.getMail(), + communicationInformationDB.getTel()); + } + + public static List toModel(List communicationInformationDBS) { + return communicationInformationDBS.stream() + .map(CommunicationInformationDB::toModel) + .toList(); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDBId.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDBId.java new file mode 100644 index 00000000..08ba5672 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDBId.java @@ -0,0 +1,41 @@ +package fr.insee.pearljam.infrastructure.campaign.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.io.Serial; +import java.io.Serializable; + +/** + * This class is used to defines the association between OrganizationUnit and + * Campaign tables. + * + * @author scorcaud + */ +@Embeddable +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class CommunicationInformationDBId implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + /** + * The organizationUnit Id + */ + @Column(name = "organization_unit_id") + private String organizationUnitId; + + /** + * The campaign Id + */ + @Column(name = "campaign_id") + private String campaignId; + +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java new file mode 100644 index 00000000..03871190 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java @@ -0,0 +1,20 @@ +package fr.insee.pearljam.infrastructure.campaign.jpa; + +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDBId; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; +import java.util.Optional; + +public interface CommunicationInformationJpaRepository extends JpaRepository { + + @Query(value = """ + SELECT * FROM communication_information + WHERE campaign_id=?1 + AND organization_unit_id=?2""", nativeQuery = true) + Optional findCommunicationInformation(String campaignId, String organizationalUnitId); + + List findByCampaignId(String campaignId); +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java b/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java index 01c845be..47ca6acf 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java @@ -174,10 +174,14 @@ private void authorizeRequests(HttpSecurity http) throws Exception { .hasAnyRole(adminRole, localUserRole, nationalUserRole) .requestMatchers(HttpMethod.PUT, Constants.API_CAMPAIGN_ID_OU_ID_VISIBILITY) .hasAnyRole(adminRole, localUserRole, nationalUserRole) + .requestMatchers(HttpMethod.PUT, Constants.API_CAMPAIGN_ID_OU_ID_COMMUNICATION_INFORMATION) + .hasRole(adminRole) .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGN_ID_VISIBILITIES) .hasRole(adminRole) .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGN_ID_COMMUNICATION_TEMPLATES) .hasRole(adminRole) + .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGN_ID_COMMUNICATION_INFORMATIONS) + .hasRole(adminRole) .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGN_ID_REFERENTS) .hasAnyRole(adminRole, localUserRole, nationalUserRole) .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGNS_ID_ON_GOING) diff --git a/src/main/resources/db/changelog/543_create_communication_information.xml b/src/main/resources/db/changelog/543_create_communication_information.xml new file mode 100644 index 00000000..8f582139 --- /dev/null +++ b/src/main/resources/db/changelog/543_create_communication_information.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/db/dataset/init-demo-data.sql b/src/main/resources/db/dataset/init-demo-data.sql index a9436d85..0925591f 100644 --- a/src/main/resources/db/dataset/init-demo-data.sql +++ b/src/main/resources/db/dataset/init-demo-data.sql @@ -142,6 +142,17 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000); +INSERT INTO communication_information ( + organization_unit_id, + campaign_id, + address, + mail, + tel +) VALUES + ('OU-NORTH', 'SIMPSONS2020X00','50 beverly hills street, north region', 'north-simpsons@nooneknows.fr', '0321234567'), + ('OU-SOUTH', 'SIMPSONS2020X00','60 rue des clopinettes, south region', 'south-simpsons@nooneknows.fr', NULL), + ('OU-NORTH', 'VQS2021X00', NULL, 'north-vqs@nooneknows.fr', ''); + INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', TRUE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '13', FALSE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Claude Watkins' AND s.bs='13'; diff --git a/src/main/resources/db/dataset/reinit-test-data.sql b/src/main/resources/db/dataset/reinit-test-data.sql index 8150428e..d35dce62 100644 --- a/src/main/resources/db/dataset/reinit-test-data.sql +++ b/src/main/resources/db/dataset/reinit-test-data.sql @@ -26,6 +26,7 @@ TRUNCATE TABLE public.comment; TRUNCATE TABLE public.closing_cause; TRUNCATE TABLE public.organization_unit; TRUNCATE TABLE public.address; +TRUNCATE TABLE public.communication_information; ALTER TABLE public.communication_request_status ALTER COLUMN id RESTART WITH 1; ALTER TABLE public.communication_request ALTER COLUMN id RESTART WITH 1; @@ -120,6 +121,16 @@ INSERT INTO visibility ( ('OU-SOUTH', 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308), ('OU-WEST' , 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308); +INSERT INTO communication_information ( + organization_unit_id, + campaign_id, + address, + mail, + tel +) VALUES + ('OU-NORTH', 'SIMPSONS2020X00','50 beverly hills street, north region', 'north-simpsons@nooneknows.fr', '0321234567'), + ('OU-SOUTH', 'VQS2021X00', NULL, 'north-vqs@nooneknows.fr', ''); + INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; diff --git a/src/main/resources/db/master.xml b/src/main/resources/db/master.xml index 0bd757fd..0665c907 100644 --- a/src/main/resources/db/master.xml +++ b/src/main/resources/db/master.xml @@ -48,7 +48,10 @@ - + + + + \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java index c696a4fc..20c1304a 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java @@ -1,8 +1,6 @@ package fr.insee.pearljam.api.campaign.controller; -import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; -import fr.insee.pearljam.api.campaign.dto.input.CommunicationTemplateCreateDto; -import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignCreateDto; +import fr.insee.pearljam.api.campaign.dto.input.*; import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.controller.CampaignController; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; @@ -103,12 +101,14 @@ void testCreateCampaign04() throws Exception { ContactAttemptConfiguration.F2F, List.of(visibility), List.of(), + List.of(), List.of()); CampaignCreateDto campaign2 = generateCampaign("campId", " ", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(visibility), List.of(), + List.of(), List.of()); List campaigns = List.of(campaign1, campaign2); for(CampaignCreateDto campaign : campaigns) { @@ -154,6 +154,7 @@ void testCreateCampaign05() throws Exception { ContactAttemptConfiguration.F2F, invalidCampaignVisibilities, List.of(), + List.of(), List.of()); mockMvc.perform(post(Constants.API_CAMPAIGN) .contentType(MediaType.APPLICATION_JSON) @@ -185,11 +186,13 @@ void testCreateCampaign07() throws Exception { 1721683253000L, 1721683254000L, 1721683255000L); CommunicationTemplateCreateDto communicationTemplate = new CommunicationTemplateCreateDto("messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); CommunicationTemplateCreateDto duplicatedCommunicationTemplate = new CommunicationTemplateCreateDto("messhId2", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CampaignCreateDto campaign = generateCampaign("campId", "label", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(visibility), List.of(), + List.of(), List.of(communicationTemplate, duplicatedCommunicationTemplate)); mockMvc.perform(post(Constants.API_CAMPAIGN) @@ -217,12 +220,17 @@ public CampaignCreateDto generateDefaultCampaign() { 1721683263000L, 1721683264000L, 1721683265000L); + CommunicationInformationCampaignCreateDto communicationInformation = new CommunicationInformationCampaignCreateDto("OU-SOUTH", + "address", + "mail", + "tel"); ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); ReferentDto secondReferent = new ReferentDto("Dupont", "Jean", "1234567890", "PRIMARY"); return generateCampaign("campId", "An other campaign", "test.test@sdf.com", IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL, List.of(firstVisibility, secondVisibility), + List.of(communicationInformation), List.of(firstReferent, secondReferent), List.of(communicationTemplate1, communicationTemplate2)); } @@ -233,12 +241,14 @@ private CampaignCreateDto generateCampaign( ContactOutcomeConfiguration contactOutcomeConfiguration, ContactAttemptConfiguration contactAttemptConfiguration, List visibilities, + List communicationInformations, List referents, List communicationTemplates) { return new CampaignCreateDto(campaignId, campaignLabel, visibilities, + communicationInformations, communicationTemplates, referents, email, diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java index 983d1d75..98f67b30 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java @@ -52,7 +52,7 @@ void setup() { @Test @DisplayName("Should retrieve campaign") void testGetCampaign01() throws Exception { - CampaignResponseDto campaign = new CampaignResponseDto("campaign-id", "label", null, null, "email", + CampaignResponseDto campaign = new CampaignResponseDto("campaign-id", "label", null, null, null, "email", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.F2F); campaignService.setCampaignToRetrieve(campaign); diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java index b225b50b..7d444833 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java @@ -1,6 +1,7 @@ package fr.insee.pearljam.api.campaign.controller; import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; +import fr.insee.pearljam.api.campaign.dto.input.CommunicationInformationCampaignUpdateDto; import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignUpdateDto; import fr.insee.pearljam.api.controller.CampaignController; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; @@ -71,6 +72,7 @@ void testUpdateCampaign02() throws Exception { "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(), + List.of(), List.of()); mockMvc.perform(put(updatePath) .contentType(MediaType.APPLICATION_JSON) @@ -133,6 +135,7 @@ private void testUpdateExceptions(VisibilityCampaignUpdateDto visibility, HttpSt "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(visibility), + List.of(), List.of()); mockMvc.perform(put(updatePath) .contentType(MediaType.APPLICATION_JSON) @@ -153,24 +156,36 @@ private CampaignUpdateDto generateDefaultCampaign() { 1721683263000L, 1721683264000L, 1721683265000L); + + CommunicationInformationCampaignUpdateDto firstCommunication = generateCommunicationInformation("OU-SOUTH", + "address", + "mail", + "tel"); ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); ReferentDto secondReferent = new ReferentDto("Dupont", "Jean", "1234567890", "PRIMARY"); return generateCampaign("An other campaign", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(firstVisibility, secondVisibility), + List.of(firstCommunication), List.of(firstReferent, secondReferent)); } + private CommunicationInformationCampaignUpdateDto generateCommunicationInformation(String ouId, String address, String mail, String tel) { + return new CommunicationInformationCampaignUpdateDto(ouId, address, mail, tel); + } + private CampaignUpdateDto generateCampaign(String campaignLabel, String email, IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, ContactAttemptConfiguration contactAttemptConfiguration, List visibilities, + List communicationInformations, List referents) { return new CampaignUpdateDto( campaignLabel, visibilities, + communicationInformations, referents, email, identificationConfiguration, diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java index d85a260a..cb2cf90b 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java @@ -3,6 +3,7 @@ import fr.insee.pearljam.api.campaign.controller.dummy.ReferentFakeService; import fr.insee.pearljam.api.campaign.controller.dummy.VisibilityFakeService; import fr.insee.pearljam.api.campaign.dto.input.*; +import fr.insee.pearljam.api.campaign.dto.input.CommunicationTemplateCreateDto; import fr.insee.pearljam.api.domain.*; import fr.insee.pearljam.api.service.impl.CampaignServiceImpl; import fr.insee.pearljam.api.surveyunit.controller.dummy.SurveyUnitFakeService; @@ -79,13 +80,15 @@ void setup() { SurveyUnitFakeService surveyUnitService = new SurveyUnitFakeService(); PreferenceFakeService preferenceService = new PreferenceFakeService(); ReferentFakeService referentService = new ReferentFakeService(); + CommunicationInformationFakeService communicationInformationService = new CommunicationInformationFakeService(); campaignService = new CampaignServiceImpl( campaignRepository, userRepository, surveyUnitRepository, organizationUnitRepository, messageRepository, - userService, utilsService, surveyUnitService, preferenceService, referentService, visibilityService, dateService); + userService, utilsService, surveyUnitService, preferenceService, referentService, visibilityService, dateService, + communicationInformationService); } - // TODO : handle referent + // TODO : handle referent & communication informations @Test @DisplayName("Should create a new campaign successfully") void shouldCreateNewCampaign() throws CampaignAlreadyExistException, OrganizationalUnitNotFoundException, VisibilityHasInvalidDatesException { @@ -98,6 +101,7 @@ void shouldCreateNewCampaign() throws CampaignAlreadyExistException, Organizatio campaignId, "Campaign 1", List.of(visibilityDto), + null, List.of(communicationTemplateDto), null, null, @@ -139,6 +143,7 @@ void shouldThrowCampaignAlreadyExistExceptionWhenCreatingExistingCampaign() { null, null, null, + null, IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F @@ -149,10 +154,10 @@ void shouldThrowCampaignAlreadyExistExceptionWhenCreatingExistingCampaign() { .hasMessage(CampaignAlreadyExistException.MESSAGE); } - // TODO : handle referents + // TODO : handle referents & communication infos @Test @DisplayName("Should update an existing campaign successfully") - void shouldUpdateExistingCampaign() throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { + void shouldUpdateExistingCampaign() throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException, OrganizationalUnitNotFoundException { String campaignId = existingCampaign.getId(); // Given @@ -161,6 +166,7 @@ void shouldUpdateExistingCampaign() throws CampaignNotFoundException, Visibility CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", List.of(visibilityDto), + List.of(), null, "emailUpdated@email.com", IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, @@ -189,12 +195,13 @@ void shouldUpdateExistingCampaign() throws CampaignNotFoundException, Visibility @ValueSource(strings = {"", " "}) @NullSource @DisplayName("Should not update email if empty") - void shouldNotUpdateEmailIfNull(String emailToUpdate) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { + void shouldNotUpdateEmailIfNull(String emailToUpdate) throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException, OrganizationalUnitNotFoundException { String campaignId = existingCampaign.getId(); // Given CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", + null, null, null, emailToUpdate, IdentificationConfiguration.NOIDENT, @@ -211,14 +218,16 @@ void shouldNotUpdateEmailIfNull(String emailToUpdate) throws CampaignNotFoundExc @Test @DisplayName("Should not update visibilities if null") - void shouldNotUpdateVisibilitiesIfNull() throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException { + void shouldNotUpdateVisibilitiesIfNull() throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException, OrganizationalUnitNotFoundException { String campaignId = existingCampaign.getId(); // Given CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", null, - null, null, + null, + null, + null, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -233,13 +242,15 @@ void shouldNotUpdateVisibilitiesIfNull() throws CampaignNotFoundException, Visib @Test @DisplayName("Should not update referents if null") - void shouldNotUpdateReferentsIfNull() throws VisibilityHasInvalidDatesException, CampaignNotFoundException, VisibilityNotFoundException { + void shouldNotUpdateReferentsIfNull() throws VisibilityHasInvalidDatesException, CampaignNotFoundException, VisibilityNotFoundException, OrganizationalUnitNotFoundException { String campaignId = existingCampaign.getId(); // Given CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", null, - null, null, + null, + null, + null, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -259,7 +270,9 @@ void shouldThrowCampaignNotFoundExceptionWhenUpdatingNonExistentCampaign() { CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", null, - null, null, + null, + null, + null, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java new file mode 100644 index 00000000..96a87b60 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java @@ -0,0 +1,27 @@ +package fr.insee.pearljam.domain.campaign.service.dummy; + +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; +import fr.insee.pearljam.domain.campaign.port.userside.CommunicationInformationService; +import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.CommunicationInformationNotFoundException; +import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; + +import java.util.List; + +public class CommunicationInformationFakeService implements CommunicationInformationService { + @Override + public List findCommunicationInformations(String campaignId) throws CampaignNotFoundException { + return List.of(); + } + + @Override + public void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException, CampaignNotFoundException { + + } + + @Override + public void updateCommunicationInformation(CommunicationInformation communicationInformationToUpdate) throws CommunicationInformationNotFoundException { + + } +} diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index b4f6d792..af0c129d 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -7,9 +7,9 @@ import fr.insee.pearljam.api.utils.ScriptConstants; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; -import org.json.JSONException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; @@ -25,7 +25,6 @@ import org.springframework.test.web.servlet.MvcResult; import org.springframework.transaction.annotation.Transactional; -import java.text.ParseException; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @@ -47,13 +46,6 @@ class CampaignIT { @Autowired private CampaignRepository campaignRepository; - /** - * Test that the GET endpoint "api/campaigns" - * - * @throws InterruptedException - * @throws JSONException - * @throws ParseException - */ @Test @DisplayName("Should retrieve campaign") void testGetCampaign() throws Exception { @@ -88,6 +80,14 @@ void testGetCampaign() throws Exception { "endDate":1724582154316 } ], + "communicationInformations":[ + { + "organizationalUnit":"OU-NORTH", + "address":"50 beverly hills street, north region", + "mail":"north-simpsons@nooneknows.fr", + "tel":"0321234567" + } + ], "referents":[ { "firstName":"Gerard", @@ -148,6 +148,19 @@ void testCreateCampaign() throws Exception { "role":"PRIMARY" } ], + "communicationInformations": [ + { + "organizationalUnit": "OU-NORTH", + "address": "addr1", + "mail": "mail1", + "tel": "tel1" + }, + { + "organizationalUnit":"OU-SOUTH", + "address": "addr2", + "mail": "mail2" + } + ], "communications": [ { "meshuggahId": "meshId1", @@ -189,9 +202,9 @@ void testCreateCampaign() throws Exception { .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, 1721683254000L, 1721683255000L)) - .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", - 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L)); + .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-SOUTH", + 1721683260000L, 1721683261000L, 1721683262000L, + 1721683263000L, 1721683264000L, 1721683265000L)); assertThat(campaignCreated.getCommunicationTemplates()).hasSize(3); assertThat(campaignCreated.getCommunicationTemplates()) @@ -201,6 +214,22 @@ void testCreateCampaign() throws Exception { CommunicationMedium.EMAIL, CommunicationType.NOTICE)) .anySatisfy(communicationTemplateToCheck -> assertCommunicationTemplate(communicationTemplateToCheck, campaignId, "meshId3", CommunicationMedium.LETTER, CommunicationType.NOTICE)); + + assertThat(campaignCreated.getCommunicationInformations()).hasSize(2); + assertThat(campaignCreated.getCommunicationInformations()) + .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, + campaignId, + "OU-NORTH", + "addr1", + "mail1", + "tel1")) + .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, + campaignId, + "OU-SOUTH", + "addr2", + "mail2", + null)); + assertThat(campaignCreated.getReferents()).hasSize(2); assertThat(campaignCreated.getReferents()) @@ -218,6 +247,19 @@ private void assertCommunicationTemplate(CommunicationTemplateDB communicationTe assertThat(communicationTemplateToCheck.getMedium()).isEqualTo(medium); } + private void assertCommunicationInformation(CommunicationInformationDB communicationInformationToCheck, + String campaignId, + String organizationalUnitId, + String address, + String mail, + String tel) { + assertThat(communicationInformationToCheck.getCampaign().getId()).isEqualTo(campaignId); + assertThat(communicationInformationToCheck.getOrganizationUnit().getId()).isEqualTo(organizationalUnitId); + assertThat(communicationInformationToCheck.getTel()).isEqualTo(tel); + assertThat(communicationInformationToCheck.getAddress()).isEqualTo(address); + assertThat(communicationInformationToCheck.getMail()).isEqualTo(mail); + } + @Test @DisplayName("Should update campaign") @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) @@ -247,6 +289,20 @@ void testUpdateCampaign() throws Exception { "organizationalUnit":"OU-SOUTH" } ], + "communicationInformations": [ + { + "organizationalUnit": "OU-NORTH", + "address": "addr1", + "mail": "mail1", + "tel": "tel1" + }, + { + "organizationalUnit": "OU-SOUTH", + "address": "addr2", + "mail": "mail2", + "tel": "tel2" + } + ], "referents":[ { "firstName":"Bob", @@ -286,10 +342,24 @@ void testUpdateCampaign() throws Exception { 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, 1721683254000L, 1721683255000L)) - .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", - 1721683250000L, 1721683251000L, - 1721683252000L, 1721683253000L, - 1721683254000L, 1721683255000L)); + .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-SOUTH", + 1721683260000L, 1721683261000L, + 1721683262000L, 1721683263000L, + 1721683264000L, 1721683265000L)); + assertThat(campaignUpdated.getCommunicationInformations()).hasSize(2); + assertThat(campaignUpdated.getCommunicationInformations()) + .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, + campaignId, + "OU-NORTH", + "addr1", + "mail1", + "tel1")) + .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, + campaignId, + "OU-SOUTH", + "addr2", + "mail2", + "tel2")); assertThat(campaignUpdated.getReferents()).hasSize(2); assertThat(campaignUpdated.getReferents()) diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java new file mode 100644 index 00000000..f56eb997 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java @@ -0,0 +1,92 @@ +package fr.insee.pearljam.integration.campaign; + +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.ScriptConstants; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDBId; +import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationInformationJpaRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.transaction.annotation.Transactional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ActiveProfiles("auth") +@AutoConfigureMockMvc +@ContextConfiguration +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Transactional +class CommunicationInformationIT { + @Autowired + private MockMvc mockMvc; + + @Autowired + private CommunicationInformationJpaRepository communicationInformationRepository; + + @Test + void testGetCommunicationInformations() throws Exception { + MvcResult mvcResult = mockMvc.perform( + get("/api/campaign/SIMPSONS2020X00/communication-informations") + .with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andReturn(); + + String resultContent = mvcResult.getResponse().getContentAsString(); + String expectedResult = """ + [ + { + "organizationalUnit": "OU-NORTH", + "address": "50 beverly hills street, north region", + "mail": "north-simpsons@nooneknows.fr", + "tel": "0321234567" + } + ]"""; + JSONAssert.assertEquals(resultContent, expectedResult, JSONCompareMode.NON_EXTENSIBLE); + } + + @Test + @DisplayName("Should update communication information") + @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) + void testUpdateCommunicationInformation() throws Exception { + String organizationalUnitId = "OU-NORTH"; + String campaignId = "SIMPSONS2020X00"; + String updatePath = String.format("/api/campaign/%s/organizational-unit/%s/communication-information", campaignId, organizationalUnitId); + String content = """ + { + "address": "newAddr", + "mail": "newMail", + "tel": "newTel" + }"""; + + mockMvc.perform(put(updatePath) + .with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)) + .content(content) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + CommunicationInformationDB communicationDBToCheck = communicationInformationRepository.getReferenceById(new CommunicationInformationDBId(organizationalUnitId, campaignId)); + + assertThat(communicationDBToCheck.getCampaign().getId()).isEqualTo(campaignId); + assertThat(communicationDBToCheck.getOrganizationUnit().getId()).isEqualTo(organizationalUnitId); + assertThat(communicationDBToCheck.getAddress()).isEqualTo("newAddr"); + assertThat(communicationDBToCheck.getMail()).isEqualTo("newMail"); + assertThat(communicationDBToCheck.getTel()).isEqualTo("newTel"); + } +} From eacbaba8ee9321102a8505765f52bb0a055b459c Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 17 Sep 2024 12:42:46 +0200 Subject: [PATCH 31/48] fix: sonar issues --- .../service/dummy/CommunicationInformationFakeService.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java index 96a87b60..2fb75d12 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java @@ -4,7 +4,6 @@ import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; import fr.insee.pearljam.domain.campaign.port.userside.CommunicationInformationService; import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.exception.CommunicationInformationNotFoundException; import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; import java.util.List; @@ -17,11 +16,11 @@ public List findCommunicationInformations(String campa @Override public void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException, CampaignNotFoundException { - + // not used at this moment } @Override - public void updateCommunicationInformation(CommunicationInformation communicationInformationToUpdate) throws CommunicationInformationNotFoundException { - + public void updateCommunicationInformation(CommunicationInformation communicationInformationToUpdate) { + // not used at this moment } } From a5f2677629356ba701aa67d70b03b1dfea64439b Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 17 Sep 2024 14:20:55 +0200 Subject: [PATCH 32/48] fix: delete useless methods --- .../CommunicationInformationUpdateDto.java | 10 ------- .../CommunicationInformationRepository.java | 13 ++------- .../CommunicationInformationDaoAdapter.java | 27 +++---------------- 3 files changed, 6 insertions(+), 44 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java index 54552a5d..6ccfbfa5 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java @@ -4,8 +4,6 @@ import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; import lombok.NonNull; -import java.util.List; - public record CommunicationInformationUpdateDto( @JsonProperty(required = true) String address, @@ -27,12 +25,4 @@ public static CommunicationInformation toModel(CommunicationInformationUpdateDto communicationInformation.mail(), communicationInformation.tel()); } - - public static List toModel(List communicationsInformations, - @NonNull String campaignId, - @NonNull String ouId) { - return communicationsInformations.stream() - .map(communicationInformations -> toModel(communicationInformations, campaignId, ouId)) - .toList(); - } } diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java index c4825747..5bc652e9 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java @@ -5,18 +5,9 @@ import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; import java.util.List; -import java.util.Optional; public interface CommunicationInformationRepository { - /** - * - * @param campaignId campaign id - * @param organizationalUnitId organizational unit id - * @return the communication information for a campaign and an organizational unit - */ - Optional findCommunicationInformation(String campaignId, String organizationalUnitId); - /** * * @param campaignId campaign id @@ -26,9 +17,9 @@ public interface CommunicationInformationRepository { /** * Update a communication information - * @param communicatioInformationToUpdate the communication information to update + * @param communicationInformationToUpdate the communication information to update */ - void update(CommunicationInformation communicatioInformationToUpdate); + void update(CommunicationInformation communicationInformationToUpdate); /** * set the communication informations to a campaign diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java index 401cf5d5..382a81bb 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java @@ -12,24 +12,18 @@ import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationInformationJpaRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; - import java.util.List; -import java.util.Optional; +import java.util.List; @RequiredArgsConstructor @Repository +@Transactional public class CommunicationInformationDaoAdapter implements CommunicationInformationRepository { private final CommunicationInformationJpaRepository crudRepository; private final OrganizationUnitRepository organizationUnitRepository; private final CampaignRepository campaignRepository; - @Override - public Optional findCommunicationInformation(String campaignId, String organizationalUnitId) { - return crudRepository - .findCommunicationInformation(campaignId, organizationalUnitId) - .map(CommunicationInformationDB::toModel); - } - @Override public List findCommunicationInformations(String campaignId) { return CommunicationInformationDB.toModel( @@ -57,20 +51,7 @@ public void setCommunicationInformations(List communic .findById(communicationInformationToUpdate.organizationalUnitId()) .orElseThrow(OrganizationalUnitNotFoundException::new); - CommunicationInformationDB communicationConfigurationDB = - crudRepository - .findCommunicationInformation( - communicationInformationToUpdate.campaignId(), - communicationInformationToUpdate.organizationalUnitId() - ) - .map(communicationInformationDB -> { - communicationInformationDB.setMail(communicationInformationToUpdate.mail()); - communicationInformationDB.setTel(communicationInformationToUpdate.tel()); - communicationInformationDB.setAddress(communicationInformationToUpdate.address()); - return communicationInformationDB; - }) - .orElse(CommunicationInformationDB.fromModel(communicationInformationToUpdate, campaign, organizationUnit)); - + CommunicationInformationDB communicationConfigurationDB = CommunicationInformationDB.fromModel(communicationInformationToUpdate, campaign, organizationUnit); currentCommunicationInformations.add(communicationConfigurationDB); } campaignRepository.save(campaign); From 8f5075dde24f6ced51ad2965a45a7967f9795aae Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 17 Sep 2024 14:21:24 +0200 Subject: [PATCH 33/48] test: add communication info not found test --- ...ommunicationInformationControllerTest.java | 51 +++++++++++++++++++ .../CommunicationInformationFakeService.java | 9 +++- 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java new file mode 100644 index 00000000..c2a0b330 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java @@ -0,0 +1,51 @@ +package fr.insee.pearljam.api.campaign.controller; + +import fr.insee.pearljam.api.campaign.dto.input.CommunicationInformationUpdateDto; +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.JsonTestHelper; +import fr.insee.pearljam.api.utils.MockMvcTestUtils; +import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; +import fr.insee.pearljam.domain.campaign.service.dummy.CommunicationInformationFakeService; +import fr.insee.pearljam.domain.exception.CommunicationInformationNotFoundException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; + +class CommunicationInformationControllerTest { + + private MockMvc mockMvc; + private CommunicationInformationFakeService communicationInformationService; + private final String campaignId = "campaign-id"; + private final String organizationalUnitId = "ou-id"; + private final String updatePath = String.format("/api/campaign/%s/organizational-unit/%s/communication-information", campaignId, organizationalUnitId); + + @BeforeEach + void setup() { + communicationInformationService = new CommunicationInformationFakeService(); + AuthenticationUserFakeService authenticatedUserService = new AuthenticationUserFakeService(AuthenticatedUserTestHelper.AUTH_ADMIN); + CommunicationInformationController communicationInformationController = + new CommunicationInformationController(communicationInformationService, authenticatedUserService); + mockMvc = MockMvcBuilders + .standaloneSetup(communicationInformationController) + .setControllerAdvice(MockMvcTestUtils.createExceptionControllerAdvice()) + .build(); + } + + @Test + @DisplayName("Should return not found when communication information does not exist") + void testUpdateCommunicationInformation01() throws Exception { + communicationInformationService.setShouldThrowCommunicationInformationNotFoundException(true); + CommunicationInformationUpdateDto communicationInformationToUpdate = + new CommunicationInformationUpdateDto("addr", "mail", "0123456789"); + mockMvc.perform(put(updatePath) + .content(JsonTestHelper.toJson(communicationInformationToUpdate)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updatePath, CommunicationInformationNotFoundException.MESSAGE)); + } +} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java index 2fb75d12..df8bd3f7 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java @@ -4,11 +4,16 @@ import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; import fr.insee.pearljam.domain.campaign.port.userside.CommunicationInformationService; import fr.insee.pearljam.domain.exception.CampaignNotFoundException; +import fr.insee.pearljam.domain.exception.CommunicationInformationNotFoundException; import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; +import lombok.Setter; import java.util.List; public class CommunicationInformationFakeService implements CommunicationInformationService { + @Setter + private boolean shouldThrowCommunicationInformationNotFoundException = false; + @Override public List findCommunicationInformations(String campaignId) throws CampaignNotFoundException { return List.of(); @@ -21,6 +26,8 @@ public void setCommunicationInformations(List communic @Override public void updateCommunicationInformation(CommunicationInformation communicationInformationToUpdate) { - // not used at this moment + if(shouldThrowCommunicationInformationNotFoundException) { + throw new CommunicationInformationNotFoundException(); + } } } From 86d253c11b459352a9418b0b215bc9ebdef81439 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 17 Sep 2024 14:22:06 +0200 Subject: [PATCH 34/48] fix: adapt jpa request --- .../campaign/jpa/CommunicationInformationJpaRepository.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java index 03871190..f9747751 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java @@ -11,9 +11,9 @@ public interface CommunicationInformationJpaRepository extends JpaRepository { @Query(value = """ - SELECT * FROM communication_information - WHERE campaign_id=?1 - AND organization_unit_id=?2""", nativeQuery = true) + SELECT ci FROM CommunicationInformationDB ci + WHERE ci.campaign.id=?1 + AND ci.organizationUnit.id=?2""") Optional findCommunicationInformation(String campaignId, String organizationalUnitId); List findByCampaignId(String campaignId); From 6442955f3b0e94e012b33d61ac3185129842943f Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 18 Sep 2024 10:15:59 +0200 Subject: [PATCH 35/48] fix: use spring data query instead of jpa query for CommunicationInformationDB --- .../adapter/CommunicationInformationDaoAdapter.java | 2 +- .../jpa/CommunicationInformationJpaRepository.java | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java index 382a81bb..f2004d08 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java @@ -33,7 +33,7 @@ public List findCommunicationInformations(String campa @Override public void update(CommunicationInformation communicationInformationToUpdate) { - CommunicationInformationDB currentCommunicationInformationDB = crudRepository.findCommunicationInformation( + CommunicationInformationDB currentCommunicationInformationDB = crudRepository.findByCampaignIdAndOrganizationUnitId( communicationInformationToUpdate.campaignId(), communicationInformationToUpdate.organizationalUnitId()) .orElseThrow(CommunicationInformationNotFoundException::new); currentCommunicationInformationDB.setMail(communicationInformationToUpdate.mail()); diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java index f9747751..c8a151c9 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java @@ -3,18 +3,13 @@ import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDBId; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.Optional; public interface CommunicationInformationJpaRepository extends JpaRepository { - @Query(value = """ - SELECT ci FROM CommunicationInformationDB ci - WHERE ci.campaign.id=?1 - AND ci.organizationUnit.id=?2""") - Optional findCommunicationInformation(String campaignId, String organizationalUnitId); + Optional findByCampaignIdAndOrganizationUnitId(String campaignId, String organizationalUnitId); List findByCampaignId(String campaignId); } From 928c3bfdff16610ae394e7e2af315ad32919aba5 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 17 Sep 2024 18:59:44 +0200 Subject: [PATCH 36/48] ci: rework of releases/tags - create release on push on main branch (git tag/release note/docker tag) - create release candidate on push on develop branch (git tag/release note/docker tag) - create fix/feature snapshot tags (git & Docker) on demand (tag overriding is allowed) based on branch name - Check pom versions in PRs - Run sonar --- .github/workflows/build.yml | 28 ------ .github/workflows/develop-release.yml | 45 --------- .github/workflows/pr-validity.yml | 46 +++++++++ .github/workflows/release-candidate.yml | 116 ++++++++++++++++++++++ .github/workflows/release.yml | 126 +++++++++++++++++------- .github/workflows/snapshot.yml | 92 +++++++++++++++++ .github/workflows/sonar.yml | 1 - 7 files changed, 342 insertions(+), 112 deletions(-) delete mode 100644 .github/workflows/build.yml delete mode 100644 .github/workflows/develop-release.yml create mode 100644 .github/workflows/pr-validity.yml create mode 100644 .github/workflows/release-candidate.yml create mode 100644 .github/workflows/snapshot.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index ee60c24d..00000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: Build - -on: - pull_request: - branches: - - '*' - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 21 - uses: actions/setup-java@v4 - with: - distribution: "temurin" - java-version: "21" - - name: Get current version - id: version - run: echo "::set-output name=prop::$(mvn -f pom.xml help:evaluate -Dexpression=project.version -q -DforceStdout)" - - run: echo ${{steps.version.outputs.prop}} - - name: Build with Maven - run: mvn install --file pom.xml --batch-mode --no-transfer-progress - - name: Upload jar - uses: actions/upload-artifact@v4 - with: - name: app-jar - path: target/ \ No newline at end of file diff --git a/.github/workflows/develop-release.yml b/.github/workflows/develop-release.yml deleted file mode 100644 index 41bd73f4..00000000 --- a/.github/workflows/develop-release.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: Release Candidate - -on: - push: - branches: - - 'develop' - tags: - - '*' - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 21 - uses: actions/setup-java@v4 - with: - distribution: "temurin" - java-version: "21" - - name: Build with Maven - run: mvn install --file pom.xml --batch-mode --no-transfer-progress - - name: Upload jar - uses: actions/upload-artifact@v4 - with: - name: app-jar - path: target/ - release: - runs-on: ubuntu-latest - steps: - - name: Checkout current branch - uses: actions/checkout@v4 - - name: Get current version - id: version - run: echo "::set-output name=prop::$(mvn -f pom.xml help:evaluate -Dexpression=project.version -q -DforceStdout)" - - run: echo ${{steps.version.outputs.prop}} - - name: Release snapshot - id: release-snapshot - uses: actions/create-release@latest - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - tag_name: ${{steps.version.outputs.prop}}-rc - release_name: Release Candidate ${{steps.version.outputs.prop}} - draft: false - prerelease: false \ No newline at end of file diff --git a/.github/workflows/pr-validity.yml b/.github/workflows/pr-validity.yml new file mode 100644 index 00000000..1575b09e --- /dev/null +++ b/.github/workflows/pr-validity.yml @@ -0,0 +1,46 @@ +name: Check version + +on: + pull_request: + types: [opened, synchronize, reopened] + +jobs: + check-version: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Get version + id: version + run: | + case "${{ github.base_ref }}" in + main) + echo "version=$(mvn -f pom.xml help:evaluate -Dexpression=project.version -q -DforceStdout)" >> $GITHUB_OUTPUT + ;; + develop) + echo "version=$(mvn -f pom.xml help:evaluate -Dexpression=project.version -q -DforceStdout)-rc" >> $GITHUB_OUTPUT + ;; + *) + echo "version=${{ github.base_ref }}" >> $GITHUB_OUTPUT + ;; + esac + + - name: Print version + run: echo ${{ steps.version.outputs.version }} + + - name: Find git tag + if: ${{ github.base_ref == 'main' || github.base_ref == 'develop' }} + uses: mukunku/tag-exists-action@v1.6.0 + id: check-tag-exists + with: + tag: ${{ steps.version.outputs.version }} + + - name: Tag verification + if: ${{ github.base_ref == 'main' || github.base_ref == 'develop' }} + id: check-tag + run: | + if [[ "${{ steps.check-tag-exists.outputs.exists }}" == "true" ]]; then + echo "Tag ${{ steps.version.outputs.version }} already exists, don't forget to upgrade your pom" + exit 1 + fi \ No newline at end of file diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml new file mode 100644 index 00000000..5063cf19 --- /dev/null +++ b/.github/workflows/release-candidate.yml @@ -0,0 +1,116 @@ +name: Release Candidate & Docker + +on: + push: + branches: + - 'develop' +jobs: + check-version: + runs-on: ubuntu-latest + outputs: + release-version: ${{ steps.version.outputs.version }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Get version + id: version + run: echo "version=$(mvn -f pom.xml help:evaluate -Dexpression=project.version -q -DforceStdout)-rc" >> $GITHUB_OUTPUT + + - name: Print version + run: echo ${{ steps.version.outputs.version }} + + - uses: mukunku/tag-exists-action@v1.6.0 + name: Check tag existence + id: check-tag-exists + with: + tag: ${{ steps.version.outputs.version }} + + - name: Tag verification + id: check-tag + run: | + if [[ "${{ steps.check-tag-exists.outputs.exists }}" == "true" ]]; then + echo "Nothing to tag/release, the tag ${{ steps.version.outputs.version }} already exists" + exit 1 + fi + + build-sources: + needs: check-version + runs-on: ubuntu-latest + steps: + - name: Extract branch name + shell: bash + run: echo "branch=$(echo ${GITHUB_REF#refs/heads/})" >>$GITHUB_OUTPUT + id: extract_branch + + - uses: actions/checkout@v4 + with: + ref: ${{ steps.extract_branch.outputs.branch }} + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + distribution: "temurin" + java-version: "21" + + - name: Build API + run: mvn package -Dchangelist=-rc --no-transfer-progress + + - name: Upload API jar + uses: actions/upload-artifact@v4 + with: + name: app-jar + path: target/*.jar + + create-release-candidate: + needs: [ check-version, build-sources ] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.ref }} + fetch-depth: 0 + + - name: Get previous tag + id: previousTag + run: echo "previousTag=$(git --no-pager tag --sort=creatordate --merged ${{ github.ref_name }} | grep '^[0-9]\+\.[0-9]\+\.[0-9]\+\-rc' | tail -1)" >> $GITHUB_OUTPUT + + - name: Create release note + id: changelog + uses: requarks/changelog-action@v1 + with: + fromTag: ${{ github.sha }} + toTag: ${{ steps.previousTag.outputs.previousTag}} + token: ${{ secrets.GITHUB_TOKEN }} + writeToFile: false + + - uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ needs.check-version.outputs.release-version }} + target_commitish: ${{ github.head_ref || github.ref }} + name: ${{ needs.check-version.outputs.release-version }} + body: ${{steps.changelog.outputs.changes}} + prerelease: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + docker: + needs: [ check-version, build-sources ] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Download uploaded jar + uses: actions/download-artifact@v4 + with: + name: app-jar + path: target/ + + - name: Publish to Docker Hub + uses: elgohr/Publish-Docker-Github-Action@v5 + with: + name: inseefr/pearl-jam-back-office + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + default_branch: ${{ github.ref }} + tags: ${{ needs.check-version.outputs.release-version }} \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 622f24d4..e1b89ac4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,66 +3,116 @@ name: Release & Docker on: push: branches: - - 'main' - tags: - - '*' - + - main jobs: - build: + check-version: + runs-on: ubuntu-latest + outputs: + release-version: ${{ steps.version-step.outputs.version }} + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '21' + + - name: Checkout repo + uses: actions/checkout@v4 + + - name: Get source version + id: version-step + run: echo "version=$(mvn -f pom.xml help:evaluate -Dexpression=project.version -q -DforceStdout)" >> $GITHUB_OUTPUT + + - name: Print source version + run: echo ${{ steps.version-step.outputs.version }} + + - uses: mukunku/tag-exists-action@v1.6.0 + name: Check tag existence + id: check-tag-exists + with: + tag: ${{ steps.version-step.outputs.version }} + + - name: Tag verification + id: check-tag + run: | + if [[ "${{ steps.check-tag-exists.outputs.exists }}" == "true" ]]; then + echo "Nothing to tag/release, the tag ${{ steps.version-step.outputs.version }} already exists" + exit 1 + fi + + if ! [[ "${{ steps.version-step.outputs.version }}" =~ ^[0-9]+.[0-9]+.[0-9]+$ ]]; then + echo "Nothing to tag/release, the tag ${{ steps.version-step.outputs.version }} is not in correct format X.Y.Z" + exit 1 + fi + + build-sources: + needs: check-version runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - name: Set up JDK 21 uses: actions/setup-java@v4 with: - distribution: "temurin" - java-version: "21" - - name: Build with Maven - run: mvn install --file pom.xml --batch-mode --no-transfer-progress - - name: Upload jar + distribution: 'temurin' + java-version: '21' + + - uses: actions/checkout@v4 + - name: Build app + run: mvn package --no-transfer-progress + + - name: Upload app jar uses: actions/upload-artifact@v4 with: name: app-jar - path: target/ - release: + path: target/*.jar + + create-release: + needs: [ check-version, build-sources ] runs-on: ubuntu-latest steps: - - name: Checkout current branch - uses: actions/checkout@v4 - - name: Get current version - id: version - run: echo "::set-output name=prop::$(mvn -f pom.xml help:evaluate -Dexpression=project.version -q -DforceStdout)" - - run: echo ${{steps.version.outputs.prop}} - - name: Release snapshot - id: release-snapshot - uses: actions/create-release@latest + - uses: actions/checkout@v4 + with: + ref: ${{ github.ref }} + fetch-depth: 0 + + - name: Get previous final release tag + id: previousTag + run: echo "previousTag=$(git --no-pager tag --sort=creatordate --merged ${{ github.ref_name }} | grep "^[0-9]\+\.[0-9]\+\.[0-9]\+$" | tail -1)" >> $GITHUB_OUTPUT + + - name: Create release note + id: changelog + uses: requarks/changelog-action@v1 + with: + fromTag: ${{ github.sha }} + toTag: ${{ steps.previousTag.outputs.previousTag}} + token: ${{ secrets.GITHUB_TOKEN }} + writeToFile: false + + - uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ needs.check-version.outputs.release-version }} + target_commitish: ${{ github.head_ref || github.ref }} + name: ${{ needs.check-version.outputs.release-version }} + body: ${{steps.changelog.outputs.changes}} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - tag_name: ${{steps.version.outputs.prop}} - release_name: Release ${{steps.version.outputs.prop}} - draft: false - prerelease: false - docker: - needs: build + + docker: + needs: [ check-version, build-sources ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - name: Download build - id: download + + - name: Download uploaded jar uses: actions/download-artifact@v4 with: name: app-jar path: target/ - - name: Get current version - id: version - run: echo "::set-output name=prop::$(mvn -f pom.xml help:evaluate -Dexpression=project.version -q -DforceStdout)" - - run: echo ${{steps.version.outputs.prop}} - - name: Publish to Registry + + - name: Publish to Docker Hub uses: elgohr/Publish-Docker-Github-Action@v5 with: name: inseefr/pearl-jam-back-office username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - tags: ${{steps.version.outputs.prop}} - + default_branch: ${{ github.ref }} + tags: ${{ needs.check-version.outputs.release-version }} \ No newline at end of file diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml new file mode 100644 index 00000000..0f15a018 --- /dev/null +++ b/.github/workflows/snapshot.yml @@ -0,0 +1,92 @@ +name: Snapshot on feature/hotfix branches + +on: + workflow_dispatch: + +jobs: + verify-branch: + runs-on: ubuntu-latest + steps: + - name: Verify branch + run: | + if [[ ! "${{ github.ref }}" =~ ^refs/heads/(feature|hotfix|feat|fix)-.* ]]; then + echo "This workflow can only be run on 'feature-*' or 'hotfix-*' branches." + exit 1 + fi + + check-version: + needs: verify-branch + runs-on: ubuntu-latest + outputs: + release-version: ${{ steps.version.outputs.version }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Get version + id: version + shell: bash + run: echo "version=$(echo ${GITHUB_REF#refs/heads/})-snapshot" >>$GITHUB_OUTPUT + + - name: Print version + run: echo ${{ steps.version.outputs.version }} + + - uses: mukunku/tag-exists-action@v1.6.0 + name: Check tag existence + id: check-tag-exists + with: + tag: ${{ steps.version.outputs.version }} + + - name: Create or update tag + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + if [[ "${{ steps.check-tag-exists.outputs.exists }}" == "true" ]]; then + echo "Tag ${{ steps.version.outputs.version }} exists, deleting it" + git push origin :refs/tags/${{ steps.version.outputs.version }} + fi + echo "Creating new tag ${{ steps.version.outputs.version }}..." + git tag ${{ steps.version.outputs.version }} ${{ github.sha }} + git push origin refs/tags/${{ steps.version.outputs.version }}:refs/tags/${{ steps.version.outputs.version }} + + build-sources: + needs: check-version + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + distribution: "temurin" + java-version: "21" + + - name: Build API + run: mvn package --no-transfer-progress + + - name: Upload API jar + uses: actions/upload-artifact@v4 + with: + name: app-jar + path: target/*.jar + + publish-docker: + needs: [ check-version, build-sources ] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Download uploaded jar + uses: actions/download-artifact@v4 + with: + name: app-jar + path: target/ + + - name: Publish to Docker Hub + uses: elgohr/Publish-Docker-Github-Action@v5 + with: + name: inseefr/pearl-jam-back-office + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + default_branch: ${{ github.ref }} + tags: ${{ needs.check-version.outputs.release-version }} \ No newline at end of file diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 9915b706..96ee81bb 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -4,7 +4,6 @@ on: push: branches: - main - - master - develop pull_request: types: [opened, synchronize, reopened] From 53bf0a35c9044835b7aee6db727580912a7d5920 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 17 Sep 2024 19:00:16 +0200 Subject: [PATCH 37/48] build: create renovate configuration --- pom.xml | 2 +- renovate.json | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 renovate.json diff --git a/pom.xml b/pom.xml index 390262fb..a90e4c9e 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ fr.insee.pearljam pearljam-back-office - 5.1.0 + 5.1.1 Pearl-Jam-Back-Office Back-office services for PearlJam diff --git a/renovate.json b/renovate.json new file mode 100644 index 00000000..1f79db43 --- /dev/null +++ b/renovate.json @@ -0,0 +1,44 @@ +{ + "extends": ["config:best-practices", ":semanticCommits", ":disableRateLimiting"], + "baseBranches": ["develop", "main"], + "packageRules": [ + { + "enabled": false, + "matchPackagePatterns": ["*"], + "matchBaseBranches": ["main"] + }, + { + "matchPackagePatterns": ["*"], + "matchBaseBranches": ["develop"], + "labels": ["dependencies"], + "bumpVersion": "patch", + "dependencyDashboardApproval": true + }, + { + "groupName": "spring", + "groupSlug": "spring", + "matchPackagePatterns": ["org.springframework.*"], + "matchBaseBranches": ["develop"], + "bumpVersion": "minor", + "dependencyDashboardApproval": true + }, + { + "groupName": "all minor dependencies", + "groupSlug": "all-minor-patch", + "matchPackagePatterns": ["*"], + "matchBaseBranches": ["develop"], + "matchUpdateTypes": ["minor", "patch"], + "bumpVersion": "patch", + "dependencyDashboardApproval": false + } + ], + "vulnerabilityAlerts": { + "enabled": true, + "baseBranches": ["main"], + "addLabels": ["security"], + "bumpVersion": "patch", + "schedule": ["before 5:00am"] + }, + "schedule": ["every weekend"], + "timezone": "Europe/Paris" +} \ No newline at end of file From 58720c562fd78212c781d8916592b419d14de982 Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 18 Sep 2024 18:39:47 +0200 Subject: [PATCH 38/48] chore(build): bump lib versions --- .mvn/wrapper/maven-wrapper.properties | 2 +- Dockerfile | 2 +- pom.xml | 14 +++++++------- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index fe378a15..443d8849 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -15,4 +15,4 @@ # specific language governing permissions and limitations # under the License. wrapperVersion=3.3.1 -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/Dockerfile b/Dockerfile index c6802c56..1f7a666e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM eclipse-temurin:21.0.3_9-jre-alpine +FROM eclipse-temurin:21.0.4_7-jre-alpine WORKDIR /opt/app/ COPY ./target/*.jar /opt/app/app.jar diff --git a/pom.xml b/pom.xml index a90e4c9e..cfab81e6 100644 --- a/pom.xml +++ b/pom.xml @@ -7,14 +7,14 @@ fr.insee.pearljam pearljam-back-office - 5.1.1 + 5.1.2 Pearl-Jam-Back-Office Back-office services for PearlJam org.springframework.boot spring-boot-starter-parent - 3.3.2 + 3.3.3 @@ -22,7 +22,7 @@ 21 UTF-8 UTF-8 - 42.7.3 + 42.7.4 inseefr https://sonarcloud.io @@ -48,7 +48,7 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - 2.5.0 + 2.6.0 @@ -127,7 +127,7 @@ org.codehaus.janino janino - 3.1.8 + 3.1.12 @@ -223,7 +223,7 @@ jakarta.xml.bind jakarta.xml.bind-api - 4.0.1 + 4.0.2 org.springframework.boot @@ -250,7 +250,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.2.5 + 3.5.0 **/TestAuthKeyCloak From 63f64ecdcf94fdcd21308cd7c3e98b232390f811 Mon Sep 17 00:00:00 2001 From: davdarras Date: Mon, 23 Sep 2024 10:12:22 +0200 Subject: [PATCH 39/48] fix: delete address from communication informations --- .../CommunicationInformationCampaignCreateDto.java | 2 -- .../CommunicationInformationCampaignUpdateDto.java | 3 --- .../dto/input/CommunicationInformationUpdateDto.java | 3 --- .../output/CommunicationInformationResponseDto.java | 2 -- .../model/communication/CommunicationInformation.java | 1 - .../adapter/CommunicationInformationDaoAdapter.java | 1 - .../campaign/entity/CommunicationInformationDB.java | 3 --- .../544_update_communication_information.xml | 10 ++++++++++ src/main/resources/db/dataset/init-demo-data.sql | 7 +++---- src/main/resources/db/dataset/reinit-test-data.sql | 5 ++--- src/main/resources/db/master.xml | 6 +++++- .../controller/CampaignControllerCreateTest.java | 1 - .../controller/CampaignControllerUpdateTest.java | 5 ++--- .../CommunicationInformationControllerTest.java | 2 +- .../pearljam/integration/campaign/CampaignIT.java | 11 ----------- .../campaign/CommunicationInformationIT.java | 3 --- 16 files changed, 23 insertions(+), 42 deletions(-) create mode 100644 src/main/resources/db/changelog/544_update_communication_information.xml diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java index d2561706..94e2c369 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java @@ -10,14 +10,12 @@ public record CommunicationInformationCampaignCreateDto( @NotBlank String organizationalUnit, - String address, String mail, String tel) { public static CommunicationInformation toModel(@NonNull CommunicationInformationCampaignCreateDto communicationInformation, String campaignId) { return new CommunicationInformation(campaignId, communicationInformation.organizationalUnit(), - communicationInformation.address(), communicationInformation.mail(), communicationInformation.tel()); } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java index 8ea2528c..f2044e32 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java @@ -10,8 +10,6 @@ public record CommunicationInformationCampaignUpdateDto( @NotBlank String organizationalUnit, @JsonProperty(required = true) - String address, - @JsonProperty(required = true) String mail, @JsonProperty(required = true) String tel) { @@ -23,7 +21,6 @@ public static CommunicationInformation toModel(CommunicationInformationCampaignU return new CommunicationInformation( campaignId, communicationInformation.organizationalUnit(), - communicationInformation.address(), communicationInformation.mail(), communicationInformation.tel()); } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java index 6ccfbfa5..414499bd 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java @@ -5,8 +5,6 @@ import lombok.NonNull; public record CommunicationInformationUpdateDto( - @JsonProperty(required = true) - String address, @JsonProperty(required = true) String mail, @JsonProperty(required = true) @@ -21,7 +19,6 @@ public static CommunicationInformation toModel(CommunicationInformationUpdateDto return new CommunicationInformation( campaignId, ouId, - communicationInformation.address(), communicationInformation.mail(), communicationInformation.tel()); } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java index 1927b513..53ac8d6b 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java @@ -6,7 +6,6 @@ public record CommunicationInformationResponseDto( String organizationalUnit, - String address, String mail, String tel) { @@ -14,7 +13,6 @@ public static List fromModel(List new CommunicationInformationResponseDto( communicationInformation.organizationalUnitId(), - communicationInformation.address(), communicationInformation.mail(), communicationInformation.tel() )) diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java index a81db0cd..272a5d8d 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java @@ -3,7 +3,6 @@ public record CommunicationInformation( String campaignId, String organizationalUnitId, - String address, String mail, String tel ) { diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java index f2004d08..f89fe1b0 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java @@ -38,7 +38,6 @@ public void update(CommunicationInformation communicationInformationToUpdate) { .orElseThrow(CommunicationInformationNotFoundException::new); currentCommunicationInformationDB.setMail(communicationInformationToUpdate.mail()); currentCommunicationInformationDB.setTel(communicationInformationToUpdate.tel()); - currentCommunicationInformationDB.setAddress(communicationInformationToUpdate.address()); crudRepository.save(currentCommunicationInformationDB); } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java index 1e413c74..8543fdec 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java @@ -38,7 +38,6 @@ public class CommunicationInformationDB implements Serializable { private Campaign campaign; private String mail; - private String address; private String tel; public static CommunicationInformationDB fromModel(CommunicationInformation communicationInformation, Campaign campaign, OrganizationUnit organizationUnit) { @@ -46,7 +45,6 @@ public static CommunicationInformationDB fromModel(CommunicationInformation comm return new CommunicationInformationDB(id, organizationUnit, campaign, communicationInformation.mail(), - communicationInformation.address(), communicationInformation.tel()); } @@ -54,7 +52,6 @@ public static CommunicationInformation toModel(CommunicationInformationDB commun return new CommunicationInformation( communicationInformationDB.getCommunicationInformationId().getCampaignId(), communicationInformationDB.getCommunicationInformationId().getOrganizationUnitId(), - communicationInformationDB.getAddress(), communicationInformationDB.getMail(), communicationInformationDB.getTel()); } diff --git a/src/main/resources/db/changelog/544_update_communication_information.xml b/src/main/resources/db/changelog/544_update_communication_information.xml new file mode 100644 index 00000000..9f037d94 --- /dev/null +++ b/src/main/resources/db/changelog/544_update_communication_information.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/src/main/resources/db/dataset/init-demo-data.sql b/src/main/resources/db/dataset/init-demo-data.sql index 0925591f..08c838b2 100644 --- a/src/main/resources/db/dataset/init-demo-data.sql +++ b/src/main/resources/db/dataset/init-demo-data.sql @@ -145,13 +145,12 @@ INSERT INTO visibility ( INSERT INTO communication_information ( organization_unit_id, campaign_id, - address, mail, tel ) VALUES - ('OU-NORTH', 'SIMPSONS2020X00','50 beverly hills street, north region', 'north-simpsons@nooneknows.fr', '0321234567'), - ('OU-SOUTH', 'SIMPSONS2020X00','60 rue des clopinettes, south region', 'south-simpsons@nooneknows.fr', NULL), - ('OU-NORTH', 'VQS2021X00', NULL, 'north-vqs@nooneknows.fr', ''); + ('OU-NORTH', 'SIMPSONS2020X00', 'north-simpsons@nooneknows.fr', '0321234567'), + ('OU-SOUTH', 'SIMPSONS2020X00', 'south-simpsons@nooneknows.fr', NULL), + ('OU-NORTH', 'VQS2021X00', 'north-vqs@nooneknows.fr', ''); INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', TRUE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; diff --git a/src/main/resources/db/dataset/reinit-test-data.sql b/src/main/resources/db/dataset/reinit-test-data.sql index d35dce62..265fb6fe 100644 --- a/src/main/resources/db/dataset/reinit-test-data.sql +++ b/src/main/resources/db/dataset/reinit-test-data.sql @@ -124,12 +124,11 @@ INSERT INTO visibility ( INSERT INTO communication_information ( organization_unit_id, campaign_id, - address, mail, tel ) VALUES - ('OU-NORTH', 'SIMPSONS2020X00','50 beverly hills street, north region', 'north-simpsons@nooneknows.fr', '0321234567'), - ('OU-SOUTH', 'VQS2021X00', NULL, 'north-vqs@nooneknows.fr', ''); + ('OU-NORTH', 'SIMPSONS2020X00', 'north-simpsons@nooneknows.fr', '0321234567'), + ('OU-SOUTH', 'VQS2021X00', 'north-vqs@nooneknows.fr', ''); diff --git a/src/main/resources/db/master.xml b/src/main/resources/db/master.xml index 0665c907..350cfac3 100644 --- a/src/main/resources/db/master.xml +++ b/src/main/resources/db/master.xml @@ -51,7 +51,11 @@ - + + + + + \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java index 20c1304a..2e1d3ac8 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java @@ -221,7 +221,6 @@ public CampaignCreateDto generateDefaultCampaign() { 1721683264000L, 1721683265000L); CommunicationInformationCampaignCreateDto communicationInformation = new CommunicationInformationCampaignCreateDto("OU-SOUTH", - "address", "mail", "tel"); ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java index 7d444833..4ce2fd2a 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java @@ -158,7 +158,6 @@ private CampaignUpdateDto generateDefaultCampaign() { 1721683265000L); CommunicationInformationCampaignUpdateDto firstCommunication = generateCommunicationInformation("OU-SOUTH", - "address", "mail", "tel"); ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); @@ -171,8 +170,8 @@ private CampaignUpdateDto generateDefaultCampaign() { List.of(firstReferent, secondReferent)); } - private CommunicationInformationCampaignUpdateDto generateCommunicationInformation(String ouId, String address, String mail, String tel) { - return new CommunicationInformationCampaignUpdateDto(ouId, address, mail, tel); + private CommunicationInformationCampaignUpdateDto generateCommunicationInformation(String ouId, String mail, String tel) { + return new CommunicationInformationCampaignUpdateDto(ouId, mail, tel); } private CampaignUpdateDto generateCampaign(String campaignLabel, diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java index c2a0b330..9d336631 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java @@ -42,7 +42,7 @@ void setup() { void testUpdateCommunicationInformation01() throws Exception { communicationInformationService.setShouldThrowCommunicationInformationNotFoundException(true); CommunicationInformationUpdateDto communicationInformationToUpdate = - new CommunicationInformationUpdateDto("addr", "mail", "0123456789"); + new CommunicationInformationUpdateDto("mail", "0123456789"); mockMvc.perform(put(updatePath) .content(JsonTestHelper.toJson(communicationInformationToUpdate)) .contentType(MediaType.APPLICATION_JSON)) diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index af0c129d..28e3e975 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -83,7 +83,6 @@ void testGetCampaign() throws Exception { "communicationInformations":[ { "organizationalUnit":"OU-NORTH", - "address":"50 beverly hills street, north region", "mail":"north-simpsons@nooneknows.fr", "tel":"0321234567" } @@ -151,13 +150,11 @@ void testCreateCampaign() throws Exception { "communicationInformations": [ { "organizationalUnit": "OU-NORTH", - "address": "addr1", "mail": "mail1", "tel": "tel1" }, { "organizationalUnit":"OU-SOUTH", - "address": "addr2", "mail": "mail2" } ], @@ -220,13 +217,11 @@ void testCreateCampaign() throws Exception { .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, campaignId, "OU-NORTH", - "addr1", "mail1", "tel1")) .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, campaignId, "OU-SOUTH", - "addr2", "mail2", null)); @@ -250,13 +245,11 @@ private void assertCommunicationTemplate(CommunicationTemplateDB communicationTe private void assertCommunicationInformation(CommunicationInformationDB communicationInformationToCheck, String campaignId, String organizationalUnitId, - String address, String mail, String tel) { assertThat(communicationInformationToCheck.getCampaign().getId()).isEqualTo(campaignId); assertThat(communicationInformationToCheck.getOrganizationUnit().getId()).isEqualTo(organizationalUnitId); assertThat(communicationInformationToCheck.getTel()).isEqualTo(tel); - assertThat(communicationInformationToCheck.getAddress()).isEqualTo(address); assertThat(communicationInformationToCheck.getMail()).isEqualTo(mail); } @@ -292,13 +285,11 @@ void testUpdateCampaign() throws Exception { "communicationInformations": [ { "organizationalUnit": "OU-NORTH", - "address": "addr1", "mail": "mail1", "tel": "tel1" }, { "organizationalUnit": "OU-SOUTH", - "address": "addr2", "mail": "mail2", "tel": "tel2" } @@ -351,13 +342,11 @@ void testUpdateCampaign() throws Exception { .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, campaignId, "OU-NORTH", - "addr1", "mail1", "tel1")) .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, campaignId, "OU-SOUTH", - "addr2", "mail2", "tel2")); diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java index f56eb997..53a0fcce 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java @@ -53,7 +53,6 @@ void testGetCommunicationInformations() throws Exception { [ { "organizationalUnit": "OU-NORTH", - "address": "50 beverly hills street, north region", "mail": "north-simpsons@nooneknows.fr", "tel": "0321234567" } @@ -70,7 +69,6 @@ void testUpdateCommunicationInformation() throws Exception { String updatePath = String.format("/api/campaign/%s/organizational-unit/%s/communication-information", campaignId, organizationalUnitId); String content = """ { - "address": "newAddr", "mail": "newMail", "tel": "newTel" }"""; @@ -85,7 +83,6 @@ void testUpdateCommunicationInformation() throws Exception { assertThat(communicationDBToCheck.getCampaign().getId()).isEqualTo(campaignId); assertThat(communicationDBToCheck.getOrganizationUnit().getId()).isEqualTo(organizationalUnitId); - assertThat(communicationDBToCheck.getAddress()).isEqualTo("newAddr"); assertThat(communicationDBToCheck.getMail()).isEqualTo("newMail"); assertThat(communicationDBToCheck.getTel()).isEqualTo("newTel"); } From 45017b0e4705eff772496cc4d98c307fc1dcb179 Mon Sep 17 00:00:00 2001 From: davdarras Date: Mon, 23 Sep 2024 10:16:31 +0200 Subject: [PATCH 40/48] typo: rename communications to communication templates --- .../pearljam/api/campaign/dto/input/CampaignCreateDto.java | 2 +- .../fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java | 2 +- .../java/fr/insee/pearljam/integration/campaign/CampaignIT.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java index 5ed65423..93cb41c8 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java @@ -26,7 +26,7 @@ public record CampaignCreateDto ( List communicationInformations, @Valid @NoDuplicateMediumAndType - List communications, + List communicationTemplates, List referents, String email, IdentificationConfiguration identificationConfiguration, diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index 9e8ad4f6..081a3892 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -193,7 +193,7 @@ public void createCampaign(CampaignCreateDto campaignDto) updateReferents(campaign, campaignDto.referents()); } - List communicationTemplatesToCreate = CommunicationTemplateCreateDto.toModel(campaignDto.communications()); + List communicationTemplatesToCreate = CommunicationTemplateCreateDto.toModel(campaignDto.communicationTemplates()); if(communicationTemplatesToCreate != null) { List communicationsDBToCreate = CommunicationTemplateDB.fromModel(communicationTemplatesToCreate, campaign); campaign.setCommunicationTemplates(communicationsDBToCreate); diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index 28e3e975..7bcfd6f8 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -158,7 +158,7 @@ void testCreateCampaign() throws Exception { "mail": "mail2" } ], - "communications": [ + "communicationTemplates": [ { "meshuggahId": "meshId1", "medium": "LETTER", From 81b8e721feefacee0a436804bba955dd57b5130f Mon Sep 17 00:00:00 2001 From: davdarras Date: Mon, 30 Sep 2024 10:59:36 +0200 Subject: [PATCH 41/48] fix: create ready com request status when creaing com requests --- pom.xml | 2 +- .../impl/SurveyUnitUpdateServiceImpl.java | 5 ++++- .../dto/CommunicationRequestCreateDto.java | 5 +++-- .../communication/CommunicationRequest.java | 8 +++++--- .../CommunicationRequestStatus.java | 5 +++-- .../api/authKeycloak/TestAuthKeyCloak.java | 4 ++-- .../insee/pearljam/api/noAuth/TestNoAuth.java | 4 ++-- ...ava => FixedDateServiceConfiguration.java} | 2 +- .../model/CommunicationRequestTest.java | 6 ++++-- .../SurveyUnitUpdateServiceImplTest.java | 16 ++++++++++++--- .../integration/campaign/CampaignIT.java | 2 +- .../campaign/CommunicationInformationIT.java | 2 +- .../campaign/CommunicationTemplateIT.java | 2 +- .../integration/campaign/VisibilityIT.java | 2 +- .../integration/surveyunit/SurveyUnitIT.java | 20 ++++++++++++++++++- 15 files changed, 61 insertions(+), 24 deletions(-) rename src/test/java/fr/insee/pearljam/config/{DateServiceConfiguration.java => FixedDateServiceConfiguration.java} (92%) diff --git a/pom.xml b/pom.xml index cfab81e6..707cf2ed 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ fr.insee.pearljam pearljam-back-office - 5.1.2 + 5.1.3 Pearl-Jam-Back-Office Back-office services for PearlJam diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java index e89b59eb..bdc5df97 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java @@ -5,6 +5,7 @@ import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestCreateDto; import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; +import fr.insee.pearljam.domain.campaign.port.userside.DateService; import fr.insee.pearljam.domain.surveyunit.model.Comment; import fr.insee.pearljam.domain.surveyunit.model.Identification; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; @@ -24,6 +25,7 @@ public class SurveyUnitUpdateServiceImpl implements SurveyUnitUpdateService { private final CommunicationRequestRepository communicationRequestRepository; + private final DateService dateService; @Transactional @Override @@ -36,7 +38,8 @@ public void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitUpdateDto sur surveyUnit.updateComments(commentsToUpdate); } if(surveyUnitUpdateDto.communicationRequests() != null) { - List communicationRequestsToCreate = CommunicationRequestCreateDto.toModel(surveyUnitUpdateDto.communicationRequests()); + Long timestamp = dateService.getCurrentTimestamp(); + List communicationRequestsToCreate = CommunicationRequestCreateDto.toModel(surveyUnitUpdateDto.communicationRequests(), timestamp); communicationRequestRepository.addCommunicationRequests(surveyUnit, communicationRequestsToCreate); } diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java index 68c4de22..e2279fc0 100644 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java @@ -28,12 +28,13 @@ public record CommunicationRequestCreateDto( * Converts a list of communication request DTOs into a list of communication request models. * * @param requests the list of communication request DTOs + * @param readyTimestamp ready timestamp of the communication requests (when does the communication request are created in the back) * @return the list of communication request models */ - public static List toModel(List requests) { + public static List toModel(List requests, Long readyTimestamp) { return requests.stream() .map(request -> - CommunicationRequest.create(request.communicationTemplateId(), request.creationTimestamp(), request.reason())) + CommunicationRequest.create(request.communicationTemplateId(), request.creationTimestamp(), readyTimestamp, request.reason())) .toList(); } } diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java index 7116f3f9..548c853c 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java @@ -13,13 +13,15 @@ public record CommunicationRequest( /** * Create a communication request for messhugah * @param communicationTemplateId communication configuration id - * @param creationTimestamp creation date of the communication request + * @param creationTimestamp creation date of the communication request (coming from the front) + * @param readyTimestamp ready timestamp of the communication request (when does the communication request is created in the back) * @param reason reason why the communication request is created * @return {@link CommunicationRequest} communication request object */ - public static CommunicationRequest create(Long communicationTemplateId, Long creationTimestamp, CommunicationRequestReason reason) { + public static CommunicationRequest create(Long communicationTemplateId, Long creationTimestamp, Long readyTimestamp, CommunicationRequestReason reason) { List status = new ArrayList<>(); - status.add(CommunicationRequestStatus.create(creationTimestamp)); + status.add(CommunicationRequestStatus.create(creationTimestamp, CommunicationStatusType.INITIATED)); + status.add(CommunicationRequestStatus.create(readyTimestamp, CommunicationStatusType.READY)); return new CommunicationRequest(null, communicationTemplateId, reason, CommunicationRequestEmitter.INTERVIEWER, status); } } diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestStatus.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestStatus.java index 6d02ac84..5520d32c 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestStatus.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequestStatus.java @@ -8,9 +8,10 @@ public record CommunicationRequestStatus( /** * Create a CommunicationRequestStatus * @param timestamp status creation date + * @param statusType status type * @return {@link CommunicationRequestStatus} communication request status object */ - public static CommunicationRequestStatus create(Long timestamp) { - return new CommunicationRequestStatus(null, timestamp, CommunicationStatusType.INITIATED); + public static CommunicationRequestStatus create(Long timestamp, CommunicationStatusType statusType) { + return new CommunicationRequestStatus(null, timestamp, statusType); } } diff --git a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java index 7f0ef5e0..eff2c46b 100644 --- a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java +++ b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java @@ -25,7 +25,7 @@ import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.ScriptConstants; -import fr.insee.pearljam.config.DateServiceConfiguration; +import fr.insee.pearljam.config.FixedDateServiceConfiguration; import fr.insee.pearljam.domain.surveyunit.model.CommentType; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import fr.insee.pearljam.infrastructure.campaign.jpa.VisibilityJpaRepository; @@ -77,7 +77,7 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) @RequiredArgsConstructor -@Import(DateServiceConfiguration.class) +@Import(FixedDateServiceConfiguration.class) class TestAuthKeyCloak { private final SurveyUnitService surveyUnitService; diff --git a/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java b/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java index 69d79578..048ef24b 100644 --- a/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java +++ b/src/test/java/fr/insee/pearljam/api/noAuth/TestNoAuth.java @@ -8,7 +8,7 @@ import fr.insee.pearljam.api.repository.ClosingCauseRepository; import fr.insee.pearljam.api.repository.MessageRepository; import fr.insee.pearljam.api.utils.ScriptConstants; -import fr.insee.pearljam.config.DateServiceConfiguration; +import fr.insee.pearljam.config.FixedDateServiceConfiguration; import lombok.RequiredArgsConstructor; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; @@ -40,7 +40,7 @@ @TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) @RequiredArgsConstructor @TestMethodOrder(MethodOrderer.OrderAnnotation.class) -@Import(DateServiceConfiguration.class) +@Import(FixedDateServiceConfiguration.class) class TestNoAuth { private final MessageRepository messageRepository; diff --git a/src/test/java/fr/insee/pearljam/config/DateServiceConfiguration.java b/src/test/java/fr/insee/pearljam/config/FixedDateServiceConfiguration.java similarity index 92% rename from src/test/java/fr/insee/pearljam/config/DateServiceConfiguration.java rename to src/test/java/fr/insee/pearljam/config/FixedDateServiceConfiguration.java index e8c8cfd8..f406b871 100644 --- a/src/test/java/fr/insee/pearljam/config/DateServiceConfiguration.java +++ b/src/test/java/fr/insee/pearljam/config/FixedDateServiceConfiguration.java @@ -9,7 +9,7 @@ @TestConfiguration @Profile("test") -public class DateServiceConfiguration { +public class FixedDateServiceConfiguration { @Bean @Primary diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java index 1db96216..84f40b34 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java @@ -13,10 +13,11 @@ void testCreateCommunicationRequest() { // Given Long communicationTemplateId = 1L; Long creationDate = System.currentTimeMillis(); + Long readyDate = System.currentTimeMillis(); CommunicationRequestReason reason = CommunicationRequestReason.REFUSAL; // When - CommunicationRequest communicationRequest = CommunicationRequest.create(communicationTemplateId, creationDate, reason); + CommunicationRequest communicationRequest = CommunicationRequest.create(communicationTemplateId, creationDate, readyDate, reason); // Then assertNotNull(communicationRequest); @@ -25,7 +26,8 @@ void testCreateCommunicationRequest() { assertEquals(reason, communicationRequest.reason()); assertEquals(CommunicationRequestEmitter.INTERVIEWER, communicationRequest.emitter()); assertNotNull(communicationRequest.status()); - assertEquals(1, communicationRequest.status().size()); + assertEquals(2, communicationRequest.status().size()); assertEquals(creationDate, communicationRequest.status().getFirst().date()); + assertEquals(readyDate, communicationRequest.status().getLast().date()); } } diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java index b0b51e15..c9d14417 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java @@ -3,6 +3,8 @@ import fr.insee.pearljam.api.domain.*; import fr.insee.pearljam.api.service.impl.SurveyUnitUpdateServiceImpl; import fr.insee.pearljam.api.surveyunit.dto.*; +import fr.insee.pearljam.domain.campaign.port.userside.DateService; +import fr.insee.pearljam.domain.campaign.service.dummy.FixedDateService; import fr.insee.pearljam.domain.surveyunit.model.CommentType; import fr.insee.pearljam.domain.surveyunit.model.communication.*; import fr.insee.pearljam.domain.surveyunit.model.question.*; @@ -28,11 +30,13 @@ class SurveyUnitUpdateServiceImplTest { private SurveyUnit surveyUnit; private SurveyUnitUpdateDto surveyUnitDto; private CommunicationTemplateDB communicationTemplate; + private DateService dateService; @BeforeEach void setup() { + dateService = new FixedDateService(); communicationRequestFakeRepository = new CommunicationRequestFakeRepository(); - surveyUnitService = new SurveyUnitUpdateServiceImpl(communicationRequestFakeRepository); + surveyUnitService = new SurveyUnitUpdateServiceImpl(communicationRequestFakeRepository, dateService); surveyUnit = new SurveyUnit("id", true, true, null, null, null, null, null, null); @@ -74,13 +78,19 @@ void testUpdateCommunication01() { 1L, CommunicationRequestReason.UNREACHABLE, CommunicationRequestEmitter.INTERVIEWER, - List.of(tuple(null, 12345678910L, CommunicationStatusType.INITIATED)) + List.of( + tuple(null, 12345678910L, CommunicationStatusType.INITIATED), + tuple(null, dateService.getCurrentTimestamp(), CommunicationStatusType.READY) + ) ), tuple(null, 2L, CommunicationRequestReason.REFUSAL, CommunicationRequestEmitter.INTERVIEWER, - List.of(tuple(null, 1234567891011L, CommunicationStatusType.INITIATED)) + List.of( + tuple(null, 1234567891011L, CommunicationStatusType.INITIATED), + tuple(null, dateService.getCurrentTimestamp(), CommunicationStatusType.READY) + ) ) ); } diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index 7bcfd6f8..7a0691b9 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -33,7 +33,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@ActiveProfiles("auth") +@ActiveProfiles(profiles = {"auth", "test"}) @AutoConfigureMockMvc @ContextConfiguration @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java index 53a0fcce..45b631a7 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java @@ -27,7 +27,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@ActiveProfiles("auth") +@ActiveProfiles(profiles = {"auth", "test"}) @AutoConfigureMockMvc @ContextConfiguration @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java index a0c3aacb..973a110f 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java @@ -17,7 +17,7 @@ import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -@ActiveProfiles("auth") +@ActiveProfiles(profiles = {"auth", "test"}) @AutoConfigureMockMvc @ContextConfiguration @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java index 5f522c27..02a42360 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java @@ -28,7 +28,7 @@ import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; -@ActiveProfiles("auth") +@ActiveProfiles(profiles = {"auth", "test"}) @AutoConfigureMockMvc @ContextConfiguration @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index bb57cb16..5b53817a 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -3,6 +3,8 @@ import fr.insee.pearljam.api.service.SurveyUnitService; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import fr.insee.pearljam.api.utils.ScriptConstants; +import fr.insee.pearljam.config.FixedDateServiceConfiguration; +import fr.insee.pearljam.domain.campaign.port.userside.DateService; import org.json.JSONException; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; @@ -10,6 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; @@ -24,10 +27,11 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@ActiveProfiles("auth") +@ActiveProfiles(profiles = {"auth", "test"}) @AutoConfigureMockMvc @ContextConfiguration @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Import(FixedDateServiceConfiguration.class) @Transactional class SurveyUnitIT { @@ -37,6 +41,9 @@ class SurveyUnitIT { @Autowired private SurveyUnitService surveyUnitService; + @Autowired + private DateService dateService; + @Test void testGetAllSurveyUnits() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/api/survey-units") @@ -283,6 +290,7 @@ void testGetSurveyUnitDetail() throws Exception { @Test @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) void testPutSurveyUnitDetail() throws Exception { + long currentTimestamp = dateService.getCurrentTimestamp(); String updateJson = """ { "id":"20", @@ -494,6 +502,11 @@ void testPutSurveyUnitDetail() throws Exception { { "date":1721903754305, "status":"INITIATED" + }, + { + "date":""" + currentTimestamp + """ + , + "status":"READY" } ] }, @@ -516,6 +529,11 @@ void testPutSurveyUnitDetail() throws Exception { { "date":1721903754405, "status":"INITIATED" + }, + { + "date":""" + currentTimestamp + """ + , + "status":"READY" } ] }, From 489a6137ec652a54d548e6ebedd73c52c3fc0033 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 10 Sep 2024 16:12:39 +0200 Subject: [PATCH 42/48] feat: add use letter communication --- .../input/VisibilityCampaignCreateDto.java | 7 +- .../input/VisibilityCampaignUpdateDto.java | 6 +- .../dto/input/VisibilityUpdateDto.java | 6 +- .../dto/output/VisibilityCampaignDto.java | 8 +- .../domain/campaign/model/Visibility.java | 10 ++- .../adapter/VisibilityDaoAdapter.java | 2 +- .../campaign/entity/VisibilityDB.java | 13 ++- ...44_add_letter_communication_visibility.xml | 15 ++++ .../resources/db/dataset/init-demo-data.sql | 24 +++-- .../resources/db/dataset/reinit-test-data.sql | 17 ++-- src/main/resources/db/master.xml | 3 +- .../CampaignControllerCreateTest.java | 32 ++++--- .../CampaignControllerUpdateTest.java | 14 +-- .../controller/VisibilityControllerTest.java | 8 +- .../VisibilityCampaignCreateDtoTest.java | 3 +- .../VisibilityCampaignUpdateDtoTest.java | 6 +- .../dto/input/VisibilityUpdateDtoTest.java | 2 +- .../dto/output/VisibilityCampaignDtoTest.java | 4 +- .../domain/campaign/model/VisibilityTest.java | 21 ++--- .../service/CampaignServiceImplTest.java | 18 ++-- .../service/VisibilityServiceImplTest.java | 11 +-- .../dummy/VisibilityFakeRepository.java | 2 +- .../adapter/VisibilityDaoAdapterTest.java | 8 +- .../campaign/entity/VisibilityDBTest.java | 90 ++++++++++++------- .../integration/campaign/CampaignIT.java | 29 +++--- .../integration/campaign/VisibilityIT.java | 10 ++- 26 files changed, 233 insertions(+), 136 deletions(-) create mode 100644 src/main/resources/db/changelog/544_add_letter_communication_visibility.xml diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java index ea724614..a6241d9b 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java @@ -35,7 +35,9 @@ public record VisibilityCampaignCreateDto( @NotNull Long endDate, @NotBlank - String organizationalUnit + String organizationalUnit, + @NotNull + Boolean useLetterCommunication ) { public static Visibility toModel(@NonNull VisibilityCampaignCreateDto visibility, String campaignId) { @@ -46,7 +48,8 @@ public static Visibility toModel(@NonNull VisibilityCampaignCreateDto visibility visibility.identificationPhaseStartDate(), visibility.collectionStartDate(), visibility.collectionEndDate(), - visibility.endDate()); + visibility.endDate(), + visibility.useLetterCommunication()); } public static List toModel(List visibilities, String campaignId) { diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java index 2698af45..a6eed06e 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java @@ -28,7 +28,8 @@ public record VisibilityCampaignUpdateDto( Long collectionEndDate, Long endDate, @NotBlank - String organizationalUnit + String organizationalUnit, + Boolean useLetterCommunication ) { public static Visibility toModel(@NonNull VisibilityCampaignUpdateDto visibility, String campaignId) { return new Visibility(campaignId, @@ -38,7 +39,8 @@ public static Visibility toModel(@NonNull VisibilityCampaignUpdateDto visibility visibility.identificationPhaseStartDate(), visibility.collectionStartDate(), visibility.collectionEndDate(), - visibility.endDate()); + visibility.endDate(), + visibility.useLetterCommunication()); } public static List toModel(List visibilitiesDto, String campaignId) { diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java index 2e7062d4..712a24bc 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java @@ -23,7 +23,8 @@ public record VisibilityUpdateDto( Long identificationPhaseStartDate, Long collectionStartDate, Long collectionEndDate, - Long endDate + Long endDate, + Boolean useLetterCommunication ) { public static Visibility toModel(@NonNull VisibilityUpdateDto visibilityDto, @@ -35,6 +36,7 @@ public static Visibility toModel(@NonNull VisibilityUpdateDto visibilityDto, visibilityDto.identificationPhaseStartDate(), visibilityDto.collectionStartDate(), visibilityDto.collectionEndDate(), - visibilityDto.endDate()); + visibilityDto.endDate(), + visibilityDto.useLetterCommunication()); } } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java index 5fd7f26f..a28362fe 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java @@ -6,7 +6,7 @@ import java.util.List; @JsonPropertyOrder({ "organizationalUnit", "managementStartDate", "interviewerStartDate", - "identificationPhaseStartDate", "collectionStartDate", "collectionEndDate", "endDate"}) + "identificationPhaseStartDate", "collectionStartDate", "collectionEndDate", "endDate", "useLetterCommunication"}) public record VisibilityCampaignDto( String organizationalUnit, Long managementStartDate, @@ -14,7 +14,8 @@ public record VisibilityCampaignDto( Long identificationPhaseStartDate, Long collectionStartDate, Long collectionEndDate, - Long endDate) { + Long endDate, + boolean useLetterCommunication) { public static List fromModel(List visibilities) { return visibilities.stream() @@ -25,7 +26,8 @@ public static List fromModel(List visibilitie visibility.identificationPhaseStartDate(), visibility.collectionStartDate(), visibility.collectionEndDate(), - visibility.endDate() + visibility.endDate(), + visibility.useLetterCommunication() )) .toList(); } diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java index c2f3fbfc..5abe9f83 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java @@ -11,6 +11,7 @@ * @param collectionStartDate The start date of collection * @param collectionEndDate The end date of collection * @param endDate The end date of visibility + * @param useLetterCommunication The usage of letter communications (can we send letters for this visibility) */ public record Visibility( String campaignId, @@ -20,7 +21,8 @@ public record Visibility( Long identificationPhaseStartDate, Long collectionStartDate, Long collectionEndDate, - Long endDate + Long endDate, + Boolean useLetterCommunication ) { public static Visibility merge(Visibility currentVisibility, Visibility visibilityToUpdate) throws VisibilityHasInvalidDatesException { Long managementStartDate = visibilityToUpdate.managementStartDate() != null ? @@ -35,6 +37,8 @@ public static Visibility merge(Visibility currentVisibility, Visibility visibili visibilityToUpdate.collectionEndDate() : currentVisibility.collectionEndDate(); Long endDate = visibilityToUpdate.endDate() != null ? visibilityToUpdate.endDate() : currentVisibility.endDate(); + Boolean useCommunication = visibilityToUpdate.useLetterCommunication() != null ? + visibilityToUpdate.useLetterCommunication() : currentVisibility.useLetterCommunication(); Visibility updatedVisibility = new Visibility( currentVisibility.campaignId(), @@ -44,7 +48,9 @@ public static Visibility merge(Visibility currentVisibility, Visibility visibili identificationPhaseStartDate, collectionStartDate, collectionEndDate, - endDate); + endDate, + useCommunication + ); if(isValid(updatedVisibility)) { return updatedVisibility; diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java index fe98c865..25d3c5bc 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapter.java @@ -43,7 +43,7 @@ public void updateDates(Visibility visibilityToUpdate) throws VisibilityNotFound visibilityToUpdate.campaignId(), visibilityToUpdate.organizationalUnitId()) .orElseThrow(VisibilityNotFoundException::new); - visibilityDB.updateDates(visibilityToUpdate); + visibilityDB.update(visibilityToUpdate); crudRepository.save(visibilityDB); } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java index f62b5741..eaa1b1db 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java @@ -41,8 +41,9 @@ public class VisibilityDB implements Serializable { private Long collectionStartDate; private Long collectionEndDate; private Long endDate; + private boolean useLetterCommunication; - public void updateDates(Visibility visibilityToUpdate) { + public void update(Visibility visibilityToUpdate) { String ouId = visibilityToUpdate.organizationalUnitId(); String campaignId = visibilityToUpdate.campaignId(); if (visibilityToUpdate.managementStartDate() != null) { @@ -69,6 +70,11 @@ public void updateDates(Visibility visibilityToUpdate) { log.info("Updating end date for campaign {} and Organizational Unit {}", campaignId, ouId); this.setEndDate(visibilityToUpdate.endDate()); } + + if (visibilityToUpdate.useLetterCommunication() != null) { + log.info("Updating letter communication usage for campaign {} and Organizational Unit {}", campaignId, ouId); + this.setUseLetterCommunication(visibilityToUpdate.useLetterCommunication()); + } } public static VisibilityDB fromModel(Visibility visibility, Campaign campaign, OrganizationUnit organizationUnit) { @@ -76,7 +82,7 @@ public static VisibilityDB fromModel(Visibility visibility, Campaign campaign, O return new VisibilityDB(id, organizationUnit, campaign, visibility.managementStartDate(), visibility.interviewerStartDate(), visibility.identificationPhaseStartDate(), - visibility.collectionStartDate(), visibility.collectionEndDate(), visibility.endDate()); + visibility.collectionStartDate(), visibility.collectionEndDate(), visibility.endDate(), visibility.useLetterCommunication()); } public static Visibility toModel(VisibilityDB visibilityDB) { @@ -88,7 +94,8 @@ public static Visibility toModel(VisibilityDB visibilityDB) { visibilityDB.getIdentificationPhaseStartDate(), visibilityDB.getCollectionStartDate(), visibilityDB.getCollectionEndDate(), - visibilityDB.getEndDate()); + visibilityDB.getEndDate(), + visibilityDB.isUseLetterCommunication()); } public static List toModel(List visibilityDBs) { diff --git a/src/main/resources/db/changelog/544_add_letter_communication_visibility.xml b/src/main/resources/db/changelog/544_add_letter_communication_visibility.xml new file mode 100644 index 00000000..f455e352 --- /dev/null +++ b/src/main/resources/db/changelog/544_add_letter_communication_visibility.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/db/dataset/init-demo-data.sql b/src/main/resources/db/dataset/init-demo-data.sql index 08c838b2..10667442 100644 --- a/src/main/resources/db/dataset/init-demo-data.sql +++ b/src/main/resources/db/dataset/init-demo-data.sql @@ -84,7 +84,8 @@ INSERT INTO visibility ( end_date, identification_phase_start_date, interviewer_start_date, - management_start_date + management_start_date, + use_letter_communication ) VALUES ('OU-NORTH', 'SIMPSONS2020X00', EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, @@ -92,7 +93,8 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000), + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true), ('OU-NORTH', 'VQS2021X00', EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, @@ -100,7 +102,8 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000), + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true), ('OU-SOUTH', 'VQS2021X00', EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, @@ -108,7 +111,8 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000), + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true), ('OU-SOUTH', 'SIMPSONS2020X00', EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, @@ -116,7 +120,8 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000), + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true), ('OU-SOUTH', 'ZCLOSEDX00', EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, @@ -124,7 +129,8 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000), + EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, + true), ('OU-WEST', 'ZCLOSEDX00', EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, @@ -132,7 +138,8 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000), + EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, + true), ('OU-SOUTH', 'XCLOSEDX00', EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, @@ -140,7 +147,8 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000); + EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, + true); INSERT INTO communication_information ( organization_unit_id, diff --git a/src/main/resources/db/dataset/reinit-test-data.sql b/src/main/resources/db/dataset/reinit-test-data.sql index 265fb6fe..c86568a2 100644 --- a/src/main/resources/db/dataset/reinit-test-data.sql +++ b/src/main/resources/db/dataset/reinit-test-data.sql @@ -111,15 +111,16 @@ INSERT INTO visibility ( end_date, identification_phase_start_date, interviewer_start_date, - management_start_date + management_start_date, + use_letter_communication ) VALUES - ('OU-NORTH', 'SIMPSONS2020X00',1721903754305, 1719225354304, 1724582154306, 1719138954303, 1719052554302, 1718966154301), - ('OU-SOUTH', 'SIMPSONS2020X00',1721903754315, 1719225354314, 1724582154316, 1719138954310, 1719052554309, 1718966154308), - ('OU-NORTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308), - ('OU-SOUTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308), - ('OU-SOUTH', 'XCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308), - ('OU-SOUTH', 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308), - ('OU-WEST' , 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308); + ('OU-NORTH', 'SIMPSONS2020X00',1721903754305, 1719225354304, 1724582154306, 1719138954303, 1719052554302, 1718966154301, true), + ('OU-SOUTH', 'SIMPSONS2020X00',1721903754315, 1719225354314, 1724582154316, 1719138954310, 1719052554309, 1718966154308, false), + ('OU-NORTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308, true), + ('OU-SOUTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308, true), + ('OU-SOUTH', 'XCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true), + ('OU-SOUTH', 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true), + ('OU-WEST' , 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true); INSERT INTO communication_information ( organization_unit_id, diff --git a/src/main/resources/db/master.xml b/src/main/resources/db/master.xml index 350cfac3..ab155ab2 100644 --- a/src/main/resources/db/master.xml +++ b/src/main/resources/db/master.xml @@ -57,5 +57,6 @@ - + + \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java index 2e1d3ac8..2487bbfe 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java @@ -95,7 +95,7 @@ void testCreateCampaign03() throws Exception { void testCreateCampaign04() throws Exception { VisibilityCampaignCreateDto visibility = generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L); + 1721683253000L, 1721683254000L, 1721683255000L, true); CampaignCreateDto campaign1 = generateCampaign(" ", "An other campaign", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, @@ -128,19 +128,25 @@ void testCreateCampaign04() throws Exception { void testCreateCampaign05() throws Exception { List invalidVisibilities = new ArrayList<>(Arrays.asList( generateVisibility(" ", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L), + 1721683253000L, 1721683254000L, 1721683255000L, true), generateVisibility("OU-NORTH", null, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L), + 1721683253000L, 1721683254000L, 1721683255000L, true), generateVisibility("OU-NORTH", 1721683250000L, null, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L), + 1721683253000L, 1721683254000L, 1721683255000L, true), generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, null, - 1721683253000L, 1721683254000L, 1721683255000L), + 1721683253000L, 1721683254000L, 1721683255000L, true), generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, - null, 1721683254000L, 1721683255000L), + null, 1721683254000L, 1721683255000L, true), generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, null, 1721683255000L), + 1721683253000L, null, 1721683255000L, true), generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, null) + 1721683253000L, 1721683254000L, null, true), + generateVisibility("OU-NORTH", 1721683250000L, + 1721683251000L, + 1721683252000L, + 1721683253000L, + 1721683254000L, + 1721683255000L, null) )); invalidVisibilities.add(null); @@ -183,7 +189,7 @@ void testCreateCampaign06() throws Exception { @DisplayName("Should return conflict when duplicate medium/type on communication configurations") void testCreateCampaign07() throws Exception { VisibilityCampaignCreateDto visibility = generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L); + 1721683253000L, 1721683254000L, 1721683255000L, true); CommunicationTemplateCreateDto communicationTemplate = new CommunicationTemplateCreateDto("messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); CommunicationTemplateCreateDto duplicatedCommunicationTemplate = new CommunicationTemplateCreateDto("messhId2", CommunicationMedium.EMAIL, CommunicationType.NOTICE); @@ -213,13 +219,13 @@ public CampaignCreateDto generateDefaultCampaign() { 1721683252000L, 1721683253000L, 1721683254000L, - 1721683255000L); + 1721683255000L, true); VisibilityCampaignCreateDto secondVisibility = generateVisibility("OU-SOUTH", 1721683260L, 1721683261000L, 1721683262000L, 1721683263000L, 1721683264000L, - 1721683265000L); + 1721683265000L, true); CommunicationInformationCampaignCreateDto communicationInformation = new CommunicationInformationCampaignCreateDto("OU-SOUTH", "mail", "tel"); @@ -260,8 +266,8 @@ private CampaignCreateDto generateCampaign( private VisibilityCampaignCreateDto generateVisibility(String organizationalUnit, Long managementDate, Long interviewerDate, Long identificationDate, Long collectionStartDate, - Long collectionEndDate, Long endDate) { + Long collectionEndDate, Long endDate, Boolean useLetterCommunication) { return new VisibilityCampaignCreateDto(managementDate, - interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit); + interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit, useLetterCommunication); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java index 4ce2fd2a..a1a390b2 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java @@ -90,7 +90,7 @@ void testUpdateCampaign03() throws Exception { VisibilityCampaignUpdateDto visibility = generateVisibility(" ", 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, 1721683254000L, - 1721683255000L); + 1721683255000L, true); testUpdateExceptions(visibility, HttpStatus.BAD_REQUEST, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE); } @@ -114,7 +114,7 @@ void testUpdateCampaign06() throws Exception { VisibilityCampaignUpdateDto visibility = generateVisibility("ou-id", null, null, null, null, - null, null); + null, null, true); testUpdateExceptions(visibility, HttpStatus.BAD_REQUEST, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE); } @@ -155,7 +155,8 @@ private CampaignUpdateDto generateDefaultCampaign() { 1721683262000L, 1721683263000L, 1721683264000L, - 1721683265000L); + 1721683265000L, + true); CommunicationInformationCampaignUpdateDto firstCommunication = generateCommunicationInformation("OU-SOUTH", "mail", @@ -197,14 +198,15 @@ private CampaignUpdateDto generateCampaign(String campaignLabel, private VisibilityCampaignUpdateDto generateDefaultVisibility() { return generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, - 1721683254000L, 1721683255000L); + 1721683254000L, 1721683255000L, true); } private VisibilityCampaignUpdateDto generateVisibility( String organizationalUnit, Long managementDate, Long interviewerDate, Long identificationDate, - Long collectionStartDate, Long collectionEndDate, Long endDate) { + Long collectionStartDate, Long collectionEndDate, Long endDate, Boolean useLetterCommunication) { return new VisibilityCampaignUpdateDto(managementDate, - interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit); + interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, + organizationalUnit, useLetterCommunication); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java index 8a2fd84e..9466ed44 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java @@ -56,11 +56,11 @@ void testGetVisibilities01() throws Exception { Visibility visibility1 = new Visibility(campaignId, organizationalUnitId, 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L); + 1721683253000L, 1721683254000L, 1721683255000L, true); Visibility visibility2 = new Visibility(campaignId, "ou-id2", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L); + 1721683253000L, 1721683254000L, 1721683255000L, true); List visibilities = List.of(visibility1, visibility2); visibilityService.save(visibility1); visibilityService.save(visibility2); @@ -95,7 +95,7 @@ void testUpdateVisibility01() throws Exception { Visibility visibility = new Visibility(campaignId, organizationalUnitId, 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L); + 1721683253000L, 1721683254000L, 1721683255000L, true); visibilityService.save(visibility); VisibilityUpdateDto visibilityToUpdate = generateUpdateVisibility(); @@ -158,6 +158,6 @@ private VisibilityUpdateDto generateUpdateVisibility( Long identificationDate, Long collectionStartDate, Long collectionEndDate, Long endDate) { return new VisibilityUpdateDto(managementDate, - interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate); + interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, true); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java index 282228b3..75a127dc 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java @@ -25,7 +25,7 @@ void testToModel() { VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto( managementStartDate, interviewerStartDate, identificationPhaseStartDate, - collectionStartDate, collectionEndDate, endDate, organizationalUnit); + collectionStartDate, collectionEndDate, endDate, organizationalUnit, true); // When Visibility visibility = VisibilityCampaignCreateDto @@ -41,5 +41,6 @@ void testToModel() { assertThat(visibility.collectionStartDate()).isEqualTo(collectionStartDate); assertThat(visibility.collectionEndDate()).isEqualTo(collectionEndDate); assertThat(visibility.endDate()).isEqualTo(endDate); + assertThat(visibility.useLetterCommunication()).isTrue(); } } \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java index 87e17cd1..d1ec8b48 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java @@ -15,8 +15,8 @@ class VisibilityCampaignUpdateDtoTest { void testToModel() { // Given String campaignId = "campaign1"; - VisibilityCampaignUpdateDto dto1 = new VisibilityCampaignUpdateDto(1L, 2L, 3L, 4L, 5L, 6L, "OU1"); - VisibilityCampaignUpdateDto dto2 = new VisibilityCampaignUpdateDto(11L, 12L, 13L, 14L, 15L, 16L, "OU2"); + VisibilityCampaignUpdateDto dto1 = new VisibilityCampaignUpdateDto(1L, 2L, 3L, 4L, 5L, 6L, "OU1", true); + VisibilityCampaignUpdateDto dto2 = new VisibilityCampaignUpdateDto(11L, 12L, 13L, 14L, 15L, 16L, "OU2", null); List dtoList = List.of(dto1, dto2); // When @@ -34,6 +34,7 @@ void testToModel() { assertThat(firstVisibility.collectionStartDate()).isEqualTo(4L); assertThat(firstVisibility.collectionEndDate()).isEqualTo(5L); assertThat(firstVisibility.endDate()).isEqualTo(6L); + assertThat(firstVisibility.useLetterCommunication()).isTrue(); Visibility lastVisibility = modelList.getLast(); assertThat(lastVisibility.campaignId()).isEqualTo(campaignId); @@ -44,5 +45,6 @@ void testToModel() { assertThat(lastVisibility.collectionStartDate()).isEqualTo(14L); assertThat(lastVisibility.collectionEndDate()).isEqualTo(15L); assertThat(lastVisibility.endDate()).isEqualTo(16L); + assertThat(lastVisibility.useLetterCommunication()).isNull(); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java index 9675697a..f1b722aa 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java @@ -23,7 +23,7 @@ void testToModel() { VisibilityUpdateDto dto = new VisibilityUpdateDto( managementStartDate, interviewerStartDate, identificationPhaseStartDate, - collectionStartDate, collectionEndDate, endDate); + collectionStartDate, collectionEndDate, endDate, true); // When Visibility model = VisibilityUpdateDto.toModel(dto, campaignId, ouId); diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java index 3a9f3d8e..daf62bde 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java @@ -14,8 +14,8 @@ class VisibilityCampaignDtoTest { @DisplayName("Should return dto objects from models") void testFromModel() { // Given - Visibility visibility1 = new Visibility("campaign-id", "OU1", 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); - Visibility visibility2 = new Visibility("campaign-id", "OU2", 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + Visibility visibility1 = new Visibility("campaign-id", "OU1", 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); + Visibility visibility2 = new Visibility("campaign-id", "OU2", 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); List visibilityList = List.of(visibility1, visibility2); // When diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java index e8ca73c9..15937001 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java @@ -16,10 +16,10 @@ class VisibilityTest { void testMergeAndDateValidation() throws VisibilityHasInvalidDatesException { // Given Visibility currentVisibility = new Visibility("campaign1", "OU1", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); Visibility updateVisibility = new Visibility("campaign1", "OU1", - 1617933000000L, 1627933000000L, 1627934000000L, 1627935000000L, 1627936000000L, 1628277601000L); + 1617933000000L, 1627933000000L, 1627934000000L, 1627935000000L, 1627936000000L, 1628277601000L, false); // When Visibility mergedVisibility = Visibility.merge(currentVisibility, updateVisibility); @@ -33,17 +33,18 @@ void testMergeAndDateValidation() throws VisibilityHasInvalidDatesException { assertThat(mergedVisibility.collectionStartDate()).isEqualTo(1627935000000L); assertThat(mergedVisibility.collectionEndDate()).isEqualTo(1627936000000L); assertThat(mergedVisibility.endDate()).isEqualTo(1628277601000L); + assertThat(mergedVisibility.useLetterCommunication()).isFalse(); } @Test - @DisplayName("Should merge 2 visibilities and keep original dates when updated dates are null") - void testMergeNullDates() throws VisibilityHasInvalidDatesException { + @DisplayName("Should merge 2 visibilities and keep original values when updated values are null") + void testMergeNull() throws VisibilityHasInvalidDatesException { // Given Visibility currentVisibility = new Visibility("campaign1", "OU1", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); Visibility updateVisibility = new Visibility("campaign1", "OU1", - null, null, null, null, null, null); + null, null, null, null, null, null, null); // When Visibility mergedVisibility = Visibility.merge(currentVisibility, updateVisibility); @@ -64,10 +65,10 @@ void testMergeNullDates() throws VisibilityHasInvalidDatesException { void testMergeThrowsExceptionForInvalidDates() { // Given Visibility currentVisibility = new Visibility("campaign1", "OU1", - 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); Visibility updateVisibility = new Visibility("campaign1", "OU1", - 1227845600000L, 1327932000001L, 1327932000002L, 1327932000003L, 1327932000004L, 1327932000004L); + 1227845600000L, 1327932000001L, 1327932000002L, 1327932000003L, 1327932000004L, 1327932000004L, true); // When & Then assertThatThrownBy(() -> Visibility.merge(currentVisibility, updateVisibility)) @@ -87,12 +88,12 @@ void testMergeThrowsExceptionForInvalidDates() { void testMergeThrowsExceptionForInvalidDates2(String managementStartDate, String interviwerStartDate, String identificationPhaseStartDate, String collectionStartDate, String collectionEndDate, String endDate) { // Given Visibility currentVisibility = new Visibility("campaign1", "OU1", - 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); Visibility updateVisibility = new Visibility("campaign1", "OU1", getLong(managementStartDate), getLong(interviwerStartDate), getLong(identificationPhaseStartDate), getLong(collectionStartDate), - getLong(collectionEndDate), getLong(endDate)); + getLong(collectionEndDate), getLong(endDate), true); // When & Then assertThatThrownBy(() -> Visibility.merge(currentVisibility, updateVisibility)) diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java index cb2cf90b..83ae7584 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java @@ -46,11 +46,11 @@ class CampaignServiceImplTest { private final Visibility existingVisibility1 = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L); + 1721683253000L, 1721683254000L, 1721683255000L, true); private final Visibility existingVisibility2 = new Visibility(existingCampaign.getId(), "OU2", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L); + 1721683253000L, 1721683254000L, 1721683255000L, true); @BeforeEach void setup() { @@ -96,7 +96,7 @@ void shouldCreateNewCampaign() throws CampaignAlreadyExistException, Organizatio CommunicationTemplateCreateDto communicationTemplateDto = new CommunicationTemplateCreateDto("meshuggahId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto(1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId()); + 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId(), true); CampaignCreateDto campaignCreateDto = new CampaignCreateDto( campaignId, "Campaign 1", @@ -135,7 +135,7 @@ void shouldCreateNewCampaign() throws CampaignAlreadyExistException, Organizatio void shouldThrowCampaignAlreadyExistExceptionWhenCreatingExistingCampaign() { String campaignId = existingCampaign.getId(); VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto(1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId()); + 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId(), true); CampaignCreateDto existingCampaignDto = new CampaignCreateDto( campaignId, "Existing campaign", @@ -162,7 +162,7 @@ void shouldUpdateExistingCampaign() throws CampaignNotFoundException, Visibility // Given VisibilityCampaignUpdateDto visibilityDto = new VisibilityCampaignUpdateDto(1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId()); + 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId(), true); CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", List.of(visibilityDto), @@ -287,11 +287,11 @@ void shouldReturnTrueIfCampaignIsOngoing() throws CampaignNotFoundException { Visibility ongoingVisibility = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, - 1628191200000L, Instant.now().plusSeconds(10000).toEpochMilli()); + 1628191200000L, Instant.now().plusSeconds(10000).toEpochMilli(), true); Visibility closedVisibility = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, - 1628191200000L, Instant.now().toEpochMilli()); + 1628191200000L, Instant.now().toEpochMilli(), true); visibilityService.save(ongoingVisibility); visibilityService.save(closedVisibility); @@ -306,11 +306,11 @@ void shouldReturnFalseIfCampaignIsNotOngoing() throws CampaignNotFoundException Visibility closedVisibility1 = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, - 1628191200000L, Instant.now().minusSeconds(3600).toEpochMilli()); + 1628191200000L, Instant.now().minusSeconds(3600).toEpochMilli(), true); Visibility closedVisibility2 = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, - 1628191200000L, Instant.now().toEpochMilli()); + 1628191200000L, Instant.now().toEpochMilli(), true); visibilityService.save(closedVisibility1); visibilityService.save(closedVisibility2); diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java index 0d3b4327..f1481aea 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java @@ -26,11 +26,11 @@ void setUp() { visibilityRepository = new VisibilityFakeRepository(); visibilityService = new VisibilityServiceImpl(visibilityRepository); visibility1 = new Visibility("campaign1", "OU1", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); visibility2 = new Visibility("campaign2", "OU2", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); visibility3 = new Visibility("campaign1", "OU2", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); visibilityRepository.save(visibility1); visibilityRepository.save(visibility2); visibilityRepository.save(visibility3); @@ -51,7 +51,8 @@ void shouldReturnVisibilitiesForValidCampaignId() { @DisplayName("Should update visibility with valid data") void shouldUpdateVisibilityWithValidData() throws VisibilityNotFoundException, VisibilityHasInvalidDatesException { Visibility visibilityToUpdate = new Visibility(visibility1.campaignId(), visibility1.organizationalUnitId(), - 1627845600001L, 1627932000001L, 1628018400001L, 1628104800001L, 1628191200001L, 1628277600001L); + 1627845600001L, 1627932000001L, 1628018400001L, + 1628104800001L, 1628191200001L, 1628277600001L, false); visibilityService.updateVisibility(visibilityToUpdate); @@ -66,7 +67,7 @@ void shouldUpdateVisibilityWithValidData() throws VisibilityNotFoundException, V void shouldThrowVisibilityNotFoundExceptionIfVisibilityToUpdateDoesNotExist() { Visibility visibilityToUpdate = new Visibility("invalid-campaign", "invalid-ou", 1627845600000L, 1627932000000L, 1628018400000L, - 1628104800000L, 1628191200000L, 1628277600000L); + 1628104800000L, 1628191200000L, 1628277600000L, true); assertThatThrownBy(() -> visibilityService.updateVisibility(visibilityToUpdate)) .isInstanceOf(VisibilityNotFoundException.class) diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java index 621f84a6..32fb6c53 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java @@ -50,7 +50,7 @@ public void updateDates(Visibility visibilityToUpdate) throws VisibilityNotFound @Override public Visibility getVisibilityBySurveyUnitId(String surveyUnitId) { return new Visibility("campaign1", "OU1", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L); + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); } // Additional methods for testing purposes diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java index 8effe521..52e802f0 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java @@ -69,10 +69,10 @@ void setup() { organizationUnit2 = organizationUnitRepository.save(organizationUnit2); visibilityDB1 = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 10L, 20L, - 11L, 30L, 12L, 40L); + 11L, 30L, 12L, 40L, true); visibilityDB2 = new VisibilityDB(new VisibilityDBId(organizationUnit2.getId(), campaign.getId()), organizationUnit2, campaign, 11L, 12L, - 13L, 14L, 15L, 16L); + 13L, 14L, 15L, 16L, true); List visibilities = new ArrayList<>(); visibilities.add(visibilityDB1); visibilities.add(visibilityDB2); @@ -85,7 +85,7 @@ void setup() { void testUpdateDatesVisibilities01() throws VisibilityNotFoundException { Visibility visibilityToUpdate = new Visibility(campaign.getId(), organizationUnit.getId(), 21L, 22L, 23L, - 24L, 25L, 26L); + 24L, 25L, 26L, true); visibilityDaoAdapter.updateDates(visibilityToUpdate); Optional campaignOptional = campaignRepository.findById(campaign.getId()); @@ -109,7 +109,7 @@ void testUpdateDatesVisibilities01() throws VisibilityNotFoundException { void testUpdateDatesVisibility02() { Visibility visibilityToUpdate = new Visibility(campaign.getId(), "invalid-id", 21L, 22L, 23L, - 24L, 25L, 26L); + 24L, 25L, 26L, true); assertThatThrownBy(() -> visibilityDaoAdapter.updateDates(visibilityToUpdate)) .isInstanceOf(VisibilityNotFoundException.class) diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java index ab45ff9f..7bbbd03f 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java @@ -25,7 +25,7 @@ void setup() { void testToModel01() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L); + 3L, 4L, 5L, 6L, true); Visibility visibility = VisibilityDB.toModel(visibilityDB); assertThat(visibility.campaignId()).isEqualTo(visibilityDB.getVisibilityId().getCampaignId()); @@ -36,13 +36,14 @@ void testToModel01() { assertThat(visibility.collectionStartDate()).isEqualTo(visibilityDB.getCollectionStartDate()); assertThat(visibility.collectionEndDate()).isEqualTo(visibilityDB.getCollectionEndDate()); assertThat(visibility.endDate()).isEqualTo(visibilityDB.getEndDate()); + assertThat(visibility.useLetterCommunication().booleanValue()).isEqualTo(visibilityDB.isUseLetterCommunication()); } @Test @DisplayName("Should return entity object") void testFromModel01() { Visibility visibility = generateVisibility(1L, 2L, 3L, - 4L, 5L, 6L); + 4L, 5L, 6L, true); VisibilityDB visibilityDB = VisibilityDB.fromModel(visibility, campaign, organizationUnit); assertThat(visibilityDB.getVisibilityId().getCampaignId()).isEqualTo(visibility.campaignId()); @@ -55,72 +56,76 @@ void testFromModel01() { assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibility.collectionStartDate()); assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibility.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isEqualTo(visibility.endDate()); + assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibility.useLetterCommunication().booleanValue()); } @Test @DisplayName("Should update dates from entity object") - void testUpdateDates01() { + void testUpdate01() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L); + 3L, 4L, 5L, 6L, true); Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, - 14L, 15L, 16L); + 14L, 15L, 16L, false); - visibilityDB.updateDates(visibilityToUpdate); + visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibilityToUpdate.useLetterCommunication().booleanValue()); } @Test @DisplayName("Should not update management start date") - void testUpdateDates02() { + void testUpdate02() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L); + 3L, 4L, 5L, 6L, true); Visibility visibilityToUpdate = generateVisibility(null, 12L, 13L, - 14L, 15L, 16L); + 14L, 15L, 16L, true); - visibilityDB.updateDates(visibilityToUpdate); + visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isNotNull(); assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibilityToUpdate.useLetterCommunication().booleanValue()); } @Test @DisplayName("Should not update interviewer start date") - void testUpdateDates03() { + void testUpdate03() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L); + 3L, 4L, 5L, 6L, true); Visibility visibilityToUpdate = generateVisibility(11L, null, 13L, - 14L, 15L, 16L); + 14L, 15L, 16L, true); - visibilityDB.updateDates(visibilityToUpdate); + visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); assertThat(visibilityDB.getInterviewerStartDate()).isNotNull(); assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibilityToUpdate.useLetterCommunication().booleanValue()); } @Test @DisplayName("Should not update identification start date") - void testUpdateDates04() { + void testUpdate04() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L); + 3L, 4L, 5L, 6L, true); Visibility visibilityToUpdate = generateVisibility(11L, 12L, null, - 14L, 15L, 16L); + 14L, 15L, 16L, true); - visibilityDB.updateDates(visibilityToUpdate); + visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); assertThat(visibilityDB.getIdentificationPhaseStartDate()).isNotNull(); @@ -131,14 +136,14 @@ void testUpdateDates04() { @Test @DisplayName("Should not update collection start date") - void testUpdateDates05() { + void testUpdate05() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L); + 3L, 4L, 5L, 6L, true); Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, - null, 15L, 16L); + null, 15L, 16L, true); - visibilityDB.updateDates(visibilityToUpdate); + visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); @@ -149,44 +154,65 @@ void testUpdateDates05() { @Test @DisplayName("Should not update collection end date") - void testUpdateDates06() { + void testUpdate06() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L); + 3L, 4L, 5L, 6L, true); Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, - 14L, null, 16L); + 14L, null, 16L, true); - visibilityDB.updateDates(visibilityToUpdate); + visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); assertThat(visibilityDB.getCollectionEndDate()).isNotNull(); assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibilityToUpdate.useLetterCommunication().booleanValue()); } @Test @DisplayName("Should not update end date") - void testUpdateDates07() { + void testUpdate07() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L); + 3L, 4L, 5L, 6L, true); Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, - 14L, 15L, null); + 14L, 15L, null, true); - visibilityDB.updateDates(visibilityToUpdate); + visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isNotNull(); + assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibilityToUpdate.useLetterCommunication().booleanValue()); + } + + @Test + @DisplayName("Should not update communication usage") + void testUpdate08() { + VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, + 1L, 2L, + 3L, 4L, 5L, 6L, false); + Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, + 14L, 15L, null, null); + + visibilityDB.update(visibilityToUpdate); + assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); + assertThat(visibilityDB.getInterviewerStartDate()).isEqualTo(visibilityToUpdate.interviewerStartDate()); + assertThat(visibilityDB.getIdentificationPhaseStartDate()).isEqualTo(visibilityToUpdate.identificationPhaseStartDate()); + assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); + assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); + assertThat(visibilityDB.getEndDate()).isNotNull(); + assertThat(visibilityDB.isUseLetterCommunication()).isFalse(); } private Visibility generateVisibility(Long managementStartDate, Long interviewerStartDate, Long identificationPhaseStartDate, - Long collectionStartDate, Long collectionEndDate, Long endDate) { + Long collectionStartDate, Long collectionEndDate, Long endDate, Boolean useCommunication) { return new Visibility(campaign.getId(), organizationUnit.getId(), managementStartDate, interviewerStartDate, - identificationPhaseStartDate, collectionStartDate, collectionEndDate, endDate); + identificationPhaseStartDate, collectionStartDate, collectionEndDate, endDate, useCommunication); } } diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index 7a0691b9..b9a16bbf 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -68,7 +68,8 @@ void testGetCampaign() throws Exception { "identificationPhaseStartDate":1719138954303, "collectionStartDate":1719225354304, "collectionEndDate":1721903754305, - "endDate":1724582154306 + "endDate":1724582154306, + "useLetterCommunication": true }, { "organizationalUnit":"OU-SOUTH", @@ -77,7 +78,8 @@ void testGetCampaign() throws Exception { "identificationPhaseStartDate":1719138954310, "collectionStartDate":1719225354314, "collectionEndDate":1721903754315, - "endDate":1724582154316 + "endDate":1724582154316, + "useLetterCommunication": false } ], "communicationInformations":[ @@ -121,7 +123,8 @@ void testCreateCampaign() throws Exception { "collectionStartDate":1721683253000, "collectionEndDate":1721683254000, "endDate":1721683255000, - "organizationalUnit":"OU-NORTH" + "organizationalUnit":"OU-NORTH", + "useLetterCommunication": true }, { "managementStartDate":1721683260000, @@ -130,7 +133,8 @@ void testCreateCampaign() throws Exception { "collectionStartDate":1721683263000, "collectionEndDate":1721683264000, "endDate":1721683265000, - "organizationalUnit":"OU-SOUTH" + "organizationalUnit":"OU-SOUTH", + "useLetterCommunication": false } ], "referents":[ @@ -198,10 +202,10 @@ void testCreateCampaign() throws Exception { assertThat(campaignCreated.getVisibilities()) .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L)) + 1721683253000L, 1721683254000L, 1721683255000L, true)) .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-SOUTH", 1721683260000L, 1721683261000L, 1721683262000L, - 1721683263000L, 1721683264000L, 1721683265000L)); + 1721683263000L, 1721683264000L, 1721683265000L, false)); assertThat(campaignCreated.getCommunicationTemplates()).hasSize(3); assertThat(campaignCreated.getCommunicationTemplates()) @@ -270,7 +274,8 @@ void testUpdateCampaign() throws Exception { "collectionStartDate":1721683253000, "collectionEndDate":1721683254000, "endDate":1721683255000, - "organizationalUnit":"OU-NORTH" + "organizationalUnit":"OU-NORTH", + "useLetterCommunication": false }, { "managementStartDate":1721683260000, @@ -279,7 +284,8 @@ void testUpdateCampaign() throws Exception { "collectionStartDate":1721683263000, "collectionEndDate":1721683264000, "endDate":1721683265000, - "organizationalUnit":"OU-SOUTH" + "organizationalUnit":"OU-SOUTH", + "useLetterCommunication": true } ], "communicationInformations": [ @@ -332,11 +338,11 @@ void testUpdateCampaign() throws Exception { .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, - 1721683254000L, 1721683255000L)) + 1721683254000L, 1721683255000L, false)) .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-SOUTH", 1721683260000L, 1721683261000L, 1721683262000L, 1721683263000L, - 1721683264000L, 1721683265000L)); + 1721683264000L, 1721683265000L, true)); assertThat(campaignUpdated.getCommunicationInformations()).hasSize(2); assertThat(campaignUpdated.getCommunicationInformations()) .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, @@ -376,7 +382,7 @@ void testDeleteCampaign() throws Exception { private void assertVisibility(VisibilityDB visibilityToCheck, String campaignId, String organizationUnitId, long managementStartDate, long interviewerStartDate, long identificationPhaseStartDate, long collectionStartDate, - long collectionEndDate, long endDate) { + long collectionEndDate, long endDate, boolean useLetterCommunication) { assertThat(visibilityToCheck.getCampaign().getId()).isEqualTo(campaignId); assertThat(visibilityToCheck.getOrganizationUnit().getId()).isEqualTo(organizationUnitId); assertThat(visibilityToCheck.getManagementStartDate()).isEqualTo(managementStartDate); @@ -385,6 +391,7 @@ private void assertVisibility(VisibilityDB visibilityToCheck, String campaignId, assertThat(visibilityToCheck.getCollectionStartDate()).isEqualTo(collectionStartDate); assertThat(visibilityToCheck.getCollectionEndDate()).isEqualTo(collectionEndDate); assertThat(visibilityToCheck.getEndDate()).isEqualTo(endDate); + assertThat(visibilityToCheck.isUseLetterCommunication()).isEqualTo(useLetterCommunication); } private void assertReferent(Referent referentToCheck, String campaignId, String role, String lastName, diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java index 02a42360..594889bd 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java @@ -60,7 +60,8 @@ void testGetVisibilities() throws Exception { "identificationPhaseStartDate":1719138954303, "collectionStartDate":1719225354304, "collectionEndDate":1721903754305, - "endDate":1724582154306 + "endDate":1724582154306, + "useLetterCommunication": true }, { "organizationalUnit":"OU-SOUTH", @@ -69,7 +70,8 @@ void testGetVisibilities() throws Exception { "identificationPhaseStartDate":1719138954310, "collectionStartDate":1719225354314, "collectionEndDate":1721903754315, - "endDate":1724582154316 + "endDate":1724582154316, + "useLetterCommunication": false } ] """; @@ -90,7 +92,8 @@ void testUpdateVisibility() throws Exception { "identificationPhaseStartDate":1719138954308, "collectionStartDate":null, "collectionEndDate":1921903754308, - "endDate":2024582154308 + "endDate":2024582154308, + "useLetterCommunication": true }"""; mockMvc.perform(put(updatePath) @@ -109,5 +112,6 @@ void testUpdateVisibility() throws Exception { assertThat(visibilityDBToCheck.getCollectionStartDate()).isEqualTo(1719225354304L); assertThat(visibilityDBToCheck.getCollectionEndDate()).isEqualTo(1921903754308L); assertThat(visibilityDBToCheck.getEndDate()).isEqualTo(2024582154308L); + assertThat(visibilityDBToCheck.isUseLetterCommunication()).isTrue(); } } From c886a1bd041264553156e66fcf557a2bf0c7858b Mon Sep 17 00:00:00 2001 From: davdarras Date: Wed, 11 Sep 2024 19:27:43 +0200 Subject: [PATCH 43/48] fix: create cancelled com requests when letter communication not allowed --- pom.xml | 2 +- .../impl/SurveyUnitUpdateServiceImpl.java | 57 +++++++++++- .../exception/ExceptionControllerAdvice.java | 5 ++ .../CommunicationTemplateRepository.java | 11 ++- .../port/userside/VisibilityService.java | 9 ++ .../service/VisibilityServiceImpl.java | 6 ++ .../VisibilityNotFoundException.java | 2 +- .../communication/CommunicationRequest.java | 15 ++++ .../CommunicationTemplateDaoAdapter.java | 8 ++ .../entity/CommunicationTemplateDB.java | 8 +- ...5_add_letter_communication_visibility.xml} | 2 +- src/main/resources/db/master.xml | 2 +- .../dummy/VisibilityFakeService.java | 12 +++ .../model/CommunicationRequestTest.java | 20 ++--- .../SurveyUnitUpdateServiceImplTest.java | 89 +++++++++++++++++-- .../CommunicationTemplateFakeRepository.java | 33 +++++++ .../integration/surveyunit/SurveyUnitIT.java | 86 +++++++++++++++++- 17 files changed, 337 insertions(+), 30 deletions(-) rename src/main/resources/db/changelog/{544_add_letter_communication_visibility.xml => 545_add_letter_communication_visibility.xml} (95%) create mode 100644 src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationTemplateFakeRepository.java diff --git a/pom.xml b/pom.xml index 707cf2ed..0556badb 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ fr.insee.pearljam pearljam-back-office - 5.1.3 + 5.1.4 Pearl-Jam-Back-Office Back-office services for PearlJam diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java index bdc5df97..ac84ea3c 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java @@ -6,6 +6,13 @@ import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.domain.campaign.port.userside.DateService; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.port.serverside.CommunicationTemplateRepository; +import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; +import fr.insee.pearljam.domain.exception.CommunicationTemplateNotFoundException; +import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; import fr.insee.pearljam.domain.surveyunit.model.Comment; import fr.insee.pearljam.domain.surveyunit.model.Identification; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; @@ -25,6 +32,8 @@ public class SurveyUnitUpdateServiceImpl implements SurveyUnitUpdateService { private final CommunicationRequestRepository communicationRequestRepository; + private final CommunicationTemplateRepository communicationTemplateRepository; + private final VisibilityService visibilityService; private final DateService dateService; @Transactional @@ -39,11 +48,57 @@ public void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitUpdateDto sur } if(surveyUnitUpdateDto.communicationRequests() != null) { Long timestamp = dateService.getCurrentTimestamp(); - List communicationRequestsToCreate = CommunicationRequestCreateDto.toModel(surveyUnitUpdateDto.communicationRequests(), timestamp); + List communicationRequestsToCreate = + surveyUnitUpdateDto.communicationRequests() + .stream() + .map(communicationRequestCreateDto -> getNewCommunicationRequest(communicationRequestCreateDto, surveyUnit, timestamp)) + .toList(); communicationRequestRepository.addCommunicationRequests(surveyUnit, communicationRequestsToCreate); } Identification identification = IdentificationDto.toModel(surveyUnitUpdateDto.identification()); surveyUnit.updateIdentification(identification); } + + /** + * This method checks the validity of a communication request + * @param communicationRequestToCreate communication request to create + * @param surveyUnit the survey unit to update + * @return a new communication request + */ + private CommunicationRequest getNewCommunicationRequest(CommunicationRequestCreateDto communicationRequestToCreate, SurveyUnit surveyUnit, Long readyTimestamp) { + String campaignId = surveyUnit.getCampaign().getId(); + CommunicationTemplate communicationTemplate = communicationTemplateRepository + .findCommunicationTemplate(communicationRequestToCreate.communicationTemplateId(), campaignId) + .orElseThrow(CommunicationTemplateNotFoundException::new); + + if(!communicationTemplate.medium().equals(CommunicationMedium.LETTER)) { + return CommunicationRequest.create( + communicationRequestToCreate.communicationTemplateId(), + communicationRequestToCreate.creationTimestamp(), + readyTimestamp, + communicationRequestToCreate.reason()); + } + + Visibility visibility = visibilityService + .findVisibility(campaignId, surveyUnit.getOrganizationUnit().getId()) + .orElseThrow(VisibilityNotFoundException::new); + + + if(visibility.useLetterCommunication() != null && visibility.useLetterCommunication()) { + return CommunicationRequest.create( + communicationRequestToCreate.communicationTemplateId(), + communicationRequestToCreate.creationTimestamp(), + readyTimestamp, + communicationRequestToCreate.reason()); + } + + // if the communication request is a letter communication request, but the visibility doesn't admit it, + // create a cancelled communication request + return CommunicationRequest.createCancelled( + communicationRequestToCreate.communicationTemplateId(), + communicationRequestToCreate.creationTimestamp(), + dateService.getCurrentTimestamp(), + communicationRequestToCreate.reason()); + } } diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java index d23ded74..9c5a06cd 100644 --- a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java +++ b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java @@ -140,6 +140,11 @@ public ResponseEntity exceptions(CommunicationInformationNotFoundExcep return generateResponseError(e, HttpStatus.NOT_FOUND, request); } + @ExceptionHandler(VisibilityNotFoundException.class) + public ResponseEntity exceptions(VisibilityNotFoundException e, WebRequest request) { + return generateResponseError(e, HttpStatus.NOT_FOUND, request); + } + @ExceptionHandler(VisibilityHasInvalidDatesException.class) public ResponseEntity exceptions(VisibilityHasInvalidDatesException e, WebRequest request) { return generateResponseError(e, HttpStatus.CONFLICT, request); diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java index 7e32604c..a40f712e 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java @@ -2,13 +2,22 @@ import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import java.util.Optional; import java.util.List; public interface CommunicationTemplateRepository { + /** + * + * @param communicationTemplateId communication template id + * @param campaignId campaign id + * @return the communication template + */ + Optional findCommunicationTemplate(Long communicationTemplateId, String campaignId); + /** * * @param campaignId campaign id * @return list of communication templates for a campaign */ List findCommunicationTemplates(String campaignId); -} \ No newline at end of file +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/VisibilityService.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/VisibilityService.java index 9b5c9f9f..13363953 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/VisibilityService.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/VisibilityService.java @@ -7,6 +7,7 @@ import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; import java.util.List; +import java.util.Optional; public interface VisibilityService { @@ -35,4 +36,12 @@ public interface VisibilityService { * @return the campaign visibility */ CampaignVisibility getCampaignVisibility(String idCampaign, List ouIds); + + /** + * + * @param campaignId campaign id + * @param organizationalUnitId ou id + * @return the visibility for the campaign/ou + */ + Optional findVisibility(String campaignId, String organizationalUnitId); } diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java b/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java index 47949087..d1a394bd 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImpl.java @@ -12,6 +12,7 @@ import org.springframework.transaction.annotation.Transactional; import java.util.List; +import java.util.Optional; @Service @RequiredArgsConstructor @@ -21,6 +22,11 @@ public class VisibilityServiceImpl implements VisibilityService { private final VisibilityRepository visibilityRepository; + @Override + public Optional findVisibility(String campaignId, String organizationalUnitId) { + return visibilityRepository.findVisibility(campaignId, organizationalUnitId); + } + @Override public List findVisibilities(String campaignId) { return visibilityRepository.findVisibilities(campaignId); diff --git a/src/main/java/fr/insee/pearljam/domain/exception/VisibilityNotFoundException.java b/src/main/java/fr/insee/pearljam/domain/exception/VisibilityNotFoundException.java index bbbb7285..8943c1de 100644 --- a/src/main/java/fr/insee/pearljam/domain/exception/VisibilityNotFoundException.java +++ b/src/main/java/fr/insee/pearljam/domain/exception/VisibilityNotFoundException.java @@ -1,6 +1,6 @@ package fr.insee.pearljam.domain.exception; -public class VisibilityNotFoundException extends EntityNotFoundException { +public class VisibilityNotFoundException extends RuntimeException { public static final String MESSAGE = "Visibility not found"; diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java index 548c853c..89479e78 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java @@ -24,4 +24,19 @@ public static CommunicationRequest create(Long communicationTemplateId, Long cre status.add(CommunicationRequestStatus.create(readyTimestamp, CommunicationStatusType.READY)); return new CommunicationRequest(null, communicationTemplateId, reason, CommunicationRequestEmitter.INTERVIEWER, status); } + + /** + * Create a communication request for messhugah + * @param communicationTemplateId communication configuration id + * @param creationTimestamp creation date of the communication request (coming from the front) + * @param readyTimestamp ready timestamp of the communication request (when does the communication request is created in the back) + * @param reason reason why the communication request is created + * @return {@link CommunicationRequest} communication request object + */ + public static CommunicationRequest createCancelled(Long communicationTemplateId, Long creationTimestamp, Long readyTimestamp, CommunicationRequestReason reason) { + List status = new ArrayList<>(); + status.add(CommunicationRequestStatus.create(creationTimestamp, CommunicationStatusType.INITIATED)); + status.add(CommunicationRequestStatus.create(readyTimestamp, CommunicationStatusType.CANCELLED)); + return new CommunicationRequest(null, communicationTemplateId, reason, CommunicationRequestEmitter.INTERVIEWER, status); + } } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java index 8df10577..49c5dbf3 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java @@ -7,6 +7,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; +import java.util.Optional; import java.util.List; @Repository @@ -21,4 +22,11 @@ public List findCommunicationTemplates(String campaignId) .findCommunicationTemplates(campaignId); return CommunicationTemplateDB.toModel(communicationTemplates); } + + @Override + public Optional findCommunicationTemplate(Long communicationTemplateId, String campaignId) { + return communicationTemplateRepository + .findCommunicationTemplate(communicationTemplateId, campaignId) + .map(CommunicationTemplateDB::toModel); + } } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java index 7b0919f0..02a6c6f1 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java @@ -55,10 +55,10 @@ public static CommunicationTemplate toModel(CommunicationTemplateDB communicatio return null; } return new CommunicationTemplate( - communicationTemplate.getId(), - communicationTemplate.getMeshuggahId(), - communicationTemplate.getMedium(), - communicationTemplate.getType()); + communicationTemplate.getId(), + communicationTemplate.getMeshuggahId(), + communicationTemplate.getMedium(), + communicationTemplate.getType()); } public static List fromModel(List communicationTemplates, Campaign campaign) { diff --git a/src/main/resources/db/changelog/544_add_letter_communication_visibility.xml b/src/main/resources/db/changelog/545_add_letter_communication_visibility.xml similarity index 95% rename from src/main/resources/db/changelog/544_add_letter_communication_visibility.xml rename to src/main/resources/db/changelog/545_add_letter_communication_visibility.xml index f455e352..156513cf 100644 --- a/src/main/resources/db/changelog/544_add_letter_communication_visibility.xml +++ b/src/main/resources/db/changelog/545_add_letter_communication_visibility.xml @@ -5,7 +5,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/pro http://www.liquibase.org/xml/ns/pro/liquibase-pro-latest.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd"> - + diff --git a/src/main/resources/db/master.xml b/src/main/resources/db/master.xml index ab155ab2..10a952b5 100644 --- a/src/main/resources/db/master.xml +++ b/src/main/resources/db/master.xml @@ -58,5 +58,5 @@ - + \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java index 170feb11..12e95c53 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/VisibilityFakeService.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; public class VisibilityFakeService implements VisibilityService { @@ -52,7 +53,18 @@ public CampaignVisibility getCampaignVisibility(String idCampaign, List return null; } + @Override + public Optional findVisibility(String campaignId, String organizationalUnitId) { + return visibilities.stream() + .filter(visibility -> visibility.campaignId().equals(campaignId) && visibility.organizationalUnitId().equals(organizationalUnitId)) + .findFirst(); + } + public void save(Visibility visibility) { visibilities.add(visibility); } + + public void clearVisibilities() { + visibilities.clear(); + } } diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java index 84f40b34..4a4b0ee9 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java @@ -4,7 +4,8 @@ import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestEmitter; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestReason; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; + +import static org.assertj.core.api.Assertions.assertThat; class CommunicationRequestTest { @@ -20,14 +21,13 @@ void testCreateCommunicationRequest() { CommunicationRequest communicationRequest = CommunicationRequest.create(communicationTemplateId, creationDate, readyDate, reason); // Then - assertNotNull(communicationRequest); - assertNull(communicationRequest.id()); - assertEquals(communicationTemplateId, communicationRequest.communicationTemplateId()); - assertEquals(reason, communicationRequest.reason()); - assertEquals(CommunicationRequestEmitter.INTERVIEWER, communicationRequest.emitter()); - assertNotNull(communicationRequest.status()); - assertEquals(2, communicationRequest.status().size()); - assertEquals(creationDate, communicationRequest.status().getFirst().date()); - assertEquals(readyDate, communicationRequest.status().getLast().date()); + assertThat(communicationRequest).isNotNull(); + assertThat(communicationRequest.id()).isNull(); + assertThat(communicationTemplateId).isEqualTo(communicationRequest.communicationTemplateId()); + assertThat(reason).isEqualTo(communicationRequest.reason()); + assertThat(communicationRequest.emitter()).isEqualTo(CommunicationRequestEmitter.INTERVIEWER); + assertThat(communicationRequest.status()).hasSize(2); + assertThat(communicationRequest.status().getFirst().date()).isEqualTo(creationDate); + assertThat(communicationRequest.status().getLast().date()).isEqualTo(readyDate); } } diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java index c9d14417..e38551aa 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java @@ -1,14 +1,20 @@ package fr.insee.pearljam.domain.surveyunit.service; +import fr.insee.pearljam.api.campaign.controller.dummy.VisibilityFakeService; import fr.insee.pearljam.api.domain.*; import fr.insee.pearljam.api.service.impl.SurveyUnitUpdateServiceImpl; import fr.insee.pearljam.api.surveyunit.dto.*; import fr.insee.pearljam.domain.campaign.port.userside.DateService; import fr.insee.pearljam.domain.campaign.service.dummy.FixedDateService; +import fr.insee.pearljam.domain.campaign.model.Visibility; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; import fr.insee.pearljam.domain.surveyunit.model.CommentType; import fr.insee.pearljam.domain.surveyunit.model.communication.*; import fr.insee.pearljam.domain.surveyunit.model.question.*; import fr.insee.pearljam.domain.surveyunit.service.dummy.CommunicationRequestFakeRepository; +import fr.insee.pearljam.domain.surveyunit.service.dummy.CommunicationTemplateFakeRepository; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommentDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; @@ -26,23 +32,37 @@ class SurveyUnitUpdateServiceImplTest { private CommunicationRequestFakeRepository communicationRequestFakeRepository; + private VisibilityFakeService visibilityFakeService; private SurveyUnitUpdateServiceImpl surveyUnitService; private SurveyUnit surveyUnit; private SurveyUnitUpdateDto surveyUnitDto; - private CommunicationTemplateDB communicationTemplate; private DateService dateService; + private CommunicationTemplateDB communicationTemplateDB; + private CommunicationTemplate communicationTemplate; + private CommunicationTemplateFakeRepository communicationTemplateFakeRepository; + private Campaign campaign; + private OrganizationUnit ou; @BeforeEach void setup() { + visibilityFakeService = new VisibilityFakeService(); + communicationTemplateFakeRepository = new CommunicationTemplateFakeRepository(); dateService = new FixedDateService(); communicationRequestFakeRepository = new CommunicationRequestFakeRepository(); - surveyUnitService = new SurveyUnitUpdateServiceImpl(communicationRequestFakeRepository, dateService); + surveyUnitService = new SurveyUnitUpdateServiceImpl(communicationRequestFakeRepository, communicationTemplateFakeRepository, visibilityFakeService, dateService); + campaign = new Campaign("campaignId", "label", null, null, null,null); + ou = new OrganizationUnit("ouId", "label-ou", OrganizationUnitType.LOCAL); + Visibility visibility = new Visibility(campaign.getId(), ou.getId(), null, null, + null, null, null, null, true); + visibilityFakeService.save(visibility); surveyUnit = new SurveyUnit("id", true, true, null, - null, null, null, null, null); + null, campaign, null, ou, null); - communicationTemplate = new CommunicationTemplateDB(3L, null, null, null, null); + communicationTemplate = new CommunicationTemplate(3L, "messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + communicationTemplateFakeRepository.save(communicationTemplate); + communicationTemplateDB = new CommunicationTemplateDB(3L, "messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE, campaign); Set communicationRequestDBs = new HashSet<>(); - communicationRequestDBs.add(new CommunicationRequestDB(10L, communicationTemplate, + communicationRequestDBs.add(new CommunicationRequestDB(10L, communicationTemplateDB, CommunicationRequestReason.REFUSAL, CommunicationRequestEmitter.TOOL, surveyUnit, null)); @@ -53,9 +73,9 @@ void setup() { @DisplayName("Should add communication requests for survey unit") void testUpdateCommunication01() { List communicationRequests = List.of( - new CommunicationRequestCreateDto(1L, 12345678910L, + new CommunicationRequestCreateDto(communicationTemplate.id(), 12345678910L, CommunicationRequestReason.UNREACHABLE), - new CommunicationRequestCreateDto(2L, 1234567891011L, + new CommunicationRequestCreateDto(communicationTemplate.id(), 1234567891011L, CommunicationRequestReason.REFUSAL) ); @@ -75,7 +95,7 @@ void testUpdateCommunication01() { ) .containsExactlyInAnyOrder( tuple(null, - 1L, + communicationTemplate.id(), CommunicationRequestReason.UNREACHABLE, CommunicationRequestEmitter.INTERVIEWER, List.of( @@ -84,7 +104,7 @@ void testUpdateCommunication01() { ) ), tuple(null, - 2L, + communicationTemplate.id(), CommunicationRequestReason.REFUSAL, CommunicationRequestEmitter.INTERVIEWER, List.of( @@ -95,6 +115,57 @@ void testUpdateCommunication01() { ); } + @Test + @DisplayName("Should add CANCELLED letter communication request if visibility doesn't allow letter communications") + void testUpdateCommunication02() { + visibilityFakeService.clearVisibilities(); + communicationTemplateFakeRepository.clearCommunicationTemplates(); + Visibility visibility = new Visibility(campaign.getId(), ou.getId(), null, null, + null, null, null, null, false); + communicationTemplate = new CommunicationTemplate(3L, "messhId", CommunicationMedium.LETTER, CommunicationType.NOTICE); + communicationTemplateFakeRepository.save(communicationTemplate); + visibilityFakeService.save(visibility); + List communicationRequests = List.of( + new CommunicationRequestCreateDto(communicationTemplate.id(), 12345678910L, + CommunicationRequestReason.UNREACHABLE), + new CommunicationRequestCreateDto(communicationTemplate.id(), 1234567891011L, + CommunicationRequestReason.REFUSAL) + ); + + surveyUnitDto = createSurveyUnitDto(null, null, communicationRequests); + surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); + + List communicationRequestResults = communicationRequestFakeRepository.getCommunicationRequestsAdded(); + assertThat(communicationRequestResults) + .hasSize(2) + .extracting(CommunicationRequest::id, + CommunicationRequest::communicationTemplateId, + CommunicationRequest::reason, + CommunicationRequest::emitter, + communicationRequest -> communicationRequest.status().stream() + .map(status -> tuple(status.id(), status.date(), status.status())) + .toList() + ) + .containsExactlyInAnyOrder( + tuple(null, + 3L, + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, + List.of( + tuple(null, 12345678910L, CommunicationStatusType.INITIATED), + tuple(null, dateService.getCurrentTimestamp(), CommunicationStatusType.CANCELLED)) + ), + tuple(null, + 3L, + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.INTERVIEWER, + List.of( + tuple(null, 1234567891011L, CommunicationStatusType.INITIATED), + tuple(null, dateService.getCurrentTimestamp(), CommunicationStatusType.CANCELLED)) + ) + ); + } + @Test @DisplayName("Should add comments for survey unit") void testUpdateComments01() { diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationTemplateFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationTemplateFakeRepository.java new file mode 100644 index 00000000..be6401e2 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationTemplateFakeRepository.java @@ -0,0 +1,33 @@ +package fr.insee.pearljam.domain.surveyunit.service.dummy; + +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; +import fr.insee.pearljam.domain.campaign.port.serverside.CommunicationTemplateRepository; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class CommunicationTemplateFakeRepository implements CommunicationTemplateRepository { + + private List communicationTemplates = new ArrayList<>(); + + public void save(CommunicationTemplate communicationTemplate) { + communicationTemplates.add(communicationTemplate); + } + + public void clearCommunicationTemplates() { + communicationTemplates.clear(); + } + + @Override + public Optional findCommunicationTemplate(Long communicationTemplateId, String campaignId) { + return communicationTemplates.stream() + .filter(communicationTemplate -> communicationTemplate.id().equals(communicationTemplateId)) + .findFirst(); + } + + @Override + public List findCommunicationTemplates(String campaignId) { + return List.of(); + } +} diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index 5b53817a..ff67ca46 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -2,10 +2,13 @@ import fr.insee.pearljam.api.service.SurveyUnitService; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.ScriptConstants; +import fr.insee.pearljam.domain.exception.CommunicationTemplateNotFoundException; import fr.insee.pearljam.config.FixedDateServiceConfiguration; import fr.insee.pearljam.domain.campaign.port.userside.DateService; import org.json.JSONException; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; @@ -13,6 +16,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; @@ -471,7 +475,7 @@ void testPutSurveyUnitDetail() throws Exception { "type":"VIC" }, { - "id":13, + "id":14, "date":1590504459838, "type":"AOC" } @@ -552,4 +556,84 @@ void testPutSurveyUnitDetail() throws Exception { }"""; JSONAssert.assertEquals(expectedJson, resultJson, JSONCompareMode.NON_EXTENSIBLE); } + + @Test + @DisplayName("Should throw exception when communication template not found") + void testPutSurveyUnitDetailException() throws Exception { + String updateJson = """ + { + "id":"20", + "persons":[ + { + "id":10, + "title":"MISTER", + "firstName":"Harriette", + "lastName":"Raymond", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":true, + "phoneNumbers":[ + ] + } + ], + "address":{ + "l1":"test1", + "l2":"test2", + "l3":"test3", + "l4":"test4", + "l5":"test5", + "l6":"test6", + "l7":"test7", + "elevator":true, + "building":"testBuilding", + "floor":"testFloor", + "door":"testDoor", + "staircase":"testStaircase", + "cityPriorityDistrict":true + }, + "priority":false, + "campaign":"VQS2021X00", + "comments":[], + "sampleIdentifiers":{ + "bs":20, + "ec":"2", + "le":20, + "noi":20, + "numfa":20, + "rges":20, + "ssech":1, + "nolog":20, + "nole":20, + "autre":"20", + "nograp":"20" + }, + "states":[ + { + "date":1590504459838, + "type":"AOC" + } + ], + "contactAttempts":[], + "contactOutcome":{ + "date":1589268626000, + "type":"IMP", + "totalNumberOfContactAttempts":2 + }, + "communicationRequests":[ + { + "communicationTemplateId":6, + "reason":"UNREACHABLE", + "creationTimestamp": 1721903754405 + } + ] + }"""; + String putUrl = "/api/survey-unit/20"; + mockMvc.perform(put(putUrl) + .with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)) + .accept(MediaType.APPLICATION_JSON) + .content(updateJson) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, putUrl, CommunicationTemplateNotFoundException.MESSAGE));; + } } From ca6297243db3ff29b28fb705aef8e9eb7d6cf45c Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 1 Oct 2024 15:18:37 +0200 Subject: [PATCH 44/48] chore(typo): words mispelling --- .../surveyunit/model/communication/CommunicationRequest.java | 4 ++-- .../insee/pearljam/integration/surveyunit/SurveyUnitIT.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java index 89479e78..8db265e4 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java @@ -11,7 +11,7 @@ public record CommunicationRequest( List status) { /** - * Create a communication request for messhugah + * Create a communication request for meshuggah * @param communicationTemplateId communication configuration id * @param creationTimestamp creation date of the communication request (coming from the front) * @param readyTimestamp ready timestamp of the communication request (when does the communication request is created in the back) @@ -26,7 +26,7 @@ public static CommunicationRequest create(Long communicationTemplateId, Long cre } /** - * Create a communication request for messhugah + * Create a communication request for meshuggah * @param communicationTemplateId communication configuration id * @param creationTimestamp creation date of the communication request (coming from the front) * @param readyTimestamp ready timestamp of the communication request (when does the communication request is created in the back) diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index ff67ca46..74df6729 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -634,6 +634,6 @@ void testPutSurveyUnitDetailException() throws Exception { .accept(MediaType.APPLICATION_JSON) .content(updateJson) .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, putUrl, CommunicationTemplateNotFoundException.MESSAGE));; + .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, putUrl, CommunicationTemplateNotFoundException.MESSAGE)); } } From 5862ad297f983560591d534076d88c2182e242b7 Mon Sep 17 00:00:00 2001 From: davdarras Date: Tue, 1 Oct 2024 18:00:50 +0200 Subject: [PATCH 45/48] fix: add use letter communication in survey unit visibility --- pom.xml | 2 +- .../api/dto/surveyunit/SurveyUnitDto.java | 27 ++----------------- .../dto/SurveyUnitVisibilityDto.java | 6 +++-- .../resources/db/dataset/reinit-test-data.sql | 2 +- .../integration/surveyunit/SurveyUnitIT.java | 13 +++++---- 5 files changed, 16 insertions(+), 34 deletions(-) diff --git a/pom.xml b/pom.xml index 0556badb..6997e0d7 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ fr.insee.pearljam pearljam-back-office - 5.1.4 + 5.1.5 Pearl-Jam-Back-Office Back-office services for PearlJam diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java index a8027300..866402d8 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDto.java @@ -7,7 +7,6 @@ import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; import fr.insee.pearljam.api.domain.IdentificationConfiguration; -import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.api.dto.address.AddressDto; import fr.insee.pearljam.api.dto.campaign.CampaignDto; import fr.insee.pearljam.api.dto.person.PersonDto; @@ -67,35 +66,12 @@ public class SurveyUnitDto { private IdentificationConfiguration identificationConfiguration; private ContactOutcomeConfiguration contactOutcomeConfiguration; private ContactAttemptConfiguration contactAttemptConfiguration; + private boolean useLetterCommunication; private List persons; private AddressDto address; - public SurveyUnitDto() { - } - - public SurveyUnitDto(SurveyUnit su, SurveyUnitVisibilityDto visibility, Boolean extended) { - this.id = su.getId(); - this.campaign = su.getCampaign().getId(); - this.campaignLabel = su.getCampaign().getLabel(); - this.managementStartDate = visibility.managementStartDate(); - this.interviewerStartDate = visibility.interviewerStartDate(); - this.identificationPhaseStartDate = visibility.identificationPhaseStartDate(); - this.collectionStartDate = visibility.collectionStartDate(); - this.collectionEndDate = visibility.collectionEndDate(); - this.endDate = visibility.endDate(); - this.identificationConfiguration = su.getCampaign().getIdentificationConfiguration(); - this.contactAttemptConfiguration = su.getCampaign().getContactAttemptConfiguration(); - this.contactOutcomeConfiguration = su.getCampaign().getContactOutcomeConfiguration(); - if (Boolean.TRUE.equals(extended)) { - this.persons = su.getPersons().stream() - .map(PersonDto::new) - .toList(); - this.address = new AddressDto(su.getAddress()); - } - } - public SurveyUnitDto(String idSurveyUnit, CampaignDto campaign, SurveyUnitVisibilityDto visibility) { this.id = idSurveyUnit; this.campaign = campaign.getId(); @@ -106,6 +82,7 @@ public SurveyUnitDto(String idSurveyUnit, CampaignDto campaign, SurveyUnitVisibi this.collectionStartDate = visibility.collectionStartDate(); this.collectionEndDate = visibility.collectionEndDate(); this.endDate = visibility.endDate(); + this.useLetterCommunication = visibility.useLetterCommunication(); this.identificationConfiguration = campaign.getIdentificationConfiguration(); this.contactAttemptConfiguration = campaign.getContactAttemptConfiguration(); this.contactOutcomeConfiguration = campaign.getContactOutcomeConfiguration(); diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitVisibilityDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitVisibilityDto.java index 5e1f6a7f..efa9d91d 100644 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitVisibilityDto.java +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitVisibilityDto.java @@ -20,7 +20,8 @@ public record SurveyUnitVisibilityDto( Long identificationPhaseStartDate, Long collectionStartDate, Long collectionEndDate, - Long endDate + Long endDate, + boolean useLetterCommunication ) { public static SurveyUnitVisibilityDto fromModel(Visibility visibility) { @@ -30,6 +31,7 @@ public static SurveyUnitVisibilityDto fromModel(Visibility visibility) { visibility.identificationPhaseStartDate(), visibility.collectionStartDate(), visibility.collectionEndDate(), - visibility.endDate()); + visibility.endDate(), + visibility.useLetterCommunication()); } } diff --git a/src/main/resources/db/dataset/reinit-test-data.sql b/src/main/resources/db/dataset/reinit-test-data.sql index c86568a2..312d70dc 100644 --- a/src/main/resources/db/dataset/reinit-test-data.sql +++ b/src/main/resources/db/dataset/reinit-test-data.sql @@ -116,7 +116,7 @@ INSERT INTO visibility ( ) VALUES ('OU-NORTH', 'SIMPSONS2020X00',1721903754305, 1719225354304, 1724582154306, 1719138954303, 1719052554302, 1718966154301, true), ('OU-SOUTH', 'SIMPSONS2020X00',1721903754315, 1719225354314, 1724582154316, 1719138954310, 1719052554309, 1718966154308, false), - ('OU-NORTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308, true), + ('OU-NORTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308, false), ('OU-SOUTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308, true), ('OU-SOUTH', 'XCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true), ('OU-SOUTH', 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true), diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index 74df6729..3bf45240 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -70,7 +70,8 @@ void testGetAllSurveyUnits() throws Exception { "endDate":1724582154306, "identificationConfiguration":"IASCO", "contactOutcomeConfiguration":"F2F", - "contactAttemptConfiguration":"F2F" + "contactAttemptConfiguration":"F2F", + "useLetterCommunication": true }, { "id":"12", @@ -84,7 +85,8 @@ void testGetAllSurveyUnits() throws Exception { "endDate":1724582154306, "identificationConfiguration":"IASCO", "contactOutcomeConfiguration":"F2F", - "contactAttemptConfiguration":"F2F" + "contactAttemptConfiguration":"F2F", + "useLetterCommunication": true }, { "id":"20", @@ -98,7 +100,8 @@ void testGetAllSurveyUnits() throws Exception { "endDate":1724582154308, "identificationConfiguration":"IASCO", "contactOutcomeConfiguration":"TEL", - "contactAttemptConfiguration":"TEL" + "contactAttemptConfiguration":"TEL", + "useLetterCommunication": false } ] """; @@ -387,7 +390,7 @@ void testPutSurveyUnitDetail() throws Exception { }, "communicationRequests":[ { - "communicationTemplateId":4, + "communicationTemplateId":5, "reason":"REFUSAL", "creationTimestamp": 1721903754305 }, @@ -499,7 +502,7 @@ void testPutSurveyUnitDetail() throws Exception { }, "communicationRequests":[ { - "communicationTemplateId":4, + "communicationTemplateId":5, "reason":"REFUSAL", "emitter":"INTERVIEWER", "status":[ From 766ef3529a4570c27b2c84d7bbe00adb17f35f14 Mon Sep 17 00:00:00 2001 From: davdarras Date: Thu, 3 Oct 2024 17:12:21 +0200 Subject: [PATCH 46/48] fix: add default value for useLetterCommunication in DB --- pom.xml | 2 +- .../db/changelog/545_add_letter_communication_visibility.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 6997e0d7..451a8245 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ fr.insee.pearljam pearljam-back-office - 5.1.5 + 5.1.6 Pearl-Jam-Back-Office Back-office services for PearlJam diff --git a/src/main/resources/db/changelog/545_add_letter_communication_visibility.xml b/src/main/resources/db/changelog/545_add_letter_communication_visibility.xml index 156513cf..e824a828 100644 --- a/src/main/resources/db/changelog/545_add_letter_communication_visibility.xml +++ b/src/main/resources/db/changelog/545_add_letter_communication_visibility.xml @@ -7,7 +7,7 @@ - + From dd797be4d578f19b43a61b40779f2a52b0514156 Mon Sep 17 00:00:00 2001 From: David Darras Date: Fri, 4 Oct 2024 09:59:19 +0200 Subject: [PATCH 47/48] fix: move mail/tel to visibility --- pom.xml | 2 +- .../CommunicationInformationController.java | 72 -------------- .../campaign/dto/input/CampaignCreateDto.java | 2 - .../campaign/dto/input/CampaignUpdateDto.java | 2 - ...unicationInformationCampaignCreateDto.java | 33 ------- ...unicationInformationCampaignUpdateDto.java | 33 ------- .../CommunicationInformationUpdateDto.java | 25 ----- .../input/VisibilityCampaignCreateDto.java | 10 +- .../input/VisibilityCampaignUpdateDto.java | 8 +- .../dto/input/VisibilityUpdateDto.java | 8 +- .../dto/output/CampaignResponseDto.java | 5 +- .../CommunicationInformationResponseDto.java | 21 ---- .../dto/output/VisibilityCampaignDto.java | 8 +- .../insee/pearljam/api/domain/Campaign.java | 4 - .../api/service/impl/CampaignServiceImpl.java | 27 +---- .../exception/ExceptionControllerAdvice.java | 5 - .../domain/campaign/model/Visibility.java | 11 ++- .../CommunicationInformation.java | 9 -- .../CommunicationInformationRepository.java | 30 ------ .../CommunicationInformationService.java | 35 ------- .../CommunicationInformationServiceImpl.java | 38 ------- .../CommunicationInformationDaoAdapter.java | 58 ----------- .../entity/CommunicationInformationDB.java | 64 ------------ .../entity/CommunicationInformationDBId.java | 41 -------- .../campaign/entity/VisibilityDB.java | 19 +++- ...CommunicationInformationJpaRepository.java | 15 --- .../546_update_communication_information.xml | 17 ++++ .../resources/db/dataset/init-demo-data.sql | 29 ++---- .../resources/db/dataset/reinit-test-data.sql | 26 ++--- src/main/resources/db/master.xml | 3 + .../CampaignControllerCreateTest.java | 13 +-- .../controller/CampaignControllerTest.java | 2 +- .../CampaignControllerUpdateTest.java | 29 +++--- ...ommunicationInformationControllerTest.java | 51 ---------- .../controller/VisibilityControllerTest.java | 12 ++- .../VisibilityCampaignCreateDtoTest.java | 7 +- .../VisibilityCampaignUpdateDtoTest.java | 12 ++- .../dto/input/VisibilityUpdateDtoTest.java | 7 +- .../dto/output/VisibilityCampaignDtoTest.java | 10 +- .../domain/campaign/model/VisibilityTest.java | 21 ++-- .../service/CampaignServiceImplTest.java | 44 +++++---- .../service/VisibilityServiceImplTest.java | 18 +++- .../CommunicationInformationFakeService.java | 33 ------- .../dummy/VisibilityFakeRepository.java | 4 +- .../SurveyUnitUpdateServiceImplTest.java | 4 +- .../adapter/VisibilityDaoAdapterTest.java | 14 ++- .../campaign/entity/VisibilityDBTest.java | 63 +++++++----- .../integration/campaign/CampaignIT.java | 99 +++++-------------- .../campaign/CommunicationInformationIT.java | 89 ----------------- .../integration/campaign/VisibilityIT.java | 14 ++- 50 files changed, 283 insertions(+), 923 deletions(-) delete mode 100644 src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationController.java delete mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java delete mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java delete mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java delete mode 100644 src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java delete mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java delete mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java delete mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationInformationService.java delete mode 100644 src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationInformationServiceImpl.java delete mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java delete mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java delete mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDBId.java delete mode 100644 src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java create mode 100644 src/main/resources/db/changelog/546_update_communication_information.xml delete mode 100644 src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java delete mode 100644 src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java delete mode 100644 src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java diff --git a/pom.xml b/pom.xml index 451a8245..7d351203 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ fr.insee.pearljam pearljam-back-office - 5.1.6 + 5.1.7 Pearl-Jam-Back-Office Back-office services for PearlJam diff --git a/src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationController.java b/src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationController.java deleted file mode 100644 index 534e850f..00000000 --- a/src/main/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationController.java +++ /dev/null @@ -1,72 +0,0 @@ -package fr.insee.pearljam.api.campaign.controller; - -import fr.insee.pearljam.api.campaign.dto.input.CommunicationInformationUpdateDto; -import fr.insee.pearljam.api.campaign.dto.output.CommunicationInformationResponseDto; -import fr.insee.pearljam.api.campaign.dto.output.VisibilityCampaignDto; -import fr.insee.pearljam.api.constants.Constants; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; -import fr.insee.pearljam.domain.campaign.port.userside.CommunicationInformationService; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.validation.Valid; -import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.NotNull; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@RestController -@Tag(name = "01. Campaigns", description = "Endpoints for campaigns") -@Slf4j -@RequiredArgsConstructor -@Validated -public class CommunicationInformationController { - private final CommunicationInformationService communicationInformationService; - private final AuthenticatedUserService authenticatedUserService; - - /** - * This method returns the list of communication informations associated with the - * campaign {id} - * - * @param campaignId campaign id - * @return List of {@link VisibilityCampaignDto} - */ - @Operation(summary = "Get campaign communication informations") - @GetMapping(path = Constants.API_CAMPAIGN_ID_COMMUNICATION_INFORMATIONS) - public List getCommunicationInformations(@NotBlank @PathVariable(value = "id") String campaignId) throws CampaignNotFoundException { - String userId = authenticatedUserService.getCurrentUserId(); - log.info("{} try to get campaign[{}] communication informations ", userId, campaignId); - - List communicationInformations = communicationInformationService.findCommunicationInformations(campaignId); - return CommunicationInformationResponseDto.fromModel(communicationInformations); - } - - /** - * Update the communication information for a given campaign and organizational unit - * - * @param communicationInformationToUpdate the communication information to update - * @param idCampaign campaign identifier - * @param idOu organizational unit id - */ - @Operation(summary = "Update the communication information of a campaign for an organizational unit") - @PutMapping(path = Constants.API_CAMPAIGN_ID_OU_ID_COMMUNICATION_INFORMATION) - public void updateCommunicationInformation( - @Valid @NotNull @RequestBody CommunicationInformationUpdateDto communicationInformationToUpdate, - @NotBlank @PathVariable(value = "idCampaign") String idCampaign, - @NotBlank @PathVariable(value = "idOu") String idOu) { - String userId = authenticatedUserService.getCurrentUserId(); - log.info("{} try to change OU[{}] communication information on campaign[{}] ", userId, idOu, idCampaign); - communicationInformationService - .updateCommunicationInformation(CommunicationInformationUpdateDto.toModel( - communicationInformationToUpdate, - idCampaign, - idOu)); - log.info("Communication information with CampaignId {} for Organizational Unit {} updated", idCampaign, - idOu); - } -} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java index 93cb41c8..aea8c958 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java @@ -23,8 +23,6 @@ public record CampaignCreateDto ( @Valid List visibilities, @Valid - List communicationInformations, - @Valid @NoDuplicateMediumAndType List communicationTemplates, List referents, diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java index 48ac2c15..31f6b4b1 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java @@ -25,8 +25,6 @@ public record CampaignUpdateDto( String campaignLabel, @Valid List visibilities, - @Valid - List communicationInformations, List referents, String email, IdentificationConfiguration identificationConfiguration, diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java deleted file mode 100644 index 94e2c369..00000000 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignCreateDto.java +++ /dev/null @@ -1,33 +0,0 @@ -package fr.insee.pearljam.api.campaign.dto.input; - -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; -import jakarta.validation.constraints.NotBlank; -import org.springframework.lang.NonNull; - -import java.util.ArrayList; -import java.util.List; - -public record CommunicationInformationCampaignCreateDto( - @NotBlank - String organizationalUnit, - String mail, - String tel) { - public static CommunicationInformation toModel(@NonNull CommunicationInformationCampaignCreateDto communicationInformation, - String campaignId) { - return new CommunicationInformation(campaignId, - communicationInformation.organizationalUnit(), - communicationInformation.mail(), - communicationInformation.tel()); - } - - public static List toModel(List communicationInformations, - String campaignId) { - if(communicationInformations == null) { - return new ArrayList<>(); - } - - return communicationInformations.stream() - .map(communicationInformation -> CommunicationInformationCampaignCreateDto.toModel(communicationInformation, campaignId)) - .toList(); - } -} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java deleted file mode 100644 index f2044e32..00000000 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationCampaignUpdateDto.java +++ /dev/null @@ -1,33 +0,0 @@ -package fr.insee.pearljam.api.campaign.dto.input; - -import com.fasterxml.jackson.annotation.JsonProperty; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; -import jakarta.validation.constraints.NotBlank; - -import java.util.List; - -public record CommunicationInformationCampaignUpdateDto( - @NotBlank - String organizationalUnit, - @JsonProperty(required = true) - String mail, - @JsonProperty(required = true) - String tel) { - - public static CommunicationInformation toModel(CommunicationInformationCampaignUpdateDto communicationInformation, String campaignId) { - if(communicationInformation == null) { - return null; - } - return new CommunicationInformation( - campaignId, - communicationInformation.organizationalUnit(), - communicationInformation.mail(), - communicationInformation.tel()); - } - - public static List toModel(List communicationsInformations, String campaignId) { - return communicationsInformations.stream() - .map(communicationInformations -> toModel(communicationInformations, campaignId)) - .toList(); - } - } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java deleted file mode 100644 index 414499bd..00000000 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationInformationUpdateDto.java +++ /dev/null @@ -1,25 +0,0 @@ -package fr.insee.pearljam.api.campaign.dto.input; - -import com.fasterxml.jackson.annotation.JsonProperty; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; -import lombok.NonNull; - -public record CommunicationInformationUpdateDto( - @JsonProperty(required = true) - String mail, - @JsonProperty(required = true) - String tel) { - - public static CommunicationInformation toModel(CommunicationInformationUpdateDto communicationInformation, - @NonNull String campaignId, - @NonNull String ouId) { - if(communicationInformation == null) { - return null; - } - return new CommunicationInformation( - campaignId, - ouId, - communicationInformation.mail(), - communicationInformation.tel()); - } -} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java index a6241d9b..41581915 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java @@ -37,7 +37,11 @@ public record VisibilityCampaignCreateDto( @NotBlank String organizationalUnit, @NotNull - Boolean useLetterCommunication + Boolean useLetterCommunication, + @NotNull + String mail, + @NotNull + String tel ) { public static Visibility toModel(@NonNull VisibilityCampaignCreateDto visibility, String campaignId) { @@ -49,7 +53,9 @@ public static Visibility toModel(@NonNull VisibilityCampaignCreateDto visibility visibility.collectionStartDate(), visibility.collectionEndDate(), visibility.endDate(), - visibility.useLetterCommunication()); + visibility.useLetterCommunication(), + visibility.mail(), + visibility.tel()); } public static List toModel(List visibilities, String campaignId) { diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java index a6eed06e..25227f66 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java @@ -29,7 +29,9 @@ public record VisibilityCampaignUpdateDto( Long endDate, @NotBlank String organizationalUnit, - Boolean useLetterCommunication + Boolean useLetterCommunication, + String mail, + String tel ) { public static Visibility toModel(@NonNull VisibilityCampaignUpdateDto visibility, String campaignId) { return new Visibility(campaignId, @@ -40,7 +42,9 @@ public static Visibility toModel(@NonNull VisibilityCampaignUpdateDto visibility visibility.collectionStartDate(), visibility.collectionEndDate(), visibility.endDate(), - visibility.useLetterCommunication()); + visibility.useLetterCommunication(), + visibility.mail(), + visibility.tel()); } public static List toModel(List visibilitiesDto, String campaignId) { diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java index 712a24bc..355d1f7f 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java @@ -24,7 +24,9 @@ public record VisibilityUpdateDto( Long collectionStartDate, Long collectionEndDate, Long endDate, - Boolean useLetterCommunication + Boolean useLetterCommunication, + String mail, + String tel ) { public static Visibility toModel(@NonNull VisibilityUpdateDto visibilityDto, @@ -37,6 +39,8 @@ public static Visibility toModel(@NonNull VisibilityUpdateDto visibilityDto, visibilityDto.collectionStartDate(), visibilityDto.collectionEndDate(), visibilityDto.endDate(), - visibilityDto.useLetterCommunication()); + visibilityDto.useLetterCommunication(), + visibilityDto.mail(), + visibilityDto.tel()); } } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java index bb1f4727..3dcf719d 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java @@ -26,7 +26,6 @@ public record CampaignResponseDto( String campaign, String campaignLabel, List visibilities, - List communicationInformations, List referents, String email, IdentificationConfiguration identificationConfiguration, @@ -35,12 +34,10 @@ public record CampaignResponseDto( ) { public static CampaignResponseDto fromModel(Campaign campaignDB, List referents, - List visibilities, - List communicationInformations) { + List visibilities) { return new CampaignResponseDto(campaignDB.getId(), campaignDB.getLabel(), visibilities, - communicationInformations, referents, campaignDB.getEmail(), campaignDB.getIdentificationConfiguration(), diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java deleted file mode 100644 index 53ac8d6b..00000000 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationInformationResponseDto.java +++ /dev/null @@ -1,21 +0,0 @@ -package fr.insee.pearljam.api.campaign.dto.output; - -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; - -import java.util.List; - -public record CommunicationInformationResponseDto( - String organizationalUnit, - String mail, - String tel) { - - public static List fromModel(List communications) { - return communications.stream() - .map(communicationInformation -> new CommunicationInformationResponseDto( - communicationInformation.organizationalUnitId(), - communicationInformation.mail(), - communicationInformation.tel() - )) - .toList(); - } -} diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java index a28362fe..5d329f8f 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDto.java @@ -15,7 +15,9 @@ public record VisibilityCampaignDto( Long collectionStartDate, Long collectionEndDate, Long endDate, - boolean useLetterCommunication) { + boolean useLetterCommunication, + String mail, + String tel) { public static List fromModel(List visibilities) { return visibilities.stream() @@ -27,7 +29,9 @@ public static List fromModel(List visibilitie visibility.collectionStartDate(), visibility.collectionEndDate(), visibility.endDate(), - visibility.useLetterCommunication() + visibility.useLetterCommunication(), + visibility.mail(), + visibility.tel() )) .toList(); } diff --git a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java index 04a1d57c..8cf5163b 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java @@ -3,7 +3,6 @@ import java.io.Serializable; import java.util.List; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import jakarta.persistence.CascadeType; @@ -76,9 +75,6 @@ public class Campaign implements Serializable { @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, orphanRemoval = true) private List communicationTemplates; - @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, orphanRemoval = true) - private List communicationInformations; - public Campaign(String id, String label, IdentificationConfiguration identConfig, ContactOutcomeConfiguration contOutConfig, ContactAttemptConfiguration contAttConfig, String email) { super(); diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index 081a3892..a98cca9c 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -3,7 +3,6 @@ import fr.insee.pearljam.api.campaign.dto.input.*; import fr.insee.pearljam.api.campaign.dto.input.CommunicationTemplateCreateDto; import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; -import fr.insee.pearljam.api.campaign.dto.output.CommunicationInformationResponseDto; import fr.insee.pearljam.api.campaign.dto.output.VisibilityCampaignDto; import fr.insee.pearljam.api.domain.Campaign; import fr.insee.pearljam.api.domain.OrganizationUnit; @@ -19,13 +18,10 @@ import fr.insee.pearljam.api.service.*; import fr.insee.pearljam.domain.campaign.model.CampaignVisibility; import fr.insee.pearljam.domain.campaign.model.Visibility; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; -import fr.insee.pearljam.domain.campaign.port.userside.CommunicationInformationService; import fr.insee.pearljam.domain.campaign.port.userside.DateService; import fr.insee.pearljam.domain.campaign.port.userside.VisibilityService; import fr.insee.pearljam.domain.exception.*; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import lombok.NonNull; @@ -67,7 +63,6 @@ public class CampaignServiceImpl implements CampaignService { private final ReferentService referentService; private final VisibilityService visibilityService; private final DateService dateService; - private final CommunicationInformationService communicationInformationService; @Override public List getListCampaign(String userId) { @@ -179,16 +174,6 @@ public void createCampaign(CampaignCreateDto campaignDto) } campaign.setVisibilities(visibilitiesDBToCreate); - List communicationInformations = CommunicationInformationCampaignCreateDto.toModel(campaignDto.communicationInformations(), campaignDto.campaign()); - List communicationInformationsDBToCreate = new ArrayList<>(); - for (CommunicationInformation communicationInformation : communicationInformations) { - OrganizationUnit organizationUnit = organizationUnitRepository.findById(communicationInformation.organizationalUnitId()) - .orElseThrow(OrganizationalUnitNotFoundException::new); - communicationInformationsDBToCreate.add(CommunicationInformationDB.fromModel(communicationInformation, campaign, organizationUnit)); - } - campaign.setCommunicationInformations(communicationInformationsDBToCreate); - - if(campaignDto.referents() != null) { updateReferents(campaign, campaignDto.referents()); } @@ -241,13 +226,6 @@ public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate } } - if(campaignToUpdate.communicationInformations() != null) { - List communicationInformations = CommunicationInformationCampaignUpdateDto.toModel( - campaignToUpdate.communicationInformations(), - campaignId); - communicationInformationService.setCommunicationInformations(communicationInformations, currentCampaign); - } - currentCampaign.setLabel(campaignToUpdate.campaignLabel()); if (!StringUtils.isBlank(campaignToUpdate.email())) { currentCampaign.setEmail(campaignToUpdate.email()); @@ -326,9 +304,6 @@ public CampaignResponseDto getCampaignDtoById(String campaignId) throws Campaign List visibilities = VisibilityCampaignDto.fromModel( visibilityService.findVisibilities(campaignId) ); - List communicationInformations = CommunicationInformationResponseDto.fromModel( - communicationInformationService.findCommunicationInformations(campaignId) - ); - return CampaignResponseDto.fromModel(campaignDB, referents, visibilities, communicationInformations); + return CampaignResponseDto.fromModel(campaignDB, referents, visibilities); } } diff --git a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java index 9c5a06cd..63d2b8a5 100644 --- a/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java +++ b/src/main/java/fr/insee/pearljam/api/web/exception/ExceptionControllerAdvice.java @@ -135,11 +135,6 @@ public ResponseEntity exceptions(SurveyUnitNotFoundException e, WebReq return generateResponseError(e, HttpStatus.NOT_FOUND, request); } - @ExceptionHandler(CommunicationInformationNotFoundException.class) - public ResponseEntity exceptions(CommunicationInformationNotFoundException e, WebRequest request) { - return generateResponseError(e, HttpStatus.NOT_FOUND, request); - } - @ExceptionHandler(VisibilityNotFoundException.class) public ResponseEntity exceptions(VisibilityNotFoundException e, WebRequest request) { return generateResponseError(e, HttpStatus.NOT_FOUND, request); diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java index 5abe9f83..2628ae84 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/Visibility.java @@ -22,7 +22,9 @@ public record Visibility( Long collectionStartDate, Long collectionEndDate, Long endDate, - Boolean useLetterCommunication + Boolean useLetterCommunication, + String mail, + String tel ) { public static Visibility merge(Visibility currentVisibility, Visibility visibilityToUpdate) throws VisibilityHasInvalidDatesException { Long managementStartDate = visibilityToUpdate.managementStartDate() != null ? @@ -39,6 +41,8 @@ public static Visibility merge(Visibility currentVisibility, Visibility visibili visibilityToUpdate.endDate() : currentVisibility.endDate(); Boolean useCommunication = visibilityToUpdate.useLetterCommunication() != null ? visibilityToUpdate.useLetterCommunication() : currentVisibility.useLetterCommunication(); + String mail = visibilityToUpdate.mail() != null ? visibilityToUpdate.mail() : currentVisibility.mail(); + String tel = visibilityToUpdate.tel() != null ? visibilityToUpdate.tel() : currentVisibility.tel(); Visibility updatedVisibility = new Visibility( currentVisibility.campaignId(), @@ -49,8 +53,9 @@ public static Visibility merge(Visibility currentVisibility, Visibility visibili collectionStartDate, collectionEndDate, endDate, - useCommunication - ); + useCommunication, + mail, + tel); if(isValid(updatedVisibility)) { return updatedVisibility; diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java deleted file mode 100644 index 272a5d8d..00000000 --- a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationInformation.java +++ /dev/null @@ -1,9 +0,0 @@ -package fr.insee.pearljam.domain.campaign.model.communication; - -public record CommunicationInformation( - String campaignId, - String organizationalUnitId, - String mail, - String tel -) { -} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java deleted file mode 100644 index 5bc652e9..00000000 --- a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationInformationRepository.java +++ /dev/null @@ -1,30 +0,0 @@ -package fr.insee.pearljam.domain.campaign.port.serverside; - -import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; -import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; - -import java.util.List; - -public interface CommunicationInformationRepository { - - /** - * - * @param campaignId campaign id - * @return the communication informations of a campaign - */ - List findCommunicationInformations(String campaignId); - - /** - * Update a communication information - * @param communicationInformationToUpdate the communication information to update - */ - void update(CommunicationInformation communicationInformationToUpdate); - - /** - * set the communication informations to a campaign - * @param communicationInformations list of communication informations to set - * @param campaign campaign - */ - void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException; -} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationInformationService.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationInformationService.java deleted file mode 100644 index bbc95957..00000000 --- a/src/main/java/fr/insee/pearljam/domain/campaign/port/userside/CommunicationInformationService.java +++ /dev/null @@ -1,35 +0,0 @@ -package fr.insee.pearljam.domain.campaign.port.userside; - -import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; - -import java.util.List; - -public interface CommunicationInformationService { - - /** - * - * @param campaignId campaign id - * @return the visibilities for the campaign - * @throws CampaignNotFoundException if campaign not found - */ - List findCommunicationInformations(String campaignId) throws CampaignNotFoundException; - - - /** - * - * @param communicationInformations List of communication informations to set - * @param campaign campaign where the list should be set - * @throws OrganizationalUnitNotFoundException exception when no ou found - * @throws CampaignNotFoundException exception when no campaign found - */ - void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException, CampaignNotFoundException; - - /** - * update a communication information - * @param communicationInformationToUpdate informationToUpdate communication information to update - */ - void updateCommunicationInformation(CommunicationInformation communicationInformationToUpdate); -} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationInformationServiceImpl.java b/src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationInformationServiceImpl.java deleted file mode 100644 index 17b14cc0..00000000 --- a/src/main/java/fr/insee/pearljam/domain/campaign/service/CommunicationInformationServiceImpl.java +++ /dev/null @@ -1,38 +0,0 @@ -package fr.insee.pearljam.domain.campaign.service; - -import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; -import fr.insee.pearljam.domain.campaign.port.serverside.CommunicationInformationRepository; -import fr.insee.pearljam.domain.campaign.port.userside.CommunicationInformationService; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@RequiredArgsConstructor -@Transactional(rollbackFor = Exception.class) -@Slf4j -public class CommunicationInformationServiceImpl implements CommunicationInformationService { - - private final CommunicationInformationRepository communicationInformationRepository; - - @Override - public List findCommunicationInformations(String campaignId) { - return communicationInformationRepository.findCommunicationInformations(campaignId); - } - - @Override - public void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException, CampaignNotFoundException { - communicationInformationRepository.setCommunicationInformations(communicationInformations, campaign); - } - - @Override - public void updateCommunicationInformation(CommunicationInformation communicationInformationToUpdate) { - communicationInformationRepository.update(communicationInformationToUpdate); - } -} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java deleted file mode 100644 index f89fe1b0..00000000 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationInformationDaoAdapter.java +++ /dev/null @@ -1,58 +0,0 @@ -package fr.insee.pearljam.infrastructure.campaign.adapter; - -import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.api.domain.OrganizationUnit; -import fr.insee.pearljam.api.repository.CampaignRepository; -import fr.insee.pearljam.api.repository.OrganizationUnitRepository; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; -import fr.insee.pearljam.domain.campaign.port.serverside.CommunicationInformationRepository; -import fr.insee.pearljam.domain.exception.CommunicationInformationNotFoundException; -import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; -import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationInformationJpaRepository; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@RequiredArgsConstructor -@Repository -@Transactional -public class CommunicationInformationDaoAdapter implements CommunicationInformationRepository { - private final CommunicationInformationJpaRepository crudRepository; - private final OrganizationUnitRepository organizationUnitRepository; - private final CampaignRepository campaignRepository; - - @Override - public List findCommunicationInformations(String campaignId) { - return CommunicationInformationDB.toModel( - crudRepository.findByCampaignId(campaignId) - ); - } - - @Override - public void update(CommunicationInformation communicationInformationToUpdate) { - CommunicationInformationDB currentCommunicationInformationDB = crudRepository.findByCampaignIdAndOrganizationUnitId( - communicationInformationToUpdate.campaignId(), communicationInformationToUpdate.organizationalUnitId()) - .orElseThrow(CommunicationInformationNotFoundException::new); - currentCommunicationInformationDB.setMail(communicationInformationToUpdate.mail()); - currentCommunicationInformationDB.setTel(communicationInformationToUpdate.tel()); - crudRepository.save(currentCommunicationInformationDB); - } - - @Override - public void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException { - List currentCommunicationInformations = campaign.getCommunicationInformations(); - currentCommunicationInformations.clear(); - for(CommunicationInformation communicationInformationToUpdate : communicationInformations) { - OrganizationUnit organizationUnit = organizationUnitRepository - .findById(communicationInformationToUpdate.organizationalUnitId()) - .orElseThrow(OrganizationalUnitNotFoundException::new); - - CommunicationInformationDB communicationConfigurationDB = CommunicationInformationDB.fromModel(communicationInformationToUpdate, campaign, organizationUnit); - currentCommunicationInformations.add(communicationConfigurationDB); - } - campaignRepository.save(campaign); - } -} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java deleted file mode 100644 index 8543fdec..00000000 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDB.java +++ /dev/null @@ -1,64 +0,0 @@ -package fr.insee.pearljam.infrastructure.campaign.entity; - -import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.api.domain.OrganizationUnit; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; -import jakarta.persistence.*; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; - -import java.io.Serial; -import java.io.Serializable; -import java.util.List; - -@Entity -@Table(name = "communication_information") -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Slf4j -public class CommunicationInformationDB implements Serializable { - - @Serial - private static final long serialVersionUID = 1L; - - @EmbeddedId - private CommunicationInformationDBId communicationInformationId; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "organization_unit_id", insertable = false, updatable = false) - private OrganizationUnit organizationUnit; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "campaign_id", insertable = false, updatable = false) - private Campaign campaign; - - private String mail; - private String tel; - - public static CommunicationInformationDB fromModel(CommunicationInformation communicationInformation, Campaign campaign, OrganizationUnit organizationUnit) { - CommunicationInformationDBId id = new CommunicationInformationDBId(organizationUnit.getId(), campaign.getId()); - return new CommunicationInformationDB(id, - organizationUnit, campaign, - communicationInformation.mail(), - communicationInformation.tel()); - } - - public static CommunicationInformation toModel(CommunicationInformationDB communicationInformationDB) { - return new CommunicationInformation( - communicationInformationDB.getCommunicationInformationId().getCampaignId(), - communicationInformationDB.getCommunicationInformationId().getOrganizationUnitId(), - communicationInformationDB.getMail(), - communicationInformationDB.getTel()); - } - - public static List toModel(List communicationInformationDBS) { - return communicationInformationDBS.stream() - .map(CommunicationInformationDB::toModel) - .toList(); - } -} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDBId.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDBId.java deleted file mode 100644 index 08ba5672..00000000 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationInformationDBId.java +++ /dev/null @@ -1,41 +0,0 @@ -package fr.insee.pearljam.infrastructure.campaign.entity; - -import jakarta.persistence.Column; -import jakarta.persistence.Embeddable; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.io.Serial; -import java.io.Serializable; - -/** - * This class is used to defines the association between OrganizationUnit and - * Campaign tables. - * - * @author scorcaud - */ -@Embeddable -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -public class CommunicationInformationDBId implements Serializable { - - @Serial - private static final long serialVersionUID = 1L; - - /** - * The organizationUnit Id - */ - @Column(name = "organization_unit_id") - private String organizationUnitId; - - /** - * The campaign Id - */ - @Column(name = "campaign_id") - private String campaignId; - -} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java index eaa1b1db..211a120b 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java @@ -42,6 +42,8 @@ public class VisibilityDB implements Serializable { private Long collectionEndDate; private Long endDate; private boolean useLetterCommunication; + private String mail; + private String tel; public void update(Visibility visibilityToUpdate) { String ouId = visibilityToUpdate.organizationalUnitId(); @@ -75,6 +77,16 @@ public void update(Visibility visibilityToUpdate) { log.info("Updating letter communication usage for campaign {} and Organizational Unit {}", campaignId, ouId); this.setUseLetterCommunication(visibilityToUpdate.useLetterCommunication()); } + + if (visibilityToUpdate.mail() != null) { + log.info("Updating mail communication usage for campaign {} and Organizational Unit {}", campaignId, ouId); + this.setMail(visibilityToUpdate.mail()); + } + + if (visibilityToUpdate.tel() != null) { + log.info("Updating tel communication usage for campaign {} and Organizational Unit {}", campaignId, ouId); + this.setTel(visibilityToUpdate.tel()); + } } public static VisibilityDB fromModel(Visibility visibility, Campaign campaign, OrganizationUnit organizationUnit) { @@ -82,7 +94,8 @@ public static VisibilityDB fromModel(Visibility visibility, Campaign campaign, O return new VisibilityDB(id, organizationUnit, campaign, visibility.managementStartDate(), visibility.interviewerStartDate(), visibility.identificationPhaseStartDate(), - visibility.collectionStartDate(), visibility.collectionEndDate(), visibility.endDate(), visibility.useLetterCommunication()); + visibility.collectionStartDate(), visibility.collectionEndDate(), visibility.endDate(), visibility.useLetterCommunication(), + visibility.mail(), visibility.tel()); } public static Visibility toModel(VisibilityDB visibilityDB) { @@ -95,7 +108,9 @@ public static Visibility toModel(VisibilityDB visibilityDB) { visibilityDB.getCollectionStartDate(), visibilityDB.getCollectionEndDate(), visibilityDB.getEndDate(), - visibilityDB.isUseLetterCommunication()); + visibilityDB.isUseLetterCommunication(), + visibilityDB.getMail(), + visibilityDB.getTel()); } public static List toModel(List visibilityDBs) { diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java deleted file mode 100644 index c8a151c9..00000000 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationInformationJpaRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package fr.insee.pearljam.infrastructure.campaign.jpa; - -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDBId; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; -import java.util.Optional; - -public interface CommunicationInformationJpaRepository extends JpaRepository { - - Optional findByCampaignIdAndOrganizationUnitId(String campaignId, String organizationalUnitId); - - List findByCampaignId(String campaignId); -} diff --git a/src/main/resources/db/changelog/546_update_communication_information.xml b/src/main/resources/db/changelog/546_update_communication_information.xml new file mode 100644 index 00000000..4c519878 --- /dev/null +++ b/src/main/resources/db/changelog/546_update_communication_information.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + diff --git a/src/main/resources/db/dataset/init-demo-data.sql b/src/main/resources/db/dataset/init-demo-data.sql index 10667442..01b89489 100644 --- a/src/main/resources/db/dataset/init-demo-data.sql +++ b/src/main/resources/db/dataset/init-demo-data.sql @@ -85,7 +85,9 @@ INSERT INTO visibility ( identification_phase_start_date, interviewer_start_date, management_start_date, - use_letter_communication + use_letter_communication, + mail, + tel ) VALUES ('OU-NORTH', 'SIMPSONS2020X00', EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, @@ -94,8 +96,7 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - true), - + true, 'north-simpsons@nooneknows.fr', '0321234567'), ('OU-NORTH', 'VQS2021X00', EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, @@ -103,7 +104,7 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - true), + true, 'north-vqs@nooneknows.fr', ''), ('OU-SOUTH', 'VQS2021X00', EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, @@ -112,7 +113,7 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - true), + true, 'south-vqs@nooneknows.fr', ''), ('OU-SOUTH', 'SIMPSONS2020X00', EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, @@ -121,7 +122,7 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - true), + true, 'south-simpsons@nooneknows.fr', '0123456789'), ('OU-SOUTH', 'ZCLOSEDX00', EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, @@ -130,7 +131,7 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, - true), + true, 'south-zclosed@nooneknows.fr', ''), ('OU-WEST', 'ZCLOSEDX00', EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, @@ -139,7 +140,7 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, - true), + true, 'west-zclosed@nooneknows.fr', ''), ('OU-SOUTH', 'XCLOSEDX00', EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, @@ -148,17 +149,7 @@ INSERT INTO visibility ( EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, - true); - -INSERT INTO communication_information ( - organization_unit_id, - campaign_id, - mail, - tel -) VALUES - ('OU-NORTH', 'SIMPSONS2020X00', 'north-simpsons@nooneknows.fr', '0321234567'), - ('OU-SOUTH', 'SIMPSONS2020X00', 'south-simpsons@nooneknows.fr', NULL), - ('OU-NORTH', 'VQS2021X00', 'north-vqs@nooneknows.fr', ''); + true, 'south-xclosed@nooneknows.fr', ''); INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', TRUE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; diff --git a/src/main/resources/db/dataset/reinit-test-data.sql b/src/main/resources/db/dataset/reinit-test-data.sql index 312d70dc..d2a0cdf5 100644 --- a/src/main/resources/db/dataset/reinit-test-data.sql +++ b/src/main/resources/db/dataset/reinit-test-data.sql @@ -26,7 +26,6 @@ TRUNCATE TABLE public.comment; TRUNCATE TABLE public.closing_cause; TRUNCATE TABLE public.organization_unit; TRUNCATE TABLE public.address; -TRUNCATE TABLE public.communication_information; ALTER TABLE public.communication_request_status ALTER COLUMN id RESTART WITH 1; ALTER TABLE public.communication_request ALTER COLUMN id RESTART WITH 1; @@ -112,26 +111,17 @@ INSERT INTO visibility ( identification_phase_start_date, interviewer_start_date, management_start_date, - use_letter_communication -) VALUES - ('OU-NORTH', 'SIMPSONS2020X00',1721903754305, 1719225354304, 1724582154306, 1719138954303, 1719052554302, 1718966154301, true), - ('OU-SOUTH', 'SIMPSONS2020X00',1721903754315, 1719225354314, 1724582154316, 1719138954310, 1719052554309, 1718966154308, false), - ('OU-NORTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308, false), - ('OU-SOUTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308, true), - ('OU-SOUTH', 'XCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true), - ('OU-SOUTH', 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true), - ('OU-WEST' , 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true); - -INSERT INTO communication_information ( - organization_unit_id, - campaign_id, + use_letter_communication, mail, tel ) VALUES - ('OU-NORTH', 'SIMPSONS2020X00', 'north-simpsons@nooneknows.fr', '0321234567'), - ('OU-SOUTH', 'VQS2021X00', 'north-vqs@nooneknows.fr', ''); - - + ('OU-NORTH', 'SIMPSONS2020X00',1721903754305, 1719225354304, 1724582154306, 1719138954303, 1719052554302, 1718966154301, true, 'north-simpsons@nooneknows.fr', '0321234567'), + ('OU-SOUTH', 'SIMPSONS2020X00',1721903754315, 1719225354314, 1724582154316, 1719138954310, 1719052554309, 1718966154308, false, 'south-simpsons@nooneknows.fr', ''), + ('OU-NORTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308, false, 'north-vqs@nooneknows.fr', ''), + ('OU-SOUTH', 'VQS2021X00',1721903754308, 1719225354308, 1724582154308, 1719138954308, 1719052554308, 1718966154308, true, 'north-vqs@nooneknows.fr', ''), + ('OU-SOUTH', 'XCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true, 'north-vqs@nooneknows.fr', ''), + ('OU-SOUTH', 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true, 'north-vqs@nooneknows.fr', ''), + ('OU-WEST' , 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true, 'north-vqs@nooneknows.fr', ''); INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; diff --git a/src/main/resources/db/master.xml b/src/main/resources/db/master.xml index 10a952b5..6d41a033 100644 --- a/src/main/resources/db/master.xml +++ b/src/main/resources/db/master.xml @@ -59,4 +59,7 @@ + + + \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java index 2487bbfe..b61b89c3 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java @@ -101,14 +101,12 @@ void testCreateCampaign04() throws Exception { ContactAttemptConfiguration.F2F, List.of(visibility), List.of(), - List.of(), List.of()); CampaignCreateDto campaign2 = generateCampaign("campId", " ", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(visibility), List.of(), - List.of(), List.of()); List campaigns = List.of(campaign1, campaign2); for(CampaignCreateDto campaign : campaigns) { @@ -160,7 +158,6 @@ void testCreateCampaign05() throws Exception { ContactAttemptConfiguration.F2F, invalidCampaignVisibilities, List.of(), - List.of(), List.of()); mockMvc.perform(post(Constants.API_CAMPAIGN) .contentType(MediaType.APPLICATION_JSON) @@ -198,7 +195,6 @@ void testCreateCampaign07() throws Exception { ContactAttemptConfiguration.F2F, List.of(visibility), List.of(), - List.of(), List.of(communicationTemplate, duplicatedCommunicationTemplate)); mockMvc.perform(post(Constants.API_CAMPAIGN) @@ -226,16 +222,12 @@ public CampaignCreateDto generateDefaultCampaign() { 1721683263000L, 1721683264000L, 1721683265000L, true); - CommunicationInformationCampaignCreateDto communicationInformation = new CommunicationInformationCampaignCreateDto("OU-SOUTH", - "mail", - "tel"); ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); ReferentDto secondReferent = new ReferentDto("Dupont", "Jean", "1234567890", "PRIMARY"); return generateCampaign("campId", "An other campaign", "test.test@sdf.com", IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL, List.of(firstVisibility, secondVisibility), - List.of(communicationInformation), List.of(firstReferent, secondReferent), List.of(communicationTemplate1, communicationTemplate2)); } @@ -246,14 +238,12 @@ private CampaignCreateDto generateCampaign( ContactOutcomeConfiguration contactOutcomeConfiguration, ContactAttemptConfiguration contactAttemptConfiguration, List visibilities, - List communicationInformations, List referents, List communicationTemplates) { return new CampaignCreateDto(campaignId, campaignLabel, visibilities, - communicationInformations, communicationTemplates, referents, email, @@ -268,6 +258,7 @@ private VisibilityCampaignCreateDto generateVisibility(String organizationalUnit Long identificationDate, Long collectionStartDate, Long collectionEndDate, Long endDate, Boolean useLetterCommunication) { return new VisibilityCampaignCreateDto(managementDate, - interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit, useLetterCommunication); + interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, organizationalUnit, + useLetterCommunication, "mail", "tel"); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java index 98f67b30..983d1d75 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java @@ -52,7 +52,7 @@ void setup() { @Test @DisplayName("Should retrieve campaign") void testGetCampaign01() throws Exception { - CampaignResponseDto campaign = new CampaignResponseDto("campaign-id", "label", null, null, null, "email", + CampaignResponseDto campaign = new CampaignResponseDto("campaign-id", "label", null, null, "email", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.F2F); campaignService.setCampaignToRetrieve(campaign); diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java index a1a390b2..8d94399c 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java @@ -1,7 +1,6 @@ package fr.insee.pearljam.api.campaign.controller; import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; -import fr.insee.pearljam.api.campaign.dto.input.CommunicationInformationCampaignUpdateDto; import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignUpdateDto; import fr.insee.pearljam.api.controller.CampaignController; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; @@ -72,7 +71,6 @@ void testUpdateCampaign02() throws Exception { "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(), - List.of(), List.of()); mockMvc.perform(put(updatePath) .contentType(MediaType.APPLICATION_JSON) @@ -90,7 +88,8 @@ void testUpdateCampaign03() throws Exception { VisibilityCampaignUpdateDto visibility = generateVisibility(" ", 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, 1721683254000L, - 1721683255000L, true); + 1721683255000L, + true, "mail", "tel"); testUpdateExceptions(visibility, HttpStatus.BAD_REQUEST, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE); } @@ -114,7 +113,8 @@ void testUpdateCampaign06() throws Exception { VisibilityCampaignUpdateDto visibility = generateVisibility("ou-id", null, null, null, null, - null, null, true); + null, null, + true, "mail", "tel"); testUpdateExceptions(visibility, HttpStatus.BAD_REQUEST, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE); } @@ -135,7 +135,6 @@ private void testUpdateExceptions(VisibilityCampaignUpdateDto visibility, HttpSt "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(visibility), - List.of(), List.of()); mockMvc.perform(put(updatePath) .contentType(MediaType.APPLICATION_JSON) @@ -156,36 +155,28 @@ private CampaignUpdateDto generateDefaultCampaign() { 1721683263000L, 1721683264000L, 1721683265000L, - true); - - CommunicationInformationCampaignUpdateDto firstCommunication = generateCommunicationInformation("OU-SOUTH", + true, "mail", "tel"); + ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); ReferentDto secondReferent = new ReferentDto("Dupont", "Jean", "1234567890", "PRIMARY"); return generateCampaign("An other campaign", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(firstVisibility, secondVisibility), - List.of(firstCommunication), List.of(firstReferent, secondReferent)); } - private CommunicationInformationCampaignUpdateDto generateCommunicationInformation(String ouId, String mail, String tel) { - return new CommunicationInformationCampaignUpdateDto(ouId, mail, tel); - } - private CampaignUpdateDto generateCampaign(String campaignLabel, String email, IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, ContactAttemptConfiguration contactAttemptConfiguration, List visibilities, - List communicationInformations, List referents) { return new CampaignUpdateDto( campaignLabel, visibilities, - communicationInformations, referents, email, identificationConfiguration, @@ -198,15 +189,17 @@ private CampaignUpdateDto generateCampaign(String campaignLabel, private VisibilityCampaignUpdateDto generateDefaultVisibility() { return generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, - 1721683254000L, 1721683255000L, true); + 1721683254000L, 1721683255000L, + true, "mail", "tel"); } private VisibilityCampaignUpdateDto generateVisibility( String organizationalUnit, Long managementDate, Long interviewerDate, Long identificationDate, - Long collectionStartDate, Long collectionEndDate, Long endDate, Boolean useLetterCommunication) { + Long collectionStartDate, Long collectionEndDate, Long endDate, + Boolean useLetterCommunication, String mail, String tel) { return new VisibilityCampaignUpdateDto(managementDate, interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, - organizationalUnit, useLetterCommunication); + organizationalUnit, useLetterCommunication, mail, tel); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java deleted file mode 100644 index 9d336631..00000000 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CommunicationInformationControllerTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package fr.insee.pearljam.api.campaign.controller; - -import fr.insee.pearljam.api.campaign.dto.input.CommunicationInformationUpdateDto; -import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; -import fr.insee.pearljam.api.utils.JsonTestHelper; -import fr.insee.pearljam.api.utils.MockMvcTestUtils; -import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; -import fr.insee.pearljam.domain.campaign.service.dummy.CommunicationInformationFakeService; -import fr.insee.pearljam.domain.exception.CommunicationInformationNotFoundException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; - -class CommunicationInformationControllerTest { - - private MockMvc mockMvc; - private CommunicationInformationFakeService communicationInformationService; - private final String campaignId = "campaign-id"; - private final String organizationalUnitId = "ou-id"; - private final String updatePath = String.format("/api/campaign/%s/organizational-unit/%s/communication-information", campaignId, organizationalUnitId); - - @BeforeEach - void setup() { - communicationInformationService = new CommunicationInformationFakeService(); - AuthenticationUserFakeService authenticatedUserService = new AuthenticationUserFakeService(AuthenticatedUserTestHelper.AUTH_ADMIN); - CommunicationInformationController communicationInformationController = - new CommunicationInformationController(communicationInformationService, authenticatedUserService); - mockMvc = MockMvcBuilders - .standaloneSetup(communicationInformationController) - .setControllerAdvice(MockMvcTestUtils.createExceptionControllerAdvice()) - .build(); - } - - @Test - @DisplayName("Should return not found when communication information does not exist") - void testUpdateCommunicationInformation01() throws Exception { - communicationInformationService.setShouldThrowCommunicationInformationNotFoundException(true); - CommunicationInformationUpdateDto communicationInformationToUpdate = - new CommunicationInformationUpdateDto("mail", "0123456789"); - mockMvc.perform(put(updatePath) - .content(JsonTestHelper.toJson(communicationInformationToUpdate)) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, updatePath, CommunicationInformationNotFoundException.MESSAGE)); - } -} diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java index 9466ed44..aacd9324 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java @@ -56,11 +56,13 @@ void testGetVisibilities01() throws Exception { Visibility visibility1 = new Visibility(campaignId, organizationalUnitId, 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, true); + 1721683253000L, 1721683254000L, 1721683255000L, + true, "mail1", "tel1"); Visibility visibility2 = new Visibility(campaignId, "ou-id2", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, true); + 1721683253000L, 1721683254000L, 1721683255000L, + true, "mail2", "tel2"); List visibilities = List.of(visibility1, visibility2); visibilityService.save(visibility1); visibilityService.save(visibility2); @@ -95,7 +97,8 @@ void testUpdateVisibility01() throws Exception { Visibility visibility = new Visibility(campaignId, organizationalUnitId, 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, true); + 1721683253000L, 1721683254000L, 1721683255000L, + true, "mail", "tel"); visibilityService.save(visibility); VisibilityUpdateDto visibilityToUpdate = generateUpdateVisibility(); @@ -158,6 +161,7 @@ private VisibilityUpdateDto generateUpdateVisibility( Long identificationDate, Long collectionStartDate, Long collectionEndDate, Long endDate) { return new VisibilityUpdateDto(managementDate, - interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, true); + interviewerDate, identificationDate, collectionStartDate, collectionEndDate, endDate, + true, "mail", "tel"); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java index 75a127dc..e86854e7 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDtoTest.java @@ -22,10 +22,13 @@ void testToModel() { Long endDate = 1628277600000L; String organizationalUnit = "OU1"; String campaignId = "campaign-id"; + String mail = "mail"; + String tel = "tel"; VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto( managementStartDate, interviewerStartDate, identificationPhaseStartDate, - collectionStartDate, collectionEndDate, endDate, organizationalUnit, true); + collectionStartDate, collectionEndDate, endDate, organizationalUnit, + true, mail, tel); // When Visibility visibility = VisibilityCampaignCreateDto @@ -42,5 +45,7 @@ void testToModel() { assertThat(visibility.collectionEndDate()).isEqualTo(collectionEndDate); assertThat(visibility.endDate()).isEqualTo(endDate); assertThat(visibility.useLetterCommunication()).isTrue(); + assertThat(visibility.mail()).isEqualTo(mail); + assertThat(visibility.tel()).isEqualTo(tel); } } \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java index d1ec8b48..6ec2b214 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDtoTest.java @@ -15,8 +15,12 @@ class VisibilityCampaignUpdateDtoTest { void testToModel() { // Given String campaignId = "campaign1"; - VisibilityCampaignUpdateDto dto1 = new VisibilityCampaignUpdateDto(1L, 2L, 3L, 4L, 5L, 6L, "OU1", true); - VisibilityCampaignUpdateDto dto2 = new VisibilityCampaignUpdateDto(11L, 12L, 13L, 14L, 15L, 16L, "OU2", null); + VisibilityCampaignUpdateDto dto1 = new VisibilityCampaignUpdateDto(1L, 2L, + 3L, 4L, 5L, 6L, "OU1", + true, "mail1", "tel1"); + VisibilityCampaignUpdateDto dto2 = new VisibilityCampaignUpdateDto(11L, 12L, 13L, + 14L, 15L, 16L, "OU2", + null, "mail2", "tel2"); List dtoList = List.of(dto1, dto2); // When @@ -35,6 +39,8 @@ void testToModel() { assertThat(firstVisibility.collectionEndDate()).isEqualTo(5L); assertThat(firstVisibility.endDate()).isEqualTo(6L); assertThat(firstVisibility.useLetterCommunication()).isTrue(); + assertThat(firstVisibility.mail()).isEqualTo("mail1"); + assertThat(firstVisibility.tel()).isEqualTo("tel1"); Visibility lastVisibility = modelList.getLast(); assertThat(lastVisibility.campaignId()).isEqualTo(campaignId); @@ -46,5 +52,7 @@ void testToModel() { assertThat(lastVisibility.collectionEndDate()).isEqualTo(15L); assertThat(lastVisibility.endDate()).isEqualTo(16L); assertThat(lastVisibility.useLetterCommunication()).isNull(); + assertThat(lastVisibility.mail()).isEqualTo("mail2"); + assertThat(lastVisibility.tel()).isEqualTo("tel2"); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java index f1b722aa..bb38ec5b 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDtoTest.java @@ -20,10 +20,13 @@ void testToModel() { Long endDate = 1628277600000L; String campaignId = "campaign1"; String ouId = "OU1"; + String mail = "mail"; + String tel= "tel"; VisibilityUpdateDto dto = new VisibilityUpdateDto( managementStartDate, interviewerStartDate, identificationPhaseStartDate, - collectionStartDate, collectionEndDate, endDate, true); + collectionStartDate, collectionEndDate, endDate, + true, mail, tel); // When Visibility model = VisibilityUpdateDto.toModel(dto, campaignId, ouId); @@ -37,5 +40,7 @@ void testToModel() { assertThat(model.collectionStartDate()).isEqualTo(collectionStartDate); assertThat(model.collectionEndDate()).isEqualTo(collectionEndDate); assertThat(model.endDate()).isEqualTo(endDate); + assertThat(model.mail()).isEqualTo(mail); + assertThat(model.tel()).isEqualTo(tel); } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java index daf62bde..2f2cc863 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/VisibilityCampaignDtoTest.java @@ -14,8 +14,14 @@ class VisibilityCampaignDtoTest { @DisplayName("Should return dto objects from models") void testFromModel() { // Given - Visibility visibility1 = new Visibility("campaign-id", "OU1", 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); - Visibility visibility2 = new Visibility("campaign-id", "OU2", 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); + Visibility visibility1 = new Visibility("campaign-id", "OU1", 1627845600000L, + 1627932000000L, 1628018400000L, + 1628104800000L, 1628191200000L, 1628277600000L, + true, "mail1", "tel1"); + Visibility visibility2 = new Visibility("campaign-id", "OU2", 1627845600000L, + 1627932000000L, 1628018400000L, 1628104800000L, + 1628191200000L, 1628277600000L, + true, "mail2", "tel2"); List visibilityList = List.of(visibility1, visibility2); // When diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java index 15937001..e33eb8d8 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/model/VisibilityTest.java @@ -16,10 +16,10 @@ class VisibilityTest { void testMergeAndDateValidation() throws VisibilityHasInvalidDatesException { // Given Visibility currentVisibility = new Visibility("campaign1", "OU1", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true, "mail", "tel"); Visibility updateVisibility = new Visibility("campaign1", "OU1", - 1617933000000L, 1627933000000L, 1627934000000L, 1627935000000L, 1627936000000L, 1628277601000L, false); + 1617933000000L, 1627933000000L, 1627934000000L, 1627935000000L, 1627936000000L, 1628277601000L, false, "mail1", "tel1"); // When Visibility mergedVisibility = Visibility.merge(currentVisibility, updateVisibility); @@ -34,6 +34,8 @@ void testMergeAndDateValidation() throws VisibilityHasInvalidDatesException { assertThat(mergedVisibility.collectionEndDate()).isEqualTo(1627936000000L); assertThat(mergedVisibility.endDate()).isEqualTo(1628277601000L); assertThat(mergedVisibility.useLetterCommunication()).isFalse(); + assertThat(mergedVisibility.mail()).isEqualTo("mail1"); + assertThat(mergedVisibility.tel()).isEqualTo("tel1"); } @Test @@ -41,10 +43,11 @@ void testMergeAndDateValidation() throws VisibilityHasInvalidDatesException { void testMergeNull() throws VisibilityHasInvalidDatesException { // Given Visibility currentVisibility = new Visibility("campaign1", "OU1", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); + 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true, "mail1", "tel1"); Visibility updateVisibility = new Visibility("campaign1", "OU1", - null, null, null, null, null, null, null); + null, null, null, null, + null, null, null, null, null); // When Visibility mergedVisibility = Visibility.merge(currentVisibility, updateVisibility); @@ -58,6 +61,8 @@ void testMergeNull() throws VisibilityHasInvalidDatesException { assertThat(mergedVisibility.collectionStartDate()).isEqualTo(1628104800000L); assertThat(mergedVisibility.collectionEndDate()).isEqualTo(1628191200000L); assertThat(mergedVisibility.endDate()).isEqualTo(1628277600000L); + assertThat(mergedVisibility.mail()).isEqualTo("mail1"); + assertThat(mergedVisibility.tel()).isEqualTo("tel1"); } @Test @@ -65,10 +70,10 @@ void testMergeNull() throws VisibilityHasInvalidDatesException { void testMergeThrowsExceptionForInvalidDates() { // Given Visibility currentVisibility = new Visibility("campaign1", "OU1", - 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); + 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true, "mail", "tel"); Visibility updateVisibility = new Visibility("campaign1", "OU1", - 1227845600000L, 1327932000001L, 1327932000002L, 1327932000003L, 1327932000004L, 1327932000004L, true); + 1227845600000L, 1327932000001L, 1327932000002L, 1327932000003L, 1327932000004L, 1327932000004L, true, null, null); // When & Then assertThatThrownBy(() -> Visibility.merge(currentVisibility, updateVisibility)) @@ -88,12 +93,12 @@ void testMergeThrowsExceptionForInvalidDates() { void testMergeThrowsExceptionForInvalidDates2(String managementStartDate, String interviwerStartDate, String identificationPhaseStartDate, String collectionStartDate, String collectionEndDate, String endDate) { // Given Visibility currentVisibility = new Visibility("campaign1", "OU1", - 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); + 1327845600000L, 1327932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true, "mail", "tel"); Visibility updateVisibility = new Visibility("campaign1", "OU1", getLong(managementStartDate), getLong(interviwerStartDate), getLong(identificationPhaseStartDate), getLong(collectionStartDate), - getLong(collectionEndDate), getLong(endDate), true); + getLong(collectionEndDate), getLong(endDate), true, null, null); // When & Then assertThatThrownBy(() -> Visibility.merge(currentVisibility, updateVisibility)) diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java index 83ae7584..a082ada3 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java @@ -46,11 +46,13 @@ class CampaignServiceImplTest { private final Visibility existingVisibility1 = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, true); + 1721683253000L, 1721683254000L, 1721683255000L, + true, "mail1", "tel1"); private final Visibility existingVisibility2 = new Visibility(existingCampaign.getId(), "OU2", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, true); + 1721683253000L, 1721683254000L, 1721683255000L, + true, "mail2", "tel2"); @BeforeEach void setup() { @@ -80,15 +82,13 @@ void setup() { SurveyUnitFakeService surveyUnitService = new SurveyUnitFakeService(); PreferenceFakeService preferenceService = new PreferenceFakeService(); ReferentFakeService referentService = new ReferentFakeService(); - CommunicationInformationFakeService communicationInformationService = new CommunicationInformationFakeService(); campaignService = new CampaignServiceImpl( campaignRepository, userRepository, surveyUnitRepository, organizationUnitRepository, messageRepository, - userService, utilsService, surveyUnitService, preferenceService, referentService, visibilityService, dateService, - communicationInformationService); + userService, utilsService, surveyUnitService, preferenceService, referentService, visibilityService, dateService); } - // TODO : handle referent & communication informations + // TODO : handle referent @Test @DisplayName("Should create a new campaign successfully") void shouldCreateNewCampaign() throws CampaignAlreadyExistException, OrganizationalUnitNotFoundException, VisibilityHasInvalidDatesException { @@ -96,12 +96,12 @@ void shouldCreateNewCampaign() throws CampaignAlreadyExistException, Organizatio CommunicationTemplateCreateDto communicationTemplateDto = new CommunicationTemplateCreateDto("meshuggahId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto(1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId(), true); + 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId(), + true, "mail", "tel"); CampaignCreateDto campaignCreateDto = new CampaignCreateDto( campaignId, "Campaign 1", List.of(visibilityDto), - null, List.of(communicationTemplateDto), null, null, @@ -135,7 +135,8 @@ void shouldCreateNewCampaign() throws CampaignAlreadyExistException, Organizatio void shouldThrowCampaignAlreadyExistExceptionWhenCreatingExistingCampaign() { String campaignId = existingCampaign.getId(); VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto(1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId(), true); + 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId(), + true, "mail", "tel"); CampaignCreateDto existingCampaignDto = new CampaignCreateDto( campaignId, "Existing campaign", @@ -143,7 +144,6 @@ void shouldThrowCampaignAlreadyExistExceptionWhenCreatingExistingCampaign() { null, null, null, - null, IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F @@ -154,7 +154,7 @@ void shouldThrowCampaignAlreadyExistExceptionWhenCreatingExistingCampaign() { .hasMessage(CampaignAlreadyExistException.MESSAGE); } - // TODO : handle referents & communication infos + // TODO : handle referents @Test @DisplayName("Should update an existing campaign successfully") void shouldUpdateExistingCampaign() throws CampaignNotFoundException, VisibilityNotFoundException, VisibilityHasInvalidDatesException, OrganizationalUnitNotFoundException { @@ -162,12 +162,13 @@ void shouldUpdateExistingCampaign() throws CampaignNotFoundException, Visibility // Given VisibilityCampaignUpdateDto visibilityDto = new VisibilityCampaignUpdateDto(1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId(), true); + 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId(), + true, "mail1", "tel1"); CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", List.of(visibilityDto), List.of(), - null, "emailUpdated@email.com", + "emailUpdated@email.com", IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -203,7 +204,7 @@ void shouldNotUpdateEmailIfNull(String emailToUpdate) throws CampaignNotFoundExc CampaignUpdateDto updateDto = new CampaignUpdateDto("campaign to update", null, null, - null, emailToUpdate, + emailToUpdate, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -227,7 +228,6 @@ void shouldNotUpdateVisibilitiesIfNull() throws CampaignNotFoundException, Visib null, null, null, - null, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -250,7 +250,6 @@ void shouldNotUpdateReferentsIfNull() throws VisibilityHasInvalidDatesException, null, null, null, - null, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -272,7 +271,6 @@ void shouldThrowCampaignNotFoundExceptionWhenUpdatingNonExistentCampaign() { null, null, null, - null, IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -287,11 +285,13 @@ void shouldReturnTrueIfCampaignIsOngoing() throws CampaignNotFoundException { Visibility ongoingVisibility = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, - 1628191200000L, Instant.now().plusSeconds(10000).toEpochMilli(), true); + 1628191200000L, Instant.now().plusSeconds(10000).toEpochMilli(), + true, "mail", "tel"); Visibility closedVisibility = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, - 1628191200000L, Instant.now().toEpochMilli(), true); + 1628191200000L, Instant.now().toEpochMilli(), + true, "mail", "tel"); visibilityService.save(ongoingVisibility); visibilityService.save(closedVisibility); @@ -306,11 +306,13 @@ void shouldReturnFalseIfCampaignIsNotOngoing() throws CampaignNotFoundException Visibility closedVisibility1 = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, - 1628191200000L, Instant.now().minusSeconds(3600).toEpochMilli(), true); + 1628191200000L, Instant.now().minusSeconds(3600).toEpochMilli(), + true, "mail", "tel"); Visibility closedVisibility2 = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, - 1628191200000L, Instant.now().toEpochMilli(), true); + 1628191200000L, Instant.now().toEpochMilli(), + true, "mail", "tel"); visibilityService.save(closedVisibility1); visibilityService.save(closedVisibility2); diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java index f1481aea..3411b78e 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/VisibilityServiceImplTest.java @@ -26,11 +26,17 @@ void setUp() { visibilityRepository = new VisibilityFakeRepository(); visibilityService = new VisibilityServiceImpl(visibilityRepository); visibility1 = new Visibility("campaign1", "OU1", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); + 1627845600000L, 1627932000000L, 1628018400000L, + 1628104800000L, 1628191200000L, 1628277600000L, + true, "mail1", "tel1"); visibility2 = new Visibility("campaign2", "OU2", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); + 1627845600000L, 1627932000000L, 1628018400000L, + 1628104800000L, 1628191200000L, 1628277600000L, + true, "mail2", "tel2"); visibility3 = new Visibility("campaign1", "OU2", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); + 1627845600000L, 1627932000000L, 1628018400000L, + 1628104800000L, 1628191200000L, 1628277600000L, + true, "mail3", "tel3"); visibilityRepository.save(visibility1); visibilityRepository.save(visibility2); visibilityRepository.save(visibility3); @@ -52,7 +58,8 @@ void shouldReturnVisibilitiesForValidCampaignId() { void shouldUpdateVisibilityWithValidData() throws VisibilityNotFoundException, VisibilityHasInvalidDatesException { Visibility visibilityToUpdate = new Visibility(visibility1.campaignId(), visibility1.organizationalUnitId(), 1627845600001L, 1627932000001L, 1628018400001L, - 1628104800001L, 1628191200001L, 1628277600001L, false); + 1628104800001L, 1628191200001L, 1628277600001L, + false, "mailUpdate", "telUpdate"); visibilityService.updateVisibility(visibilityToUpdate); @@ -67,7 +74,8 @@ void shouldUpdateVisibilityWithValidData() throws VisibilityNotFoundException, V void shouldThrowVisibilityNotFoundExceptionIfVisibilityToUpdateDoesNotExist() { Visibility visibilityToUpdate = new Visibility("invalid-campaign", "invalid-ou", 1627845600000L, 1627932000000L, 1628018400000L, - 1628104800000L, 1628191200000L, 1628277600000L, true); + 1628104800000L, 1628191200000L, 1628277600000L, + true, "mailUpdate", "telUpdate"); assertThatThrownBy(() -> visibilityService.updateVisibility(visibilityToUpdate)) .isInstanceOf(VisibilityNotFoundException.class) diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java deleted file mode 100644 index df8bd3f7..00000000 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CommunicationInformationFakeService.java +++ /dev/null @@ -1,33 +0,0 @@ -package fr.insee.pearljam.domain.campaign.service.dummy; - -import fr.insee.pearljam.api.domain.Campaign; -import fr.insee.pearljam.domain.campaign.model.communication.CommunicationInformation; -import fr.insee.pearljam.domain.campaign.port.userside.CommunicationInformationService; -import fr.insee.pearljam.domain.exception.CampaignNotFoundException; -import fr.insee.pearljam.domain.exception.CommunicationInformationNotFoundException; -import fr.insee.pearljam.domain.exception.OrganizationalUnitNotFoundException; -import lombok.Setter; - -import java.util.List; - -public class CommunicationInformationFakeService implements CommunicationInformationService { - @Setter - private boolean shouldThrowCommunicationInformationNotFoundException = false; - - @Override - public List findCommunicationInformations(String campaignId) throws CampaignNotFoundException { - return List.of(); - } - - @Override - public void setCommunicationInformations(List communicationInformations, Campaign campaign) throws OrganizationalUnitNotFoundException, CampaignNotFoundException { - // not used at this moment - } - - @Override - public void updateCommunicationInformation(CommunicationInformation communicationInformationToUpdate) { - if(shouldThrowCommunicationInformationNotFoundException) { - throw new CommunicationInformationNotFoundException(); - } - } -} diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java index 32fb6c53..e55fed93 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/VisibilityFakeRepository.java @@ -50,7 +50,9 @@ public void updateDates(Visibility visibilityToUpdate) throws VisibilityNotFound @Override public Visibility getVisibilityBySurveyUnitId(String surveyUnitId) { return new Visibility("campaign1", "OU1", - 1627845600000L, 1627932000000L, 1628018400000L, 1628104800000L, 1628191200000L, 1628277600000L, true); + 1627845600000L, 1627932000000L, 1628018400000L, + 1628104800000L, 1628191200000L, 1628277600000L, + true, "mail", "tel"); } // Additional methods for testing purposes diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java index e38551aa..46e01280 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java @@ -53,7 +53,7 @@ void setup() { campaign = new Campaign("campaignId", "label", null, null, null,null); ou = new OrganizationUnit("ouId", "label-ou", OrganizationUnitType.LOCAL); Visibility visibility = new Visibility(campaign.getId(), ou.getId(), null, null, - null, null, null, null, true); + null, null, null, null, true, "mail", "tel"); visibilityFakeService.save(visibility); surveyUnit = new SurveyUnit("id", true, true, null, null, campaign, null, ou, null); @@ -121,7 +121,7 @@ void testUpdateCommunication02() { visibilityFakeService.clearVisibilities(); communicationTemplateFakeRepository.clearCommunicationTemplates(); Visibility visibility = new Visibility(campaign.getId(), ou.getId(), null, null, - null, null, null, null, false); + null, null, null, null, false, "mail", "tel"); communicationTemplate = new CommunicationTemplate(3L, "messhId", CommunicationMedium.LETTER, CommunicationType.NOTICE); communicationTemplateFakeRepository.save(communicationTemplate); visibilityFakeService.save(visibility); diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java index 52e802f0..4699021f 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java @@ -69,10 +69,10 @@ void setup() { organizationUnit2 = organizationUnitRepository.save(organizationUnit2); visibilityDB1 = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 10L, 20L, - 11L, 30L, 12L, 40L, true); + 11L, 30L, 12L, 40L, true, "mail1", "tel1"); visibilityDB2 = new VisibilityDB(new VisibilityDBId(organizationUnit2.getId(), campaign.getId()), organizationUnit2, campaign, 11L, 12L, - 13L, 14L, 15L, 16L, true); + 13L, 14L, 15L, 16L, true, "mail2", "tel2"); List visibilities = new ArrayList<>(); visibilities.add(visibilityDB1); visibilities.add(visibilityDB2); @@ -85,7 +85,7 @@ void setup() { void testUpdateDatesVisibilities01() throws VisibilityNotFoundException { Visibility visibilityToUpdate = new Visibility(campaign.getId(), organizationUnit.getId(), 21L, 22L, 23L, - 24L, 25L, 26L, true); + 24L, 25L, 26L, true, "mail", "tel"); visibilityDaoAdapter.updateDates(visibilityToUpdate); Optional campaignOptional = campaignRepository.findById(campaign.getId()); @@ -109,7 +109,7 @@ void testUpdateDatesVisibilities01() throws VisibilityNotFoundException { void testUpdateDatesVisibility02() { Visibility visibilityToUpdate = new Visibility(campaign.getId(), "invalid-id", 21L, 22L, 23L, - 24L, 25L, 26L, true); + 24L, 25L, 26L, true, "mail", "tel"); assertThatThrownBy(() -> visibilityDaoAdapter.updateDates(visibilityToUpdate)) .isInstanceOf(VisibilityNotFoundException.class) @@ -186,6 +186,8 @@ private void assertEquals(Visibility visibilityToCheck, VisibilityDB visibilityD assertThat(visibilityToCheck.collectionStartDate()).isEqualTo(visibilityDBExpected.getCollectionStartDate()); assertThat(visibilityToCheck.collectionEndDate()).isEqualTo(visibilityDBExpected.getCollectionEndDate()); assertThat(visibilityToCheck.endDate()).isEqualTo(visibilityDBExpected.getEndDate()); + assertThat(visibilityToCheck.mail()).isEqualTo(visibilityDBExpected.getMail()); + assertThat(visibilityToCheck.tel()).isEqualTo(visibilityDBExpected.getTel()); } private void assertEquals(VisibilityDB visibilityDBToCheck, Visibility visibilityExpected) { @@ -197,6 +199,8 @@ private void assertEquals(VisibilityDB visibilityDBToCheck, Visibility visibilit assertThat(visibilityDBToCheck.getCollectionStartDate()).isEqualTo(visibilityExpected.collectionStartDate()); assertThat(visibilityDBToCheck.getCollectionEndDate()).isEqualTo(visibilityExpected.collectionEndDate()); assertThat(visibilityDBToCheck.getEndDate()).isEqualTo(visibilityExpected.endDate()); + assertThat(visibilityDBToCheck.getMail()).isEqualTo(visibilityExpected.mail()); + assertThat(visibilityDBToCheck.getTel()).isEqualTo(visibilityExpected.tel()); } private void assertEquals(VisibilityDB visibilityDBToCheck, VisibilityDB visibilityExpected) { @@ -208,5 +212,7 @@ private void assertEquals(VisibilityDB visibilityDBToCheck, VisibilityDB visibil assertThat(visibilityDBToCheck.getCollectionStartDate()).isEqualTo(visibilityExpected.getCollectionStartDate()); assertThat(visibilityDBToCheck.getCollectionEndDate()).isEqualTo(visibilityExpected.getCollectionEndDate()); assertThat(visibilityDBToCheck.getEndDate()).isEqualTo(visibilityExpected.getEndDate()); + assertThat(visibilityDBToCheck.getMail()).isEqualTo(visibilityExpected.getMail()); + assertThat(visibilityDBToCheck.getTel()).isEqualTo(visibilityExpected.getTel()); } } diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java index 7bbbd03f..5c55a02e 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java @@ -25,7 +25,7 @@ void setup() { void testToModel01() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L, true); + 3L, 4L, 5L, 6L, true, "mail", "tel"); Visibility visibility = VisibilityDB.toModel(visibilityDB); assertThat(visibility.campaignId()).isEqualTo(visibilityDB.getVisibilityId().getCampaignId()); @@ -37,13 +37,15 @@ void testToModel01() { assertThat(visibility.collectionEndDate()).isEqualTo(visibilityDB.getCollectionEndDate()); assertThat(visibility.endDate()).isEqualTo(visibilityDB.getEndDate()); assertThat(visibility.useLetterCommunication().booleanValue()).isEqualTo(visibilityDB.isUseLetterCommunication()); + assertThat(visibility.mail()).isEqualTo(visibilityDB.getMail()); + assertThat(visibility.tel()).isEqualTo(visibilityDB.getTel()); } @Test @DisplayName("Should return entity object") void testFromModel01() { Visibility visibility = generateVisibility(1L, 2L, 3L, - 4L, 5L, 6L, true); + 4L, 5L, 6L, true, "mail", "tel"); VisibilityDB visibilityDB = VisibilityDB.fromModel(visibility, campaign, organizationUnit); assertThat(visibilityDB.getVisibilityId().getCampaignId()).isEqualTo(visibility.campaignId()); @@ -57,16 +59,18 @@ void testFromModel01() { assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibility.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isEqualTo(visibility.endDate()); assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibility.useLetterCommunication().booleanValue()); + assertThat(visibilityDB.getMail()).isEqualTo(visibility.mail()); + assertThat(visibilityDB.getTel()).isEqualTo(visibility.tel()); } @Test - @DisplayName("Should update dates from entity object") + @DisplayName("Should update infos from entity object") void testUpdate01() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L, true); + 3L, 4L, 5L, 6L, true, "mail", "tel"); Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, - 14L, 15L, 16L, false); + 14L, 15L, 16L, false, "mailUpdate", "telUpdate"); visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); @@ -76,6 +80,8 @@ void testUpdate01() { assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibilityToUpdate.useLetterCommunication().booleanValue()); + assertThat(visibilityDB.getMail()).isEqualTo(visibilityToUpdate.mail()); + assertThat(visibilityDB.getTel()).isEqualTo(visibilityToUpdate.tel()); } @Test @@ -83,9 +89,9 @@ void testUpdate01() { void testUpdate02() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L, true); + 3L, 4L, 5L, 6L, true, "mail", "tel"); Visibility visibilityToUpdate = generateVisibility(null, 12L, 13L, - 14L, 15L, 16L, true); + 14L, 15L, 16L, true, "mail", "tel"); visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isNotNull(); @@ -95,6 +101,8 @@ void testUpdate02() { assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibilityToUpdate.useLetterCommunication().booleanValue()); + assertThat(visibilityDB.getMail()).isEqualTo(visibilityToUpdate.mail()); + assertThat(visibilityDB.getTel()).isEqualTo(visibilityToUpdate.tel()); } @Test @@ -102,9 +110,9 @@ void testUpdate02() { void testUpdate03() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L, true); + 3L, 4L, 5L, 6L, true, "mail", "tel"); Visibility visibilityToUpdate = generateVisibility(11L, null, 13L, - 14L, 15L, 16L, true); + 14L, 15L, 16L, true, "mail", "tel"); visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); @@ -114,6 +122,8 @@ void testUpdate03() { assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibilityToUpdate.useLetterCommunication().booleanValue()); + assertThat(visibilityDB.getMail()).isEqualTo(visibilityToUpdate.mail()); + assertThat(visibilityDB.getTel()).isEqualTo(visibilityToUpdate.tel()); } @Test @@ -121,9 +131,9 @@ void testUpdate03() { void testUpdate04() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L, true); + 3L, 4L, 5L, 6L, true, "mail", "tel"); Visibility visibilityToUpdate = generateVisibility(11L, 12L, null, - 14L, 15L, 16L, true); + 14L, 15L, 16L, true, "mail", "tel"); visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); @@ -132,6 +142,8 @@ void testUpdate04() { assertThat(visibilityDB.getCollectionStartDate()).isEqualTo(visibilityToUpdate.collectionStartDate()); assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); + assertThat(visibilityDB.getMail()).isEqualTo(visibilityToUpdate.mail()); + assertThat(visibilityDB.getTel()).isEqualTo(visibilityToUpdate.tel()); } @Test @@ -139,9 +151,9 @@ void testUpdate04() { void testUpdate05() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L, true); + 3L, 4L, 5L, 6L, true, "mail", "tel"); Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, - null, 15L, 16L, true); + null, 15L, 16L, true, "mail", "tel"); visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); @@ -157,9 +169,9 @@ void testUpdate05() { void testUpdate06() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L, true); + 3L, 4L, 5L, 6L, true, "mail", "tel"); Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, - 14L, null, 16L, true); + 14L, null, 16L, true, "mail", "tel"); visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); @@ -169,6 +181,8 @@ void testUpdate06() { assertThat(visibilityDB.getCollectionEndDate()).isNotNull(); assertThat(visibilityDB.getEndDate()).isEqualTo(visibilityToUpdate.endDate()); assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibilityToUpdate.useLetterCommunication().booleanValue()); + assertThat(visibilityDB.getMail()).isEqualTo(visibilityToUpdate.mail()); + assertThat(visibilityDB.getTel()).isEqualTo(visibilityToUpdate.tel()); } @Test @@ -176,9 +190,9 @@ void testUpdate06() { void testUpdate07() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L, true); + 3L, 4L, 5L, 6L, true, "mail", "tel"); Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, - 14L, 15L, null, true); + 14L, 15L, null, true, "mail", "tel"); visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); @@ -188,16 +202,18 @@ void testUpdate07() { assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isNotNull(); assertThat(visibilityDB.isUseLetterCommunication()).isEqualTo(visibilityToUpdate.useLetterCommunication().booleanValue()); + assertThat(visibilityDB.getMail()).isEqualTo(visibilityToUpdate.mail()); + assertThat(visibilityDB.getTel()).isEqualTo(visibilityToUpdate.tel()); } @Test - @DisplayName("Should not update communication usage") + @DisplayName("Should not update communication informations") void testUpdate08() { VisibilityDB visibilityDB = new VisibilityDB(new VisibilityDBId(organizationUnit.getId(), campaign.getId()), organizationUnit, campaign, 1L, 2L, - 3L, 4L, 5L, 6L, false); + 3L, 4L, 5L, 6L, false, "mail", "tel"); Visibility visibilityToUpdate = generateVisibility(11L, 12L, 13L, - 14L, 15L, null, null); + 14L, 15L, null, null, null, null); visibilityDB.update(visibilityToUpdate); assertThat(visibilityDB.getManagementStartDate()).isEqualTo(visibilityToUpdate.managementStartDate()); @@ -207,12 +223,15 @@ void testUpdate08() { assertThat(visibilityDB.getCollectionEndDate()).isEqualTo(visibilityToUpdate.collectionEndDate()); assertThat(visibilityDB.getEndDate()).isNotNull(); assertThat(visibilityDB.isUseLetterCommunication()).isFalse(); + assertThat(visibilityDB.getMail()).isEqualTo("mail"); + assertThat(visibilityDB.getTel()).isEqualTo("tel"); } private Visibility generateVisibility(Long managementStartDate, Long interviewerStartDate, Long identificationPhaseStartDate, - Long collectionStartDate, Long collectionEndDate, Long endDate, Boolean useCommunication) { + Long collectionStartDate, Long collectionEndDate, Long endDate, Boolean useLetterCommunication, + String mail, String tel) { return new Visibility(campaign.getId(), organizationUnit.getId(), managementStartDate, interviewerStartDate, - identificationPhaseStartDate, collectionStartDate, collectionEndDate, endDate, useCommunication); + identificationPhaseStartDate, collectionStartDate, collectionEndDate, endDate, useLetterCommunication, mail, tel); } } diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index b9a16bbf..671726d4 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -7,7 +7,6 @@ import fr.insee.pearljam.api.utils.ScriptConstants; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; import org.junit.jupiter.api.DisplayName; @@ -69,7 +68,9 @@ void testGetCampaign() throws Exception { "collectionStartDate":1719225354304, "collectionEndDate":1721903754305, "endDate":1724582154306, - "useLetterCommunication": true + "useLetterCommunication": true, + "mail": "north-simpsons@nooneknows.fr", + "tel": "0321234567" }, { "organizationalUnit":"OU-SOUTH", @@ -79,14 +80,9 @@ void testGetCampaign() throws Exception { "collectionStartDate":1719225354314, "collectionEndDate":1721903754315, "endDate":1724582154316, - "useLetterCommunication": false - } - ], - "communicationInformations":[ - { - "organizationalUnit":"OU-NORTH", - "mail":"north-simpsons@nooneknows.fr", - "tel":"0321234567" + "useLetterCommunication": false, + "mail": "south-simpsons@nooneknows.fr", + "tel": "" } ], "referents":[ @@ -124,7 +120,9 @@ void testCreateCampaign() throws Exception { "collectionEndDate":1721683254000, "endDate":1721683255000, "organizationalUnit":"OU-NORTH", - "useLetterCommunication": true + "useLetterCommunication": true, + "mail": "mail1", + "tel": "tel1" }, { "managementStartDate":1721683260000, @@ -134,7 +132,9 @@ void testCreateCampaign() throws Exception { "collectionEndDate":1721683264000, "endDate":1721683265000, "organizationalUnit":"OU-SOUTH", - "useLetterCommunication": false + "useLetterCommunication": false, + "mail": "mail2", + "tel": "tel2" } ], "referents":[ @@ -151,17 +151,6 @@ void testCreateCampaign() throws Exception { "role":"PRIMARY" } ], - "communicationInformations": [ - { - "organizationalUnit": "OU-NORTH", - "mail": "mail1", - "tel": "tel1" - }, - { - "organizationalUnit":"OU-SOUTH", - "mail": "mail2" - } - ], "communicationTemplates": [ { "meshuggahId": "meshId1", @@ -202,10 +191,10 @@ void testCreateCampaign() throws Exception { assertThat(campaignCreated.getVisibilities()) .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, - 1721683253000L, 1721683254000L, 1721683255000L, true)) + 1721683253000L, 1721683254000L, 1721683255000L, true, "mail1", "tel1")) .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-SOUTH", 1721683260000L, 1721683261000L, 1721683262000L, - 1721683263000L, 1721683264000L, 1721683265000L, false)); + 1721683263000L, 1721683264000L, 1721683265000L, false, "mail2", "tel2")); assertThat(campaignCreated.getCommunicationTemplates()).hasSize(3); assertThat(campaignCreated.getCommunicationTemplates()) @@ -216,19 +205,6 @@ void testCreateCampaign() throws Exception { .anySatisfy(communicationTemplateToCheck -> assertCommunicationTemplate(communicationTemplateToCheck, campaignId, "meshId3", CommunicationMedium.LETTER, CommunicationType.NOTICE)); - assertThat(campaignCreated.getCommunicationInformations()).hasSize(2); - assertThat(campaignCreated.getCommunicationInformations()) - .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, - campaignId, - "OU-NORTH", - "mail1", - "tel1")) - .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, - campaignId, - "OU-SOUTH", - "mail2", - null)); - assertThat(campaignCreated.getReferents()).hasSize(2); assertThat(campaignCreated.getReferents()) @@ -246,17 +222,6 @@ private void assertCommunicationTemplate(CommunicationTemplateDB communicationTe assertThat(communicationTemplateToCheck.getMedium()).isEqualTo(medium); } - private void assertCommunicationInformation(CommunicationInformationDB communicationInformationToCheck, - String campaignId, - String organizationalUnitId, - String mail, - String tel) { - assertThat(communicationInformationToCheck.getCampaign().getId()).isEqualTo(campaignId); - assertThat(communicationInformationToCheck.getOrganizationUnit().getId()).isEqualTo(organizationalUnitId); - assertThat(communicationInformationToCheck.getTel()).isEqualTo(tel); - assertThat(communicationInformationToCheck.getMail()).isEqualTo(mail); - } - @Test @DisplayName("Should update campaign") @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) @@ -275,7 +240,9 @@ void testUpdateCampaign() throws Exception { "collectionEndDate":1721683254000, "endDate":1721683255000, "organizationalUnit":"OU-NORTH", - "useLetterCommunication": false + "useLetterCommunication": false, + "mail": "mail1", + "tel": "tel1" }, { "managementStartDate":1721683260000, @@ -285,17 +252,7 @@ void testUpdateCampaign() throws Exception { "collectionEndDate":1721683264000, "endDate":1721683265000, "organizationalUnit":"OU-SOUTH", - "useLetterCommunication": true - } - ], - "communicationInformations": [ - { - "organizationalUnit": "OU-NORTH", - "mail": "mail1", - "tel": "tel1" - }, - { - "organizationalUnit": "OU-SOUTH", + "useLetterCommunication": true, "mail": "mail2", "tel": "tel2" } @@ -338,23 +295,11 @@ void testUpdateCampaign() throws Exception { .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, - 1721683254000L, 1721683255000L, false)) + 1721683254000L, 1721683255000L, false, "mail1", "tel1")) .anySatisfy(visibilityToCheck -> assertVisibility(visibilityToCheck, campaignId, "OU-SOUTH", 1721683260000L, 1721683261000L, 1721683262000L, 1721683263000L, - 1721683264000L, 1721683265000L, true)); - assertThat(campaignUpdated.getCommunicationInformations()).hasSize(2); - assertThat(campaignUpdated.getCommunicationInformations()) - .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, - campaignId, - "OU-NORTH", - "mail1", - "tel1")) - .anySatisfy(communicationInformationToCheck -> assertCommunicationInformation(communicationInformationToCheck, - campaignId, - "OU-SOUTH", - "mail2", - "tel2")); + 1721683264000L, 1721683265000L, true, "mail2", "tel2")); assertThat(campaignUpdated.getReferents()).hasSize(2); assertThat(campaignUpdated.getReferents()) @@ -382,7 +327,7 @@ void testDeleteCampaign() throws Exception { private void assertVisibility(VisibilityDB visibilityToCheck, String campaignId, String organizationUnitId, long managementStartDate, long interviewerStartDate, long identificationPhaseStartDate, long collectionStartDate, - long collectionEndDate, long endDate, boolean useLetterCommunication) { + long collectionEndDate, long endDate, boolean useLetterCommunication, String mail, String tel) { assertThat(visibilityToCheck.getCampaign().getId()).isEqualTo(campaignId); assertThat(visibilityToCheck.getOrganizationUnit().getId()).isEqualTo(organizationUnitId); assertThat(visibilityToCheck.getManagementStartDate()).isEqualTo(managementStartDate); @@ -392,6 +337,8 @@ private void assertVisibility(VisibilityDB visibilityToCheck, String campaignId, assertThat(visibilityToCheck.getCollectionEndDate()).isEqualTo(collectionEndDate); assertThat(visibilityToCheck.getEndDate()).isEqualTo(endDate); assertThat(visibilityToCheck.isUseLetterCommunication()).isEqualTo(useLetterCommunication); + assertThat(visibilityToCheck.getMail()).isEqualTo(mail); + assertThat(visibilityToCheck.getTel()).isEqualTo(tel); } private void assertReferent(Referent referentToCheck, String campaignId, String role, String lastName, diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java deleted file mode 100644 index 45b631a7..00000000 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationInformationIT.java +++ /dev/null @@ -1,89 +0,0 @@ -package fr.insee.pearljam.integration.campaign; - -import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; -import fr.insee.pearljam.api.utils.ScriptConstants; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDB; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationInformationDBId; -import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationInformationJpaRepository; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.transaction.annotation.Transactional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@ActiveProfiles(profiles = {"auth", "test"}) -@AutoConfigureMockMvc -@ContextConfiguration -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@Transactional -class CommunicationInformationIT { - @Autowired - private MockMvc mockMvc; - - @Autowired - private CommunicationInformationJpaRepository communicationInformationRepository; - - @Test - void testGetCommunicationInformations() throws Exception { - MvcResult mvcResult = mockMvc.perform( - get("/api/campaign/SIMPSONS2020X00/communication-informations") - .with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) - .andReturn(); - - String resultContent = mvcResult.getResponse().getContentAsString(); - String expectedResult = """ - [ - { - "organizationalUnit": "OU-NORTH", - "mail": "north-simpsons@nooneknows.fr", - "tel": "0321234567" - } - ]"""; - JSONAssert.assertEquals(resultContent, expectedResult, JSONCompareMode.NON_EXTENSIBLE); - } - - @Test - @DisplayName("Should update communication information") - @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) - void testUpdateCommunicationInformation() throws Exception { - String organizationalUnitId = "OU-NORTH"; - String campaignId = "SIMPSONS2020X00"; - String updatePath = String.format("/api/campaign/%s/organizational-unit/%s/communication-information", campaignId, organizationalUnitId); - String content = """ - { - "mail": "newMail", - "tel": "newTel" - }"""; - - mockMvc.perform(put(updatePath) - .with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)) - .content(content) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - - CommunicationInformationDB communicationDBToCheck = communicationInformationRepository.getReferenceById(new CommunicationInformationDBId(organizationalUnitId, campaignId)); - - assertThat(communicationDBToCheck.getCampaign().getId()).isEqualTo(campaignId); - assertThat(communicationDBToCheck.getOrganizationUnit().getId()).isEqualTo(organizationalUnitId); - assertThat(communicationDBToCheck.getMail()).isEqualTo("newMail"); - assertThat(communicationDBToCheck.getTel()).isEqualTo("newTel"); - } -} diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java index 594889bd..d2efa74a 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/VisibilityIT.java @@ -61,7 +61,9 @@ void testGetVisibilities() throws Exception { "collectionStartDate":1719225354304, "collectionEndDate":1721903754305, "endDate":1724582154306, - "useLetterCommunication": true + "useLetterCommunication": true, + "mail": "north-simpsons@nooneknows.fr", + "tel": "0321234567" }, { "organizationalUnit":"OU-SOUTH", @@ -71,7 +73,9 @@ void testGetVisibilities() throws Exception { "collectionStartDate":1719225354314, "collectionEndDate":1721903754315, "endDate":1724582154316, - "useLetterCommunication": false + "useLetterCommunication": false, + "mail": "south-simpsons@nooneknows.fr", + "tel": "" } ] """; @@ -93,7 +97,9 @@ void testUpdateVisibility() throws Exception { "collectionStartDate":null, "collectionEndDate":1921903754308, "endDate":2024582154308, - "useLetterCommunication": true + "useLetterCommunication": true, + "mail": "mail1", + "tel": "tel1" }"""; mockMvc.perform(put(updatePath) @@ -113,5 +119,7 @@ void testUpdateVisibility() throws Exception { assertThat(visibilityDBToCheck.getCollectionEndDate()).isEqualTo(1921903754308L); assertThat(visibilityDBToCheck.getEndDate()).isEqualTo(2024582154308L); assertThat(visibilityDBToCheck.isUseLetterCommunication()).isTrue(); + assertThat(visibilityDBToCheck.getMail()).isEqualTo("mail1"); + assertThat(visibilityDBToCheck.getTel()).isEqualTo("tel1"); } } From 540b84757c4609b43ce5183b246eda1609f637d0 Mon Sep 17 00:00:00 2001 From: davdarras Date: Mon, 7 Oct 2024 14:48:12 +0200 Subject: [PATCH 48/48] fix: allow no date when updating visibility --- pom.xml | 2 +- .../dto/input/VisibilityCampaignUpdateDto.java | 2 -- .../campaign/dto/input/VisibilityUpdateDto.java | 2 -- ...LeastOneDateCampaignVisibilityValidator.java | 13 ------------- .../api/web/annotation/AtLeastOneDateValid.java | 17 ----------------- .../AtLeastOneDateVisibilityValidator.java | 13 ------------- .../CampaignControllerUpdateTest.java | 11 ----------- .../controller/VisibilityControllerTest.java | 14 -------------- 8 files changed, 1 insertion(+), 73 deletions(-) delete mode 100644 src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateCampaignVisibilityValidator.java delete mode 100644 src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateValid.java delete mode 100644 src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateVisibilityValidator.java diff --git a/pom.xml b/pom.xml index 7d351203..b0655726 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ fr.insee.pearljam pearljam-back-office - 5.1.7 + 5.1.8 Pearl-Jam-Back-Office Back-office services for PearlJam diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java index 25227f66..54599052 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignUpdateDto.java @@ -1,7 +1,6 @@ package fr.insee.pearljam.api.campaign.dto.input; import com.fasterxml.jackson.annotation.JsonInclude; -import fr.insee.pearljam.api.web.annotation.AtLeastOneDateValid; import fr.insee.pearljam.domain.campaign.model.Visibility; import jakarta.validation.constraints.NotBlank; import org.springframework.lang.NonNull; @@ -19,7 +18,6 @@ * @param endDate End date of the visibility */ @JsonInclude(JsonInclude.Include.NON_NULL) -@AtLeastOneDateValid public record VisibilityCampaignUpdateDto( Long managementStartDate, Long interviewerStartDate, diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java index 355d1f7f..83dcfda0 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityUpdateDto.java @@ -1,7 +1,6 @@ package fr.insee.pearljam.api.campaign.dto.input; import com.fasterxml.jackson.annotation.JsonInclude; -import fr.insee.pearljam.api.web.annotation.AtLeastOneDateValid; import fr.insee.pearljam.domain.campaign.model.Visibility; import lombok.NonNull; @@ -16,7 +15,6 @@ * @param endDate End date of the visibility */ @JsonInclude(JsonInclude.Include.NON_NULL) -@AtLeastOneDateValid public record VisibilityUpdateDto( Long managementStartDate, Long interviewerStartDate, diff --git a/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateCampaignVisibilityValidator.java b/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateCampaignVisibilityValidator.java deleted file mode 100644 index 70572a8f..00000000 --- a/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateCampaignVisibilityValidator.java +++ /dev/null @@ -1,13 +0,0 @@ -package fr.insee.pearljam.api.web.annotation; - -import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignUpdateDto; -import jakarta.validation.ConstraintValidator; -import jakarta.validation.ConstraintValidatorContext; - -public class AtLeastOneDateCampaignVisibilityValidator implements ConstraintValidator { - @Override - public boolean isValid(VisibilityCampaignUpdateDto dto, ConstraintValidatorContext context) { - return dto.managementStartDate() != null || dto.interviewerStartDate() != null || dto.identificationPhaseStartDate() != null || - dto.collectionStartDate() != null || dto.collectionEndDate() != null || dto.endDate() != null; - } -} diff --git a/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateValid.java b/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateValid.java deleted file mode 100644 index 89bb220c..00000000 --- a/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateValid.java +++ /dev/null @@ -1,17 +0,0 @@ -package fr.insee.pearljam.api.web.annotation; - -import jakarta.validation.Constraint; -import jakarta.validation.Payload; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Constraint(validatedBy = {AtLeastOneDateCampaignVisibilityValidator.class, AtLeastOneDateVisibilityValidator.class}) -@Target({ ElementType.TYPE }) -@Retention(RetentionPolicy.RUNTIME) -public @interface AtLeastOneDateValid { - String message() default "At least one date must be provided for a visibility"; - Class[] groups() default {}; - Class[] payload() default {}; -} diff --git a/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateVisibilityValidator.java b/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateVisibilityValidator.java deleted file mode 100644 index 64f3e74e..00000000 --- a/src/main/java/fr/insee/pearljam/api/web/annotation/AtLeastOneDateVisibilityValidator.java +++ /dev/null @@ -1,13 +0,0 @@ -package fr.insee.pearljam.api.web.annotation; - -import fr.insee.pearljam.api.campaign.dto.input.VisibilityUpdateDto; -import jakarta.validation.ConstraintValidator; -import jakarta.validation.ConstraintValidatorContext; - -public class AtLeastOneDateVisibilityValidator implements ConstraintValidator { - @Override - public boolean isValid(VisibilityUpdateDto dto, ConstraintValidatorContext context) { - return dto.managementStartDate() != null || dto.interviewerStartDate() != null || dto.identificationPhaseStartDate() != null || - dto.collectionStartDate() != null || dto.collectionEndDate() != null || dto.endDate() != null; - } -} diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java index 8d94399c..8f89f971 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java @@ -107,17 +107,6 @@ void testUpdateCampaign05() throws Exception { testUpdateExceptions(HttpStatus.NOT_FOUND, VisibilityNotFoundException.MESSAGE); } - @Test - @DisplayName("Should return bad request when visibility has no date set") - void testUpdateCampaign06() throws Exception { - VisibilityCampaignUpdateDto visibility = generateVisibility("ou-id", - null, null, - null, null, - null, null, - true, "mail", "tel"); - testUpdateExceptions(visibility, HttpStatus.BAD_REQUEST, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE); - } - @Test @DisplayName("Should return conflict when invalidating update") void testUpdateCampaign07() throws Exception { diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java index aacd9324..a4684bfd 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/VisibilityControllerTest.java @@ -7,7 +7,6 @@ import fr.insee.pearljam.api.utils.JsonTestHelper; import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; -import fr.insee.pearljam.api.web.exception.ExceptionControllerAdvice; import fr.insee.pearljam.domain.campaign.model.Visibility; import fr.insee.pearljam.domain.exception.CampaignNotFoundException; import fr.insee.pearljam.domain.exception.VisibilityHasInvalidDatesException; @@ -137,19 +136,6 @@ void testUpdateVisibility03() throws Exception { .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.CONFLICT, updatePath, VisibilityHasInvalidDatesException.MESSAGE)); } - @Test - @DisplayName("Should return bad request when visibility has no date set") - void testUpdateVisibility04() throws Exception { - VisibilityUpdateDto visibility = generateUpdateVisibility( - null, null, - null, null, - null, null); - mockMvc.perform(put(updatePath) - .content(JsonTestHelper.toJson(visibility)) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.BAD_REQUEST, updatePath, ExceptionControllerAdvice.INVALID_PARAMETERS_MESSAGE)); - } - private VisibilityUpdateDto generateUpdateVisibility() { return generateUpdateVisibility(1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L,