Skip to content

Commit

Permalink
refactor: contact domain
Browse files Browse the repository at this point in the history
  • Loading branch information
BettyB979 committed Dec 6, 2023
1 parent 6275ce1 commit 8a65a0d
Show file tree
Hide file tree
Showing 7 changed files with 89 additions and 126 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,12 @@
import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent;
import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType;
import fr.insee.survey.datacollectionmanagement.contact.dto.AddressDto;
import fr.insee.survey.datacollectionmanagement.contact.dto.ContactDto;
import fr.insee.survey.datacollectionmanagement.contact.service.AddressService;
import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService;
import fr.insee.survey.datacollectionmanagement.contact.service.ContactService;
import fr.insee.survey.datacollectionmanagement.contact.util.PayloadUtil;
import fr.insee.survey.datacollectionmanagement.exception.NotFoundException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -24,6 +21,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

Expand All @@ -46,28 +44,17 @@ public class AddressController {

@Operation(summary = "Search for a contact address by the contact id")
@GetMapping(value = Constants.API_CONTACTS_ID_ADDRESS, produces = "application/json")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = AddressDto.class))),
@ApiResponse(responseCode = "404", description = "Not found"),
@ApiResponse(responseCode = "500", description = "Internal servor error")
})
@PreAuthorize("@AuthorizeMethodDecider.isInternalUser() "
+ "|| @AuthorizeMethodDecider.isWebClient() "
+ "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))"
+ "|| @AuthorizeMethodDecider.isAdmin() ")
public ResponseEntity<?> getContactAddress(@PathVariable("id") String id) {
public ResponseEntity<AddressDto> getContactAddress(@PathVariable("id") String id) {
Contact contact = contactService.findByIdentifier(id);
try {
if (contact.getAddress() != null)
return ResponseEntity.status(HttpStatus.OK)
.body(addressService.convertToDto(contact.getAddress()));
else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Address does not exist");
}

} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error");
}
if (contact.getAddress() != null)
return ResponseEntity.status(HttpStatus.OK)
.body(addressService.convertToDto(contact.getAddress()));
else throw new NotFoundException(String.format("No address found for contact %s", id));


}

Expand All @@ -77,12 +64,8 @@ public ResponseEntity<?> getContactAddress(@PathVariable("id") String id) {
+ "|| @AuthorizeMethodDecider.isWebClient() "
+ "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))"
+ "|| @AuthorizeMethodDecider.isAdmin() ")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = AddressDto.class))),
@ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = ContactDto.class))),
@ApiResponse(responseCode = "404", description = "Not found")
})
public ResponseEntity<?> putAddress(@PathVariable("id") String id, @RequestBody AddressDto addressDto) {

public ResponseEntity<AddressDto> putAddress(@PathVariable("id") String id, @RequestBody AddressDto addressDto, Authentication auth) {
Contact contact = contactService.findByIdentifier(id);
HttpStatus httpStatus;
Address addressUpdate;
Expand All @@ -102,7 +85,7 @@ public ResponseEntity<?> putAddress(@PathVariable("id") String id, @RequestBody
contactService.saveContact(contact);
httpStatus = HttpStatus.CREATED;
}

PayloadUtil.getPayloadAuthor(auth);
ContactEvent contactEventUpdate = contactEventService.createContactEvent(contact, ContactEventType.update,
null);
contactEventService.saveContactEvent(contactEventUpdate);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
package fr.insee.survey.datacollectionmanagement.contact.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import fr.insee.survey.datacollectionmanagement.constants.Constants;
import fr.insee.survey.datacollectionmanagement.contact.domain.Contact;
import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType;
import fr.insee.survey.datacollectionmanagement.contact.dto.ContactDto;
import fr.insee.survey.datacollectionmanagement.contact.dto.ContactFirstLoginDto;
import fr.insee.survey.datacollectionmanagement.contact.service.AddressService;
import fr.insee.survey.datacollectionmanagement.contact.service.ContactService;
import fr.insee.survey.datacollectionmanagement.contact.util.PayloadUtil;
import fr.insee.survey.datacollectionmanagement.exception.ImpossibleToDeleteException;
import fr.insee.survey.datacollectionmanagement.exception.NotFoundException;
import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning;
import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation;
import fr.insee.survey.datacollectionmanagement.exception.NotMatchException;
import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService;
import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService;
import fr.insee.survey.datacollectionmanagement.view.service.ViewService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
Expand All @@ -29,21 +27,19 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.text.ParseException;
import java.io.Serial;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

@RestController
@PreAuthorize("@AuthorizeMethodDecider.isInternalUser() "
+ "|| @AuthorizeMethodDecider.isWebClient() "
+ "|| @AuthorizeMethodDecider.isAdmin() ")
@Tag(name = "1 - Contacts", description = "Enpoints to create, update, delete and find contacts")
@Tag(name = "1 - Contacts", description = "Endpoints to create, update, delete and find contacts")
@Slf4j
@RequiredArgsConstructor
@Validated
Expand All @@ -55,18 +51,13 @@ public class ContactController {

private final ViewService viewService;

private final QuestioningService questioningService;

private final QuestioningAccreditationService questioningAccreditationService;

private final ModelMapper modelMapper;

@Operation(summary = "Search for contacts, paginated")
@GetMapping(value = Constants.API_CONTACTS_ALL, produces = "application/json")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ContactPage.class)))
})
public ResponseEntity<?> getContacts(
public ResponseEntity<ContactPage> getContacts(
@RequestParam(defaultValue = "0") Integer page,
@RequestParam(defaultValue = "20") Integer size,
@RequestParam(defaultValue = "identifier") String sort) {
Expand All @@ -82,90 +73,63 @@ public ResponseEntity<?> getContacts(
+ "|| @AuthorizeMethodDecider.isWebClient() "
+ "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))"
+ "|| @AuthorizeMethodDecider.isAdmin() ")
public ResponseEntity<?> getContact(@PathVariable("id") String id) {
public ResponseEntity<ContactFirstLoginDto> getContact(@PathVariable("id") String id) {
Contact contact = contactService.findByIdentifier(StringUtils.upperCase(id));
try {
return ResponseEntity.ok().body(convertToFirstLoginDto(contact));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error");
}
return ResponseEntity.ok().body(convertToFirstLoginDto(contact));


}


@Operation(summary = "Update or create a contact")
@PutMapping(value = Constants.API_CONTACTS_ID, produces = "application/json", consumes = "application/json")
@PreAuthorize("@AuthorizeMethodDecider.isInternalUser() "
+ "|| @AuthorizeMethodDecider.isWebClient() "
+ "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))"
+ "|| @AuthorizeMethodDecider.isAdmin() ")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ContactDto.class))),
@ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = ContactDto.class))),
@ApiResponse(responseCode = "400", description = "Bad request")
})
public ResponseEntity<?> putContact(@PathVariable("id") String id, @RequestBody @Valid ContactDto contactDto) {
if (StringUtils.isBlank(contactDto.getIdentifier()) || !contactDto.getIdentifier().equalsIgnoreCase(id)) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and contact identifier don't match");
public ResponseEntity<ContactDto> putContact(@PathVariable("id") String id, @RequestBody @Valid ContactDto contactDto, Authentication auth) throws JsonProcessingException {
if (!contactDto.getIdentifier().equalsIgnoreCase(id)) {
throw new NotMatchException("id and contact identifier don't match");
}
Contact contact;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest()
.buildAndExpand(contactDto.getIdentifier()).toUriString());
JsonNode payload = PayloadUtil.getPayloadAuthor(auth);

try {
contact = convertToEntity(contactDto);
} catch (ParseException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse contact");
if (contactDto.getAddress() != null)
contact.setAddress(addressService.convertToEntity(contactDto.getAddress()));
Contact contactUpdate = contactService.updateContactAddressEvent(contact, payload);
return ResponseEntity.ok().headers(responseHeaders).body(convertToDto(contactUpdate));
} catch (NotFoundException e) {
log.info("Creating contact with the identifier {}", contactDto.getIdentifier());
contact = convertToEntityNewContact(contactDto);
if (contactDto.getAddress() != null)
contact.setAddress(addressService.convertToEntity(contactDto.getAddress()));
Contact contactCreate = contactService.createContactAddressEvent(contact, null);
Contact contactCreate = contactService.createContactAddressEvent(contact, payload);
viewService.createView(id, null, null);
return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders).body(convertToDto(contactCreate));

}
if (contactDto.getAddress() != null)
contact.setAddress(addressService.convertToEntity(contactDto.getAddress()));
Contact contactUpdate = null;
try {
contactUpdate = contactService.updateContactAddressEvent(contact, null);
} catch (NotFoundException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error when update contact");
}
return ResponseEntity.ok().headers(responseHeaders).body(convertToDto(contactUpdate));

}

@Operation(summary = "Delete a contact, its address, its contactEvents and its accreditations")

@Operation(summary = "Delete a contact, its address, its contactEvents")
@DeleteMapping(value = Constants.API_CONTACTS_ID)
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "No Content"),
@ApiResponse(responseCode = "404", description = "Not found"),
@ApiResponse(responseCode = "400", description = "Bad Request")
})
@Transactional
public ResponseEntity<?> deleteContact(@PathVariable("id") String id) {
try {
Contact contact = contactService.findByIdentifier(id);
contactService.deleteContactAddressEvent(contact);

viewService.findViewByIdentifier(id).stream().forEach(viewService::deleteView);
questioningAccreditationService.findByContactIdentifier(id).stream().forEach(acc -> {
Questioning questioning = questioningService.findbyId(acc.getQuestioning().getId());
Set<QuestioningAccreditation> newSet = questioning.getQuestioningAccreditations();
newSet.removeIf(a -> a.getId().equals(acc.getId()));
questioning.setQuestioningAccreditations(newSet);
questioningService.saveQuestioning(questioning);
questioningAccreditationService.deleteAccreditation(acc);

});
log.info("Delete contact {}", id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact deleted");

} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error");
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteContact(@PathVariable("id") String id) {

if (!questioningAccreditationService.findByContactIdentifier(id).isEmpty()) {
throw new ImpossibleToDeleteException(
String.format("Contact %s cannot be deleted as he/she is still entitled to answer one or more questionnaires", id));
}

log.info("Delete contact {}", id);
Contact contact = contactService.findByIdentifier(id);
contactService.deleteContactAddressEvent(contact);

}

private ContactDto convertToDto(Contact contact) {
Expand All @@ -177,12 +141,11 @@ private ContactDto convertToDto(Contact contact) {
private ContactFirstLoginDto convertToFirstLoginDto(Contact contact) {
ContactFirstLoginDto contactFirstLoginDto = modelMapper.map(contact, ContactFirstLoginDto.class);
contactFirstLoginDto.setCivility(contact.getGender());
contactFirstLoginDto.setFirstConnect(contact.getContactEvents().stream()
.filter(e -> e.getType().equals(ContactEventType.firstConnect)).count() == 0);
contactFirstLoginDto.setFirstConnect(contact.getContactEvents().stream().noneMatch(e -> e.getType().equals(ContactEventType.firstConnect)));
return contactFirstLoginDto;
}

private Contact convertToEntity(ContactDto contactDto) throws ParseException, NoSuchElementException {
private Contact convertToEntity(ContactDto contactDto) {
Contact contact = modelMapper.map(contactDto, Contact.class);
contact.setGender(Contact.Gender.valueOf(contactDto.getCivility()));
Contact oldContact = contactService.findByIdentifier(contactDto.getIdentifier());
Expand All @@ -199,8 +162,9 @@ private Contact convertToEntityNewContact(ContactDto contactDto) {
return contact;
}

class ContactPage extends PageImpl<ContactDto> {
static class ContactPage extends PageImpl<ContactDto> {

@Serial
private static final long serialVersionUID = 656181199902518234L;

public ContactPage(List<ContactDto> content, Pageable pageable, long total) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,10 @@ public class ContactEventController {
})
public ResponseEntity<?> getContactContactEvents(@PathVariable("id") String identifier) {
Contact contact = contactService.findByIdentifier(identifier);
try {
return ResponseEntity.status(HttpStatus.OK)
.body(contact.getContactEvents().stream().map(this::convertToDto)
.toList());
return ResponseEntity.status(HttpStatus.OK)
.body(contact.getContactEvents().stream().map(this::convertToDto)
.toList());

} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error");
}

}

Expand Down Expand Up @@ -99,18 +95,13 @@ public ResponseEntity<?> postContactEvent(@RequestBody @Valid ContactEventDto co
})
public ResponseEntity<?> deleteContactEvent(@PathVariable("id") Long id) {
ContactEvent contactEvent = contactEventService.findById(id);
Contact contact = contactEvent.getContact();
contact.setContactEvents(contact.getContactEvents().stream().filter(ce -> !ce.equals(contactEvent))
.collect(Collectors.toSet()));
contactService.saveContact(contact);
contactEventService.deleteContactEvent(id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact event deleted");

try {
Contact contact = contactEvent.getContact();
contact.setContactEvents(contact.getContactEvents().stream().filter(ce -> !ce.equals(contactEvent))
.collect(Collectors.toSet()));
contactService.saveContact(contact);
contactEventService.deleteContactEvent(id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact event deleted");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error");

}
}

private ContactEventDto convertToDto(ContactEvent contactEvent) {
Expand All @@ -120,7 +111,7 @@ private ContactEventDto convertToDto(ContactEvent contactEvent) {
}

private ContactEvent convertToEntity(ContactEventDto contactEventDto) {
return modelMapper.map(contactEventDto, ContactEvent.class);
return modelMapper.map(contactEventDto, ContactEvent.class);
}

class ContactEventPage extends PageImpl<ContactEventDto> {
Expand All @@ -132,4 +123,5 @@ public ContactEventPage(List<ContactEventDto> content, Pageable pageable, long t
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
@Setter
public class ContactEventDto {

private Long id;
private String identifier;
private Date eventDate;
@ContactEventTypeValid
Expand Down
Loading

0 comments on commit 8a65a0d

Please sign in to comment.