From 453ed3639d3d3cbd1c9befc4390eaecb5c6b99a7 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 29 Dec 2023 15:38:53 +0100 Subject: [PATCH 1/4] feat: adding new groupchat attributes, groupchat may be only assigned to one agency --- api/userservice.yaml | 34 +++++++++++ .../web/controller/UserController.java | 1 - .../api/adapters/web/dto/ChatDTO.java | 14 +++++ .../api/adapters/web/dto/UserChatDTO.java | 7 +++ .../userservice/api/facade/ChatConverter.java | 4 +- .../api/facade/CreateChatFacade.java | 28 +++++++-- .../facade/userdata/ConsultantDataFacade.java | 18 ++++++ .../cob/userservice/api/model/Chat.java | 6 ++ .../cob/userservice/api/model/ChatAgency.java | 2 + .../userservice/api/service/ChatService.java | 23 +++++++- .../sessionlist/ConsultantChatEnricher.java | 5 ++ .../0045_changeSet.xml | 13 ++++ ...-hint-and-create-date-to-chat-rollback.sql | 4 ++ .../add-hint-and-create-date-to-chat.sql | 4 ++ .../db/changelog/userservice-dev-master.xml | 1 + .../db/changelog/userservice-local-master.xml | 1 + .../db/changelog/userservice-prod-master.xml | 1 + .../changelog/userservice-staging-master.xml | 1 + src/main/resources/messages.properties | 2 + .../api/facade/ChatConverterTest.java | 20 ++++++- .../api/facade/CreateChatV1FacadeTest.java | 2 + .../api/facade/CreateChatV2FacadeTest.java | 59 ++++++++++++++++--- .../api/service/ChatServiceTest.java | 47 ++++++++++----- .../ConsultantChatEnricherTest.java | 6 ++ .../api/testHelper/TestConstants.java | 54 +++++++++++++---- 25 files changed, 314 insertions(+), 43 deletions(-) create mode 100644 src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/0045_changeSet.xml create mode 100644 src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/add-hint-and-create-date-to-chat-rollback.sql create mode 100644 src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/add-hint-and-create-date-to-chat.sql diff --git a/api/userservice.yaml b/api/userservice.yaml index 2a966b3c7..ac30b37d3 100644 --- a/api/userservice.yaml +++ b/api/userservice.yaml @@ -2364,6 +2364,18 @@ components: type: string format: date-time writeOnly: true + createdAt: + type: string + format: time + example: 2023-10-23T12:05:00.000Z + chatAgencies: + type: array + items: + $ref: '#/components/schemas/AgencyDTO' + hintMessage: + type: string + example: "Hint" + maxLength: 300 SessionUserDTO: type: object @@ -2394,6 +2406,12 @@ components: lastName: type: string example: Mustermann + username: + type: string + example: beraterXYZ + displayName: + type: string + example: Berater XYZ UserSessionListResponseDTO: type: object @@ -2764,10 +2782,15 @@ components: - startTime - duration - repetitive + - agencyId properties: topic: type: string example: Wöchentliche Drogenberatung + agencyId: + type: integer + format: int64 + example: 7 startDate: type: string format: date @@ -2782,12 +2805,23 @@ components: repetitive: type: boolean example: false + hintMessage: + type: string + example: "Hint" + maxLength: 300 CreateChatResponseDTO: type: object required: - groupId properties: + createdAt: + type: string + format: time + example: 2019-10-23T12:05:00.000Z + creatorDisplayName: + type: string + example: Max M. groupId: type: string example: WCET6GWir78pNMyyD diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java index 957607f9b..947fe7b5b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java @@ -981,7 +981,6 @@ public ResponseEntity createChatV2(@RequestBody ChatDTO c var callingConsultant = this.userAccountProvider.retrieveValidatedConsultant(); var response = createChatFacade.createChatV2(chatDTO, callingConsultant); - return new ResponseEntity<>(response, HttpStatus.CREATED); } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java index 05f48e329..01fc1af72 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java @@ -20,6 +20,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.hibernate.validator.constraints.Length; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat.ISO; @@ -62,10 +63,23 @@ public class ChatDTO { @JsonProperty("repetitive") private boolean repetitive; + @NotNull(message = "{chat.agencyId.notNull}") + @ApiModelProperty(required = true, example = "5", position = 5) + @Min(value = 0, message = "{chat.agencyId.invalid}") + @JsonProperty("agencyId") + private long agencyId; + + @ApiModelProperty(required = true, example = "5", position = 6) + @Length(max = 300, message = "{chat.hintMessage.invalid}") + @JsonProperty("hintMessage") + private String hintMessage; + @Override public String toString() { return "ChatDTO [topic=" + topic + + ", agencyId=" + + agencyId + ", startDate=" + startDate + ", startTime=" diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserChatDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserChatDTO.java index ec4243eb6..560e5e113 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserChatDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserChatDTO.java @@ -6,6 +6,7 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -69,4 +70,10 @@ public class UserChatDTO { @JsonIgnore private LocalDateTime startDateWithTime; @ApiModelProperty private LastMessageDTO e2eLastMessage; + + @ApiModelProperty private String createdAt; + + @ApiModelProperty private List assignedAgencies; + + @ApiModelProperty private String hintMessage; } diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/ChatConverter.java b/src/main/java/de/caritas/cob/userservice/api/facade/ChatConverter.java index 8558cc150..de09e4c0d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/ChatConverter.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/ChatConverter.java @@ -32,7 +32,9 @@ public Chat convertToEntity(ChatDTO chatDTO, Consultant consultant, AgencyDTO ag .repetitive(isTrue(chatDTO.isRepetitive())) // Note that the repetition interval can only be weekly atm. .chatInterval(isTrue(chatDTO.isRepetitive()) ? ChatInterval.WEEKLY : null) - .updateDate(nowInUtc()); + .updateDate(nowInUtc()) + .createDate(nowInUtc()) + .hintMessage(chatDTO.getHintMessage()); if (nonNull(agencyDTO)) { builder.consultingTypeId(agencyDTO.getConsultingType()); diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/CreateChatFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/CreateChatFacade.java index 6f097b023..bfe0814ab 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/CreateChatFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/CreateChatFacade.java @@ -8,6 +8,7 @@ import de.caritas.cob.userservice.api.adapters.web.dto.AgencyDTO; import de.caritas.cob.userservice.api.adapters.web.dto.ChatDTO; import de.caritas.cob.userservice.api.adapters.web.dto.CreateChatResponseDTO; +import de.caritas.cob.userservice.api.exception.httpresponses.BadRequestException; import de.caritas.cob.userservice.api.exception.httpresponses.InternalServerErrorException; import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatAddUserToGroupException; import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatCreateGroupException; @@ -16,6 +17,7 @@ import de.caritas.cob.userservice.api.model.Chat; import de.caritas.cob.userservice.api.model.ChatAgency; import de.caritas.cob.userservice.api.model.Consultant; +import de.caritas.cob.userservice.api.model.ConsultantAgency; import de.caritas.cob.userservice.api.service.ChatService; import de.caritas.cob.userservice.api.service.agency.AgencyService; import java.util.function.BiFunction; @@ -32,7 +34,6 @@ public class CreateChatFacade { private final @NonNull RocketChatService rocketChatService; private final @NonNull AgencyService agencyService; private final @NonNull ChatConverter chatConverter; - /** * Creates a chat in MariaDB, it's relation to the agency and Rocket.Chat-room. * @@ -65,7 +66,10 @@ private CreateChatResponseDTO createChat( rcGroupId = createRocketChatGroupWithTechnicalUser(chatDTO, chat); chat.setGroupId(rcGroupId); chatService.saveChat(chat); - return new CreateChatResponseDTO().groupId(rcGroupId); + + return new CreateChatResponseDTO() + .groupId(rcGroupId) + .createdAt(chat.getCreateDate().toString()); } catch (InternalServerErrorException e) { doRollback(chat, rcGroupId); throw e; @@ -87,13 +91,25 @@ private Chat saveChatV1(Consultant consultant, ChatDTO chatDTO) { private Chat saveChatV2(Consultant consultant, ChatDTO chatDTO) { Chat chat = chatService.saveChat(chatConverter.convertToEntity(chatDTO, consultant)); - consultant - .getConsultantAgencies() - .forEach( - consultantAgency -> createChatAgencyRelation(chat, consultantAgency.getAgencyId())); + ConsultantAgency foundConsultantAgency = + findConsultantAgencyForGivenChatAgency(consultant, chatDTO); + createChatAgencyRelation(chat, foundConsultantAgency.getAgencyId()); return chat; } + private ConsultantAgency findConsultantAgencyForGivenChatAgency( + Consultant consultant, ChatDTO chatDTO) { + return consultant.getConsultantAgencies().stream() + .filter(agency -> agency.getAgencyId().equals(chatDTO.getAgencyId())) + .findFirst() + .orElseThrow( + () -> + new BadRequestException( + String.format( + "Consultant with id %s is not assigned to agency with id %s", + consultant.getId(), chatDTO.getAgencyId()))); + } + private void createChatAgencyRelation(Chat chat, Long agencyId) { chatService.saveChatAgencyRelation(new ChatAgency(chat, agencyId)); } diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacade.java index 88f13ee2d..3029790b4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacade.java @@ -5,6 +5,7 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank; import de.caritas.cob.userservice.api.adapters.web.dto.AbsenceDTO; +import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSessionResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.GroupSessionListResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.UserSessionListResponseDTO; import de.caritas.cob.userservice.api.adapters.web.mapping.UserDtoMapper; @@ -12,6 +13,7 @@ import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.api.port.in.AccountManaging; import de.caritas.cob.userservice.api.service.ConsultantService; +import java.util.List; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -71,4 +73,20 @@ public void addConsultantDisplayNameToSessionList(UserSessionListResponseDTO use } }); } + + public void addConsultantDisplayNameToSessionList( + List consultantSessionResponseDTOs) { + consultantSessionResponseDTOs.stream() + .forEach( + session -> { + var chatOwner = session.getConsultant(); + if (nonNull(chatOwner) && nonNull(chatOwner.getUsername())) { + accountManager + .findConsultantByUsername(chatOwner.getUsername()) + .ifPresent( + consultantMap -> + chatOwner.setDisplayName(userDtoMapper.displayNameOf(consultantMap))); + } + }); + } } diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Chat.java b/src/main/java/de/caritas/cob/userservice/api/model/Chat.java index 1992d67f2..95cea8a17 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Chat.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Chat.java @@ -100,6 +100,12 @@ public enum ChatInterval { @Column(name = "update_date") private LocalDateTime updateDate; + @Column(name = "create_date") + private LocalDateTime createDate; + + @Column(name = "hint_message") + private String hintMessage; + @Override public boolean equals(Object o) { if (this == o) { diff --git a/src/main/java/de/caritas/cob/userservice/api/model/ChatAgency.java b/src/main/java/de/caritas/cob/userservice/api/model/ChatAgency.java index e49300cfe..93ffc5901 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/ChatAgency.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/ChatAgency.java @@ -11,6 +11,7 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -22,6 +23,7 @@ @NoArgsConstructor @Getter @Setter +@Builder public class ChatAgency { @Id diff --git a/src/main/java/de/caritas/cob/userservice/api/service/ChatService.java b/src/main/java/de/caritas/cob/userservice/api/service/ChatService.java index 5150f3e7b..ab269c26d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/ChatService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/ChatService.java @@ -21,6 +21,7 @@ import de.caritas.cob.userservice.api.port.out.ChatAgencyRepository; import de.caritas.cob.userservice.api.port.out.ChatRepository; import de.caritas.cob.userservice.api.port.out.UserChatRepository; +import de.caritas.cob.userservice.api.service.agency.AgencyService; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; @@ -32,11 +33,13 @@ import java.util.stream.StreamSupport; import lombok.NonNull; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; /** Chat service class */ @Service @RequiredArgsConstructor +@Slf4j public class ChatService { private final @NonNull ChatRepository chatRepository; @@ -44,6 +47,8 @@ public class ChatService { private final @NonNull UserChatRepository userChatRepository; private final @NonNull ConsultantService consultantService; + private final @NonNull AgencyService agencyService; + /** * Returns a list of current chats for the provided {@link Consultant} * @@ -66,7 +71,8 @@ private ConsultantSessionResponseDTO convertChatToConsultantSessionResponseDTO(C new SessionConsultantForConsultantDTO() .id(chat.getChatOwner().getId()) .firstName(chat.getChatOwner().getFirstName()) - .lastName(chat.getChatOwner().getLastName())); + .lastName(chat.getChatOwner().getLastName()) + .username(chat.getChatOwner().getUsername())); } private String[] getChatModerators(Set chatAgencies) { @@ -137,6 +143,16 @@ private UserSessionResponseDTO convertChatToUserSessionResponseDTO(Chat chat) { } private UserChatDTO createUserChat(Chat chat) { + if (chat.getChatAgencies().size() > 1) { + log.warn( + "Chat with id {} has more than one agency assigned. " + "This should not be the case.", + chat.getId()); + } + var chatAgencies = + chat.getChatAgencies().stream() + .map(chatAgency -> agencyService.getAgency(chatAgency.getAgencyId())) + .collect(Collectors.toList()); + return new UserChatDTO( chat.getId(), chat.getTopic(), @@ -160,7 +176,10 @@ private UserChatDTO createUserChat(Chat chat) { false, getChatModerators(chat.getChatAgencies()), chat.getStartDate(), - null); + null, + chat.getCreateDate() != null ? chat.getCreateDate().toString() : null, + chatAgencies, + chat.getHintMessage()); } /** diff --git a/src/main/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricher.java b/src/main/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricher.java index 9a9c5146d..76bd02e22 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricher.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricher.java @@ -7,6 +7,7 @@ import de.caritas.cob.userservice.api.adapters.web.dto.UserChatDTO; import de.caritas.cob.userservice.api.container.RocketChatRoomInformation; import de.caritas.cob.userservice.api.facade.sessionlist.RocketChatRoomInformationProvider; +import de.caritas.cob.userservice.api.facade.userdata.ConsultantDataFacade; import de.caritas.cob.userservice.api.helper.SessionListAnalyser; import de.caritas.cob.userservice.api.model.Consultant; import java.util.List; @@ -22,6 +23,8 @@ public class ConsultantChatEnricher { private final @NonNull SessionListAnalyser sessionListAnalyser; private final @NonNull RocketChatRoomInformationProvider rocketChatRoomInformationProvider; + private final @NonNull ConsultantDataFacade consultantDataFacade; + /** * Enriches the given session with the following information from Rocket.Chat. - last message - * last message date - messages read @@ -50,6 +53,8 @@ public List updateRequiredConsultantChatValues( consultant.getRocketChatId(), consultantSessionResponseDTO)); + consultantDataFacade.addConsultantDisplayNameToSessionList(consultantSessionResponseDTOs); + return consultantSessionResponseDTOs; } diff --git a/src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/0045_changeSet.xml b/src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/0045_changeSet.xml new file mode 100644 index 000000000..e65e9c972 --- /dev/null +++ b/src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/0045_changeSet.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/add-hint-and-create-date-to-chat-rollback.sql b/src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/add-hint-and-create-date-to-chat-rollback.sql new file mode 100644 index 000000000..f3397704d --- /dev/null +++ b/src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/add-hint-and-create-date-to-chat-rollback.sql @@ -0,0 +1,4 @@ +ALTER TABLE `userservice`.`chat` + DROP COLUMN `hint_message`; +ALTER TABLE `userservice`.`chat` + DROP COLUMN `create_date`; \ No newline at end of file diff --git a/src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/add-hint-and-create-date-to-chat.sql b/src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/add-hint-and-create-date-to-chat.sql new file mode 100644 index 000000000..411dd93f2 --- /dev/null +++ b/src/main/resources/db/changelog/changeset/0045_add_hint_and_create_date_to_chat/add-hint-and-create-date-to-chat.sql @@ -0,0 +1,4 @@ +ALTER TABLE `userservice`.`chat` + ADD COLUMN `hint_message` VARCHAR(300) NULL DEFAULT NULL; +ALTER TABLE `userservice`.`chat` + ADD COLUMN `create_date` datetime NOT NULL DEFAULT (UTC_TIMESTAMP); \ No newline at end of file diff --git a/src/main/resources/db/changelog/userservice-dev-master.xml b/src/main/resources/db/changelog/userservice-dev-master.xml index 399c04829..1919daf44 100644 --- a/src/main/resources/db/changelog/userservice-dev-master.xml +++ b/src/main/resources/db/changelog/userservice-dev-master.xml @@ -50,4 +50,5 @@ + diff --git a/src/main/resources/db/changelog/userservice-local-master.xml b/src/main/resources/db/changelog/userservice-local-master.xml index 8722d74fc..3391f4c94 100644 --- a/src/main/resources/db/changelog/userservice-local-master.xml +++ b/src/main/resources/db/changelog/userservice-local-master.xml @@ -50,4 +50,5 @@ + diff --git a/src/main/resources/db/changelog/userservice-prod-master.xml b/src/main/resources/db/changelog/userservice-prod-master.xml index 1058d16fc..f072c791f 100644 --- a/src/main/resources/db/changelog/userservice-prod-master.xml +++ b/src/main/resources/db/changelog/userservice-prod-master.xml @@ -49,4 +49,5 @@ + diff --git a/src/main/resources/db/changelog/userservice-staging-master.xml b/src/main/resources/db/changelog/userservice-staging-master.xml index 6102aaf16..9bd923568 100644 --- a/src/main/resources/db/changelog/userservice-staging-master.xml +++ b/src/main/resources/db/changelog/userservice-staging-master.xml @@ -48,4 +48,5 @@ + diff --git a/src/main/resources/messages.properties b/src/main/resources/messages.properties index 31738df28..065d513ec 100644 --- a/src/main/resources/messages.properties +++ b/src/main/resources/messages.properties @@ -24,6 +24,8 @@ chat.startTime.invalid=Please provide a valid start time chat.duration.notNull=Please provide the chat's duration chat.duration.invalid=Please provide a valid duration chat.repetitive.notNull=Please provide if the chat is repetitive +chat.agencyId.notNull=Please provide agency Id +chat.hintMessage.invalid=Please provide a valid hint message that does not exceed 300 characters ## API: (error) messages regarding the Keycloak Admin Client (API) api.error.keycloakError=An unexpected Keycloak error occurred diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/ChatConverterTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/ChatConverterTest.java index ce1147f03..2d7b95fa3 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/ChatConverterTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/ChatConverterTest.java @@ -1,5 +1,6 @@ package de.caritas.cob.userservice.api.facade; +import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_HINT_MESSAGE; import static org.assertj.core.api.Assertions.assertThat; import de.caritas.cob.userservice.api.adapters.web.dto.AgencyDTO; @@ -124,7 +125,7 @@ void convertToEntity_Should_setIntervalToNull_When_repetitiveIsFalse() { } @Test - void convertToEntity_Should_setUpdateDate() { + void convertToEntity_Should_setUpdateDate_And_CreateDate() { // given ChatDTO chatDTO = givenChatDTO(); Consultant consultant = givenConsultant(); @@ -136,6 +137,22 @@ void convertToEntity_Should_setUpdateDate() { // then assertThat(chat.getUpdateDate()).isNotNull(); + assertThat(chat.getCreateDate()).isNotNull(); + } + + @Test + void convertToEntity_Should_setHintMessage() { + // given + ChatDTO chatDTO = givenChatDTO(); + Consultant consultant = givenConsultant(); + AgencyDTO agencyDTO = givenAgencyDTO(); + + // when + ChatConverter chatConverter = new ChatConverter(); + Chat chat = chatConverter.convertToEntity(chatDTO, consultant, agencyDTO); + + // then + assertThat(chat.getHintMessage()).isEqualTo(CHAT_HINT_MESSAGE); } private ChatDTO givenChatDTO() { @@ -149,6 +166,7 @@ private ChatDTO givenChatDTO(boolean repetitive) { .startTime(LocalTime.of(12, 5)) .duration(120) .repetitive(repetitive) + .hintMessage(CHAT_HINT_MESSAGE) .build(); } diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV1FacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV1FacadeTest.java index da9a5d5ab..1a71be880 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV1FacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV1FacadeTest.java @@ -34,6 +34,7 @@ import de.caritas.cob.userservice.api.service.ChatService; import de.caritas.cob.userservice.api.service.LogService; import de.caritas.cob.userservice.api.service.agency.AgencyService; +import java.time.LocalDateTime; import java.util.Optional; import org.junit.Before; import org.junit.Test; @@ -77,6 +78,7 @@ public class CreateChatV1FacadeTest { public void setup() { when(chat.getId()).thenReturn(CHAT_ID); when(chat.getConsultingTypeId()).thenReturn(15); + when(chat.getCreateDate()).thenReturn(LocalDateTime.now()); when(agencyService.getAgency(any())).thenReturn(AGENCY_DTO_KREUZBUND); setInternalState(LogService.class, "LOGGER", logger); } diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV2FacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV2FacadeTest.java index 9c12d5c05..70ba34b99 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV2FacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/CreateChatV2FacadeTest.java @@ -2,14 +2,17 @@ import static de.caritas.cob.userservice.api.testHelper.TestConstants.ACTIVE_CHAT; import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_DTO; +import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_DURATION; import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_ID; +import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_REPETITIVE; +import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_START_DATE; +import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_START_TIME; +import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_TOPIC; import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTANT_AGENCIES_SET; import static de.caritas.cob.userservice.api.testHelper.TestConstants.ERROR; import static de.caritas.cob.userservice.api.testHelper.TestConstants.GROUP_CHAT_NAME; import static de.caritas.cob.userservice.api.testHelper.TestConstants.RC_GROUP_ID; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; @@ -22,7 +25,9 @@ import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatService; import de.caritas.cob.userservice.api.adapters.rocketchat.dto.group.GroupDTO; import de.caritas.cob.userservice.api.adapters.rocketchat.dto.group.GroupResponseDTO; +import de.caritas.cob.userservice.api.adapters.web.dto.ChatDTO; import de.caritas.cob.userservice.api.adapters.web.dto.CreateChatResponseDTO; +import de.caritas.cob.userservice.api.exception.httpresponses.BadRequestException; import de.caritas.cob.userservice.api.exception.httpresponses.InternalServerErrorException; import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatAddUserToGroupException; import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatCreateGroupException; @@ -33,10 +38,13 @@ import de.caritas.cob.userservice.api.service.ChatService; import de.caritas.cob.userservice.api.service.LogService; import de.caritas.cob.userservice.api.service.agency.AgencyService; +import java.time.LocalDateTime; import java.util.Optional; +import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; @@ -75,9 +83,42 @@ public class CreateChatV2FacadeTest { @Before public void setup() { when(chat.getId()).thenReturn(CHAT_ID); + when(chat.getCreateDate()).thenReturn(LocalDateTime.now()); setInternalState(LogService.class, "LOGGER", logger); } + @Test + public void + createChatV2_Should_ThrowBadRequestException_When_ConsultantAgencyDoesNotMatchChatAgency() + throws Exception { + when(rocketChatService.createPrivateGroupWithSystemUser(any())) + .thenReturn(Optional.of(groupResponseDTO)); + when(groupResponseDTO.getGroup()).thenReturn(groupDTO); + when(groupDTO.getId()).thenReturn(RC_GROUP_ID); + when(chatService.saveChat(Mockito.any())).thenReturn(chat); + when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET); + String consultantId = UUID.randomUUID().toString(); + when(consultant.getId()).thenReturn(consultantId); + + var chatWithNonMatchingAgency = + new ChatDTO( + CHAT_TOPIC, + CHAT_START_DATE, + CHAT_START_TIME, + CHAT_DURATION, + CHAT_REPETITIVE, + 999L, + "hint"); + + try { + createChatFacade.createChatV2(chatWithNonMatchingAgency, consultant); + } catch (BadRequestException e) { + assertThat(e.getMessage()) + .isEqualTo( + "Consultant with id " + consultantId + " is not assigned to agency with id 999"); + } + } + @Test public void createChatV2_Should_ReturnValidCreateChatResponseDTO_When_DataAccessSucceeds() throws Exception { @@ -86,15 +127,16 @@ public void createChatV2_Should_ReturnValidCreateChatResponseDTO_When_DataAccess when(groupResponseDTO.getGroup()).thenReturn(groupDTO); when(groupDTO.getId()).thenReturn(RC_GROUP_ID); when(chatService.saveChat(Mockito.any())).thenReturn(chat); + when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET); CreateChatResponseDTO result = createChatFacade.createChatV2(CHAT_DTO, consultant); - assertThat(result, instanceOf(CreateChatResponseDTO.class)); - assertEquals(RC_GROUP_ID, result.getGroupId()); + assertThat(result).isInstanceOf(CreateChatResponseDTO.class); + assertThat(result.getGroupId()).isEqualTo(RC_GROUP_ID); } @Test - public void createChatV2_Should_SaveConsultantAgenciesAsChatAgencyRelations() + public void createChatV2_Should_SaveConsultantAgency_From_CharDTOAsChatAgencyRelations() throws RocketChatCreateGroupException { when(consultant.getConsultantAgencies()).thenReturn(CONSULTANT_AGENCIES_SET); when(rocketChatService.createPrivateGroupWithSystemUser(any())) @@ -106,7 +148,10 @@ public void createChatV2_Should_SaveConsultantAgenciesAsChatAgencyRelations() createChatFacade.createChatV2(CHAT_DTO, consultant); verifyNoInteractions(agencyService); - verify(chatService, times(2)).saveChatAgencyRelation(any()); + var captor = ArgumentCaptor.forClass(ChatAgency.class); + verify(chatService, times(1)).saveChatAgencyRelation(captor.capture()); + + assertThat(captor.getValue().getAgencyId()).isEqualTo(CHAT_DTO.getAgencyId()); } @Test diff --git a/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java index 667bf9721..f33bc016f 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java @@ -5,6 +5,7 @@ import static de.caritas.cob.userservice.api.testHelper.TestConstants.AUTHENTICATED_USER_3; import static de.caritas.cob.userservice.api.testHelper.TestConstants.AUTHENTICATED_USER_CONSULTANT; import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_DTO; +import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_HINT_MESSAGE; import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_ID; import static de.caritas.cob.userservice.api.testHelper.TestConstants.CHAT_V2; import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTANT; @@ -27,6 +28,7 @@ import static org.mockito.Mockito.when; import static org.powermock.reflect.Whitebox.setInternalState; +import de.caritas.cob.userservice.api.adapters.web.dto.AgencyDTO; import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSessionResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.UserSessionResponseDTO; import de.caritas.cob.userservice.api.exception.httpresponses.BadRequestException; @@ -39,6 +41,7 @@ import de.caritas.cob.userservice.api.port.out.ChatAgencyRepository; import de.caritas.cob.userservice.api.port.out.ChatRepository; import de.caritas.cob.userservice.api.port.out.UserChatRepository; +import de.caritas.cob.userservice.api.service.agency.AgencyService; import java.time.LocalDate; import java.time.LocalTime; import java.util.List; @@ -67,6 +70,8 @@ public class ChatServiceTest { @Mock private ConsultantService consultantService; + @Mock private AgencyService agencyService; + @Before public void setup() { setInternalState(LogService.class, "LOGGER", logger); @@ -130,31 +135,45 @@ public void getChatsForUserId_Should_ReturnListOfUserSessionResponseDTOWithChats when(chatRepository.findAssignedByUserId(USER_ID)).thenReturn(singletonList(CHAT_V2)); when(consultantService.findConsultantsByAgencyIds(Mockito.any())) .thenReturn(singletonList(CONSULTANT)); + when(agencyService.getAgency( + CHAT_V2.getChatAgencies().stream().findFirst().orElseThrow().getAgencyId())) + .thenReturn(new AgencyDTO().name("agency name")); List resultList = chatService.getChatsForUserId(USER_ID); - assertNull(resultList.get(0).getSession()); - assertNotNull(resultList.get(0).getChat()); - assertEquals(CHAT_V2.getId(), resultList.get(0).getChat().getId()); - assertEquals(CHAT_V2.getTopic(), resultList.get(0).getChat().getTopic()); - assertThat(CHAT_V2.getConsultingTypeId(), is(resultList.get(0).getChat().getConsultingType())); + UserSessionResponseDTO resultUserSessionResponseDTO = resultList.get(0); + assertNull(resultUserSessionResponseDTO.getSession()); + assertNotNull(resultUserSessionResponseDTO.getChat()); + assertEquals(CHAT_V2.getId(), resultUserSessionResponseDTO.getChat().getId()); + assertEquals(CHAT_V2.getTopic(), resultUserSessionResponseDTO.getChat().getTopic()); + assertThat( + CHAT_V2.getConsultingTypeId(), + is(resultUserSessionResponseDTO.getChat().getConsultingType())); assertEquals( LocalDate.of( CHAT_V2.getStartDate().getYear(), CHAT_V2.getStartDate().getMonth(), CHAT_V2.getStartDate().getDayOfMonth()), - resultList.get(0).getChat().getStartDate()); + resultUserSessionResponseDTO.getChat().getStartDate()); assertEquals( LocalTime.of( CHAT_V2.getInitialStartDate().getHour(), CHAT_V2.getInitialStartDate().getMinute()), - resultList.get(0).getChat().getStartTime()); - assertEquals(CHAT_V2.getDuration(), resultList.get(0).getChat().getDuration()); - assertEquals(CHAT_V2.isRepetitive(), resultList.get(0).getChat().isRepetitive()); - assertEquals(CHAT_V2.isActive(), resultList.get(0).getChat().isActive()); - assertEquals(CHAT_V2.getGroupId(), resultList.get(0).getChat().getGroupId()); - assertNotNull(resultList.get(0).getChat().getModerators()); - assertEquals(1, resultList.get(0).getChat().getModerators().length); - assertEquals(CONSULTANT.getRocketChatId(), resultList.get(0).getChat().getModerators()[0]); + resultUserSessionResponseDTO.getChat().getStartTime()); + assertEquals(CHAT_V2.getDuration(), resultUserSessionResponseDTO.getChat().getDuration()); + assertEquals(CHAT_V2.isRepetitive(), resultUserSessionResponseDTO.getChat().isRepetitive()); + assertEquals(CHAT_V2.isActive(), resultUserSessionResponseDTO.getChat().isActive()); + assertEquals(CHAT_V2.getGroupId(), resultUserSessionResponseDTO.getChat().getGroupId()); + + assertNotNull(resultUserSessionResponseDTO.getChat().getModerators()); + assertEquals(1, resultUserSessionResponseDTO.getChat().getModerators().length); + assertEquals( + CONSULTANT.getRocketChatId(), resultUserSessionResponseDTO.getChat().getModerators()[0]); + assertEquals(1, resultUserSessionResponseDTO.getChat().getAssignedAgencies().size()); + assertEquals( + "agency name", + resultUserSessionResponseDTO.getChat().getAssignedAgencies().get(0).getName()); + assertNotNull(resultUserSessionResponseDTO.getChat().getCreatedAt()); + assertEquals(CHAT_HINT_MESSAGE, resultUserSessionResponseDTO.getChat().getHintMessage()); } @Test diff --git a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricherTest.java b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricherTest.java index 1249e8bb5..a791f9bcc 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricherTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantChatEnricherTest.java @@ -17,12 +17,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSessionResponseDTO; import de.caritas.cob.userservice.api.container.RocketChatRoomInformation; import de.caritas.cob.userservice.api.facade.sessionlist.RocketChatRoomInformationProvider; +import de.caritas.cob.userservice.api.facade.userdata.ConsultantDataFacade; import de.caritas.cob.userservice.api.helper.SessionListAnalyser; +import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -39,6 +42,8 @@ public class ConsultantChatEnricherTest { @Mock private RocketChatRoomInformationProvider rocketChatRoomInformationProvider; + @Mock private ConsultantDataFacade consultantDataFacade; + @Test public void updateRequiredConsultantChatValues_Should_SetSubscribedFlagToTrue_WhenConsultantIsAttendeeOfAChat() { @@ -60,6 +65,7 @@ public class ConsultantChatEnricherTest { CONSULTANT) .get(0); + verify(consultantDataFacade).addConsultantDisplayNameToSessionList(Mockito.any(List.class)); assertTrue(result.getChat().isSubscribed()); } diff --git a/src/test/java/de/caritas/cob/userservice/api/testHelper/TestConstants.java b/src/test/java/de/caritas/cob/userservice/api/testHelper/TestConstants.java index 71eb30e22..3977f798c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/testHelper/TestConstants.java +++ b/src/test/java/de/caritas/cob/userservice/api/testHelper/TestConstants.java @@ -6,6 +6,8 @@ import static de.caritas.cob.userservice.api.model.Session.SessionStatus.IN_PROGRESS; import static de.caritas.cob.userservice.api.model.Session.SessionStatus.NEW; +import com.google.api.client.util.Sets; +import com.google.common.collect.Lists; import com.neovisionaries.i18n.LanguageCode; import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatCredentials; import de.caritas.cob.userservice.api.adapters.rocketchat.dto.group.GroupMemberDTO; @@ -1191,8 +1193,20 @@ public class TestConstants { public static final Long CHAT_ID_3 = 138L; public static final String INVALID_CHAT_ID = "xyz"; public static final String GROUP_CHAT_NAME = "GROUP_CHAT_NAME"; + + private static final long CHAT_AGENCY_ID = 1L; + + public static final String CHAT_HINT_MESSAGE = "CHAT_HINT_MESSAGE"; public static final ChatDTO CHAT_DTO = - new ChatDTO(CHAT_TOPIC, CHAT_START_DATE, CHAT_START_TIME, CHAT_DURATION, CHAT_REPETITIVE); + new ChatDTO( + CHAT_TOPIC, + CHAT_START_DATE, + CHAT_START_TIME, + CHAT_DURATION, + CHAT_REPETITIVE, + CHAT_AGENCY_ID, + CHAT_HINT_MESSAGE); + public static final CreateChatResponseDTO CREATE_CHAT_RESPONSE_DTO = new CreateChatResponseDTO().groupId(RC_GROUP_ID); public static final Chat ACTIVE_CHAT = @@ -1209,9 +1223,11 @@ public class TestConstants { CHAT_MAX_PARTICIPANTS, RC_GROUP_ID, CONSULTANT, + Sets.newHashSet(), null, - null, - nowInUtc()); + nowInUtc(), + nowInUtc(), + null); public static final Chat INACTIVE_CHAT = new Chat( CHAT_ID_2, @@ -1226,9 +1242,11 @@ public class TestConstants { CHAT_MAX_PARTICIPANTS, RC_GROUP_ID, CONSULTANT, + Sets.newHashSet(), null, - null, - nowInUtc()); + nowInUtc(), + nowInUtc(), + null); public static final Chat CHAT_V2 = new Chat( CHAT_ID_3, @@ -1243,9 +1261,11 @@ public class TestConstants { CHAT_MAX_PARTICIPANTS, RC_GROUP_ID, CONSULTANT, + Set.of(new ChatAgency(null, CHAT_AGENCY_ID)), null, - null, - nowInUtc()); + nowInUtc(), + nowInUtc(), + CHAT_HINT_MESSAGE); public static final ChatAgency CHAT_AGENCY = new ChatAgency(ACTIVE_CHAT, AGENCY_ID); public static final Set CHAT_AGENCIES = new HashSet<>(Collections.singletonList(CHAT_AGENCY)); @@ -1267,7 +1287,10 @@ public class TestConstants { false, null, nowInUtc(), - null); + null, + nowInUtc().toString(), + Lists.newArrayList(), + CHAT_HINT_MESSAGE); public static final UserChatDTO USER_CHAT_DTO_2 = new UserChatDTO( CHAT_ID_2, @@ -1286,7 +1309,10 @@ public class TestConstants { false, null, nowInUtc(), - null); + null, + nowInUtc().toString(), + Lists.newArrayList(), + CHAT_HINT_MESSAGE); public static final UserChatDTO USER_CHAT_DTO_3 = new UserChatDTO( CHAT_ID_3, @@ -1305,7 +1331,10 @@ public class TestConstants { false, null, nowInUtc(), - null); + null, + nowInUtc().toString(), + Lists.newArrayList(), + CHAT_HINT_MESSAGE); public static final UserSessionResponseDTO USER_CHAT_RESPONSE_DTO = new UserSessionResponseDTO() .chat(USER_CHAT_DTO_1) @@ -2155,7 +2184,10 @@ public class TestConstants { false, null, nowInUtc(), - null); + null, + nowInUtc().toString(), + Lists.newArrayList(), + CHAT_HINT_MESSAGE); public static final ConsultantSessionResponseDTO CONSULTANT_SESSION_RESPONSE_DTO_WITH_ENCRYPTED_CHAT_MESSAGE = new ConsultantSessionResponseDTO() From cae2483d823787b7cc9b7fa368a5ccd74e5641e6 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 29 Dec 2023 17:16:10 +0100 Subject: [PATCH 2/4] fix: tests --- api/userservice.yaml | 1 - .../adapters/rocketchat/RocketChatClient.java | 6 +++-- .../adapters/rocketchat/RocketChatMapper.java | 27 ++++++++++--------- .../api/adapters/web/dto/ChatDTO.java | 9 +++++-- .../api/facade/CreateChatFacade.java | 7 +++++ .../facade/userdata/ConsultantDataFacade.java | 19 +++++++++---- .../helper/json/JsonSerializationUtils.java | 6 +++++ .../api/service/session/SessionMapper.java | 3 ++- .../controller/UserControllerChatE2EIT.java | 15 ++++++++--- .../web/controller/UserControllerIT.java | 8 +++--- .../api/testHelper/RequestBodyConstants.java | 17 +++++++++++- 11 files changed, 86 insertions(+), 32 deletions(-) diff --git a/api/userservice.yaml b/api/userservice.yaml index ac30b37d3..f031df5a8 100644 --- a/api/userservice.yaml +++ b/api/userservice.yaml @@ -2782,7 +2782,6 @@ components: - startTime - duration - repetitive - - agencyId properties: topic: type: string diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatClient.java b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatClient.java index 4c1ef4262..1584756af 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatClient.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatClient.java @@ -60,8 +60,10 @@ private HttpHeaders httpHeaders() { var systemUser = rcCredentialHelper.getSystemUserSneaky(); var httpHeaders = new HttpHeaders(); - httpHeaders.add(HEADER_AUTH_TOKEN, systemUser.getRocketChatToken()); - httpHeaders.add(HEADER_USER_ID, systemUser.getRocketChatUserId()); + if (systemUser != null) { + httpHeaders.add(HEADER_AUTH_TOKEN, systemUser.getRocketChatToken()); + httpHeaders.add(HEADER_USER_ID, systemUser.getRocketChatUserId()); + } return httpHeaders; } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatMapper.java b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatMapper.java index de7da2dc9..8cabe5214 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatMapper.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatMapper.java @@ -118,21 +118,22 @@ public UpdateUser updateUserOf(String chatUserId, String displayName) { public Optional> mapOfUserResponse( ResponseEntity userResponse) { - var body = userResponse.getBody(); - if (nonNull(body)) { - var user = body.getUser(); - var map = new HashMap(); - map.put("id", user.getId()); - if (nonNull(user.getUsername())) { - map.put("username", user.getUsername()); - } - if (nonNull(user.getName())) { - map.put("displayName", user.getName()); - } + if (nonNull(userResponse)) { + var body = userResponse.getBody(); + if (nonNull(body)) { + var user = body.getUser(); + var map = new HashMap(); + map.put("id", user.getId()); + if (nonNull(user.getUsername())) { + map.put("username", user.getUsername()); + } + if (nonNull(user.getName())) { + map.put("displayName", user.getName()); + } - return Optional.of(map); + return Optional.of(map); + } } - return Optional.empty(); } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java index 01fc1af72..e7abc41de 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java @@ -5,6 +5,7 @@ import static de.caritas.cob.userservice.api.helper.UserHelper.CHAT_TOPIC_MAX_LENGTH; import static de.caritas.cob.userservice.api.helper.UserHelper.CHAT_TOPIC_MIN_LENGTH; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -43,6 +44,7 @@ public class ChatDTO { @NotNull(message = "{chat.startDate.invalid}") @ApiModelProperty(required = true, example = "2019-10-23", position = 1) @JsonProperty("startDate") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") private LocalDate startDate; @DateTimeFormat(pattern = "HH:mm") @@ -63,11 +65,10 @@ public class ChatDTO { @JsonProperty("repetitive") private boolean repetitive; - @NotNull(message = "{chat.agencyId.notNull}") @ApiModelProperty(required = true, example = "5", position = 5) @Min(value = 0, message = "{chat.agencyId.invalid}") @JsonProperty("agencyId") - private long agencyId; + private Long agencyId; @ApiModelProperty(required = true, example = "5", position = 6) @Length(max = 300, message = "{chat.hintMessage.invalid}") @@ -88,6 +89,10 @@ public String toString() { + duration + ", repetitive=" + repetitive + + ", agencyId=" + + agencyId + + ", hintMessage=" + + hintMessage + "]"; } } diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/CreateChatFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/CreateChatFacade.java index bfe0814ab..d92bd9efe 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/CreateChatFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/CreateChatFacade.java @@ -90,6 +90,7 @@ private Chat saveChatV1(Consultant consultant, ChatDTO chatDTO) { } private Chat saveChatV2(Consultant consultant, ChatDTO chatDTO) { + assertAgencyIdIsNotNull(chatDTO); Chat chat = chatService.saveChat(chatConverter.convertToEntity(chatDTO, consultant)); ConsultantAgency foundConsultantAgency = findConsultantAgencyForGivenChatAgency(consultant, chatDTO); @@ -97,6 +98,12 @@ private Chat saveChatV2(Consultant consultant, ChatDTO chatDTO) { return chat; } + private void assertAgencyIdIsNotNull(ChatDTO chatDTO) { + if (chatDTO.getAgencyId() == null) { + throw new BadRequestException("Agency id must not be null"); + } + } + private ConsultantAgency findConsultantAgencyForGivenChatAgency( Consultant consultant, ChatDTO chatDTO) { return consultant.getConsultantAgencies().stream() diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacade.java index 3029790b4..c17a26808 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataFacade.java @@ -14,12 +14,16 @@ import de.caritas.cob.userservice.api.port.in.AccountManaging; import de.caritas.cob.userservice.api.service.ConsultantService; import java.util.List; +import java.util.Map; +import java.util.Optional; import lombok.NonNull; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor +@Slf4j public class ConsultantDataFacade { private final @NonNull ConsultantService consultantService; @@ -81,11 +85,16 @@ public void addConsultantDisplayNameToSessionList( session -> { var chatOwner = session.getConsultant(); if (nonNull(chatOwner) && nonNull(chatOwner.getUsername())) { - accountManager - .findConsultantByUsername(chatOwner.getUsername()) - .ifPresent( - consultantMap -> - chatOwner.setDisplayName(userDtoMapper.displayNameOf(consultantMap))); + try { + Optional> consultantByUsername = + accountManager.findConsultantByUsername(chatOwner.getUsername()); + if (consultantByUsername.isPresent()) { + chatOwner.setDisplayName( + userDtoMapper.displayNameOf(consultantByUsername.get())); + } + } catch (Exception e) { + log.error("Error while fetching consultant by username: {}", e.getMessage()); + } } }); } diff --git a/src/main/java/de/caritas/cob/userservice/api/helper/json/JsonSerializationUtils.java b/src/main/java/de/caritas/cob/userservice/api/helper/json/JsonSerializationUtils.java index b55c66fb0..226e9cd40 100644 --- a/src/main/java/de/caritas/cob/userservice/api/helper/json/JsonSerializationUtils.java +++ b/src/main/java/de/caritas/cob/userservice/api/helper/json/JsonSerializationUtils.java @@ -6,6 +6,8 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.RuntimeJsonMappingException; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import java.text.SimpleDateFormat; public class JsonSerializationUtils { @@ -18,6 +20,10 @@ public static T deserializeFromJsonString(String jsonString, Class clazz) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true) .configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + objectMapper.setDateFormat(dateFormat); + objectMapper.registerModule(new JavaTimeModule()); + return objectMapper.readValue(jsonString, clazz); } catch (JsonProcessingException e) { throw new RuntimeJsonMappingException(e.getMessage()); diff --git a/src/main/java/de/caritas/cob/userservice/api/service/session/SessionMapper.java b/src/main/java/de/caritas/cob/userservice/api/service/session/SessionMapper.java index 831098eb4..d1f54dc32 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/session/SessionMapper.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/session/SessionMapper.java @@ -146,7 +146,8 @@ public GroupSessionResponseDTO toGroupSessionResponse( GroupSessionConsultantDTO.builder() .id(sessionConsultant.getId()) .firstName(sessionConsultant.getFirstName()) - .lastName(sessionConsultant.getLastName()); + .lastName(sessionConsultant.getLastName()) + .displayName(sessionConsultant.getDisplayName()); return response.consultant(consultant.build()); } } diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerChatE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerChatE2EIT.java index edfb4de80..92542d8c1 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerChatE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerChatE2EIT.java @@ -1,6 +1,7 @@ package de.caritas.cob.userservice.api.adapters.web.controller; -import static de.caritas.cob.userservice.api.testHelper.RequestBodyConstants.VALID_CREATE_CHAT_BODY; +import static de.caritas.cob.userservice.api.testHelper.RequestBodyConstants.VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER; +import static de.caritas.cob.userservice.api.testHelper.RequestBodyConstants.VALID_CREATE_CHAT_V1_BODY; import static de.caritas.cob.userservice.api.testHelper.TestConstants.RC_CREDENTIALS_SYSTEM_A; import static de.caritas.cob.userservice.api.testHelper.TestConstants.RC_CREDENTIALS_TECHNICAL_A; import static de.caritas.cob.userservice.api.testHelper.TestConstants.RC_GROUP_ID; @@ -62,6 +63,7 @@ import de.caritas.cob.userservice.api.model.Chat; import de.caritas.cob.userservice.api.model.ChatAgency; import de.caritas.cob.userservice.api.model.Consultant; +import de.caritas.cob.userservice.api.model.ConsultantAgency; import de.caritas.cob.userservice.api.model.User; import de.caritas.cob.userservice.api.model.UserAgency; import de.caritas.cob.userservice.api.model.UserChat; @@ -229,7 +231,7 @@ void createChatV1_Should_ReturnCreated_When_ChatWasCreated() throws Exception { .header(CSRF_HEADER, CSRF_VALUE) .header("rcToken", RandomStringUtils.randomAlphabetic(16)) .contentType(MediaType.APPLICATION_JSON) - .content(VALID_CREATE_CHAT_BODY) + .content(VALID_CREATE_CHAT_V1_BODY) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(jsonPath("groupId", is("rcGroupId"))); @@ -242,6 +244,8 @@ void createChatV2_Should_ReturnCreated_When_ChatWasCreated() throws Exception { givenAValidConsultant(true); givenAValidRocketChatSystemUser(); + ConsultantAgency consultantAgency = + consultant.getConsultantAgencies().stream().findFirst().orElseThrow(); mockMvc .perform( post("/users/chat/v2/new") @@ -249,12 +253,17 @@ void createChatV2_Should_ReturnCreated_When_ChatWasCreated() throws Exception { .header(CSRF_HEADER, CSRF_VALUE) .header("rcToken", RandomStringUtils.randomAlphabetic(16)) .contentType(MediaType.APPLICATION_JSON) - .content(VALID_CREATE_CHAT_BODY) + .content(giveValidCreateChatBodyWithAgency(consultantAgency)) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(jsonPath("groupId", is("rcGroupId"))); } + private String giveValidCreateChatBodyWithAgency(ConsultantAgency consultantAgency) { + return VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER.replace( + "${AGENCY_ID}", consultantAgency.getAgencyId().toString()); + } + @Test @WithMockUser(authorities = AuthorityValue.UPDATE_CHAT) void banFromChatShouldReturnClientErrorIfUserIdHasInvalidFormat() throws Exception { diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java index 7e74c47c2..9bea5072a 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java @@ -1681,7 +1681,7 @@ public void createChat_Should_ReturnInternalServerErrorAndLogError_When_ChatCoul mvc.perform( post(PATH_POST_CHAT_NEW) - .content(VALID_CREATE_CHAT_BODY) + .content(VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); @@ -1697,7 +1697,7 @@ public void createChat_Should_ReturnCreated_When_ChatWasCreated() throws Excepti mvc.perform( post(PATH_POST_CHAT_NEW) - .content(VALID_CREATE_CHAT_BODY) + .content(VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.CREATED.value())); @@ -1727,7 +1727,7 @@ public void createChatV2_Should_ReturnInternalServerErrorAndLogError_When_ChatCo mvc.perform( post(PATH_POST_CHAT_NEW_V2) - .content(VALID_CREATE_CHAT_BODY) + .content(VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); @@ -1743,7 +1743,7 @@ public void createChatV2_Should_ReturnCreated_When_ChatWasCreated() throws Excep mvc.perform( post(PATH_POST_CHAT_NEW_V2) - .content(VALID_CREATE_CHAT_BODY) + .content(VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.CREATED.value())); diff --git a/src/test/java/de/caritas/cob/userservice/api/testHelper/RequestBodyConstants.java b/src/test/java/de/caritas/cob/userservice/api/testHelper/RequestBodyConstants.java index fc984bce1..e0df4abfb 100644 --- a/src/test/java/de/caritas/cob/userservice/api/testHelper/RequestBodyConstants.java +++ b/src/test/java/de/caritas/cob/userservice/api/testHelper/RequestBodyConstants.java @@ -254,7 +254,7 @@ public class RequestBodyConstants { + "\", \"consultingType\": \"" + CONSULTING_TYPE_ID_SUCHT + "\"}"; - public static final String VALID_CREATE_CHAT_BODY = + public static final String VALID_CREATE_CHAT_V1_BODY = "{ \"topic\": \"" + CHAT_TOPIC + "\", \"startDate\": \"" @@ -267,6 +267,21 @@ public class RequestBodyConstants { + "\", \"repetitive\": " + CHAT_REPETITIVE + " }"; + public static final String VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER = + "{ \"topic\": \"" + + CHAT_TOPIC + + "\", \"startDate\": \"" + + CHAT_START_DATE + + "\", " + + "\"startTime\": \"" + + CHAT_START_TIME + + "\", \"duration\": \"" + + CHAT_DURATION + + "\", \"repetitive\": " + + CHAT_REPETITIVE + + ", \"agencyId\": " + + "${AGENCY_ID}" + + " }"; public static final String VALID_UPDATE_CHAT_BODY = "{ \"topic\": \"" + CHAT_TOPIC From fcd0293c19c357308409953f9bc76df3d758a5f1 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Tue, 2 Jan 2024 10:28:03 +0100 Subject: [PATCH 3/4] fix: tests --- .../web/controller/UserControllerIT.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java index 9bea5072a..ce54c7bd2 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java @@ -1681,12 +1681,22 @@ public void createChat_Should_ReturnInternalServerErrorAndLogError_When_ChatCoul mvc.perform( post(PATH_POST_CHAT_NEW) - .content(VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER) + .content(giveValidCreateChatBodyWithAgencyId(1L)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); } + private String giveValidCreateChatBodyWithAgency(ConsultantAgency consultantAgency) { + return VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER.replace( + "${AGENCY_ID}", consultantAgency.getAgencyId().toString()); + } + + private String giveValidCreateChatBodyWithAgencyId(Long agencyId) { + return VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER.replace( + "${AGENCY_ID}", agencyId.toString()); + } + @Test public void createChat_Should_ReturnCreated_When_ChatWasCreated() throws Exception { @@ -1697,7 +1707,7 @@ public void createChat_Should_ReturnCreated_When_ChatWasCreated() throws Excepti mvc.perform( post(PATH_POST_CHAT_NEW) - .content(VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER) + .content(giveValidCreateChatBodyWithAgencyId(1L)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.CREATED.value())); @@ -1727,7 +1737,7 @@ public void createChatV2_Should_ReturnInternalServerErrorAndLogError_When_ChatCo mvc.perform( post(PATH_POST_CHAT_NEW_V2) - .content(VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER) + .content(giveValidCreateChatBodyWithAgencyId(1L)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); @@ -1743,7 +1753,7 @@ public void createChatV2_Should_ReturnCreated_When_ChatWasCreated() throws Excep mvc.perform( post(PATH_POST_CHAT_NEW_V2) - .content(VALID_CREATE_CHAT_BODY_WITH_AGENCY_PLACEHOLDER) + .content(giveValidCreateChatBodyWithAgencyId(1L)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.CREATED.value())); From 02ed1777be3462bb109344632b2f07d0d2175ae9 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Tue, 2 Jan 2024 10:44:50 +0100 Subject: [PATCH 4/4] fix: tests --- .../cob/userservice/api/port/out/ChatRepository.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/port/out/ChatRepository.java b/src/main/java/de/caritas/cob/userservice/api/port/out/ChatRepository.java index 06e4aac07..cac3b29ff 100644 --- a/src/main/java/de/caritas/cob/userservice/api/port/out/ChatRepository.java +++ b/src/main/java/de/caritas/cob/userservice/api/port/out/ChatRepository.java @@ -15,7 +15,7 @@ public interface ChatRepository extends CrudRepository { value = "SELECT c.id, c.topic, c.consulting_type, c.initial_start_date, c.start_date, " + "c.duration, c.is_repetitive, c.chat_interval, c.is_active, c.max_participants, " - + "c.consultant_id_owner, c.rc_group_id, c.update_date FROM chat c JOIN chat_agency ca ON c" + + "c.consultant_id_owner, c.rc_group_id, c.update_date, c.create_date, c.hint_message FROM chat c JOIN chat_agency ca ON c" + ".id = ca.chat_id JOIN user_agency ua ON ca.agency_id = ua.agency_id AND ua.user_id = :user_id", nativeQuery = true) List findByUserId(@Param(value = "user_id") String userId); @@ -24,7 +24,7 @@ public interface ChatRepository extends CrudRepository { value = "SELECT c.id, c.topic, c.consulting_type, c.initial_start_date, c.start_date, " + "c.duration, c.is_repetitive, c.chat_interval, c.is_active, c.max_participants, " - + "c.consultant_id_owner, c.rc_group_id, c.update_date FROM chat c " + + "c.consultant_id_owner, c.rc_group_id, c.update_date, c.create_date, c.hint_message FROM chat c " + "JOIN user_chat uc ON c.id = uc.chat_id AND uc.user_id = :user_id", nativeQuery = true) List findAssignedByUserId(@Param(value = "user_id") String userId); @@ -33,7 +33,7 @@ public interface ChatRepository extends CrudRepository { value = "SELECT c.id, c.topic, c.consulting_type, c.initial_start_date, c.start_date, " + "c.duration, c.is_repetitive, c.chat_interval, c.is_active, c.max_participants, " - + "c.consultant_id_owner, c.rc_group_id, c.update_date FROM chat c JOIN chat_agency ca ON c" + + "c.consultant_id_owner, c.rc_group_id, c.update_date, c.create_date, c.hint_message FROM chat c JOIN chat_agency ca ON c" + ".id = ca.chat_id AND ca.agency_id IN :agency_ids", nativeQuery = true) List findByAgencyIds(@Param(value = "agency_ids") Set agencyIds);