|
21 | 21 | import invite.model.Organisation; |
22 | 22 | import invite.model.Provisionable; |
23 | 23 | import invite.model.Role; |
| 24 | +import invite.model.Status; |
24 | 25 | import invite.model.User; |
25 | 26 | import invite.model.UserRole; |
26 | 27 | import invite.model.UserRoleAudit; |
@@ -448,6 +449,20 @@ private boolean sendInvitation(CRMContact crmContact, Organisation organisation) |
448 | 449 | Optional<User> optionalUser = |
449 | 450 | userRepository.findByCrmContactIdAndOrganisation( |
450 | 451 | crmContact.getContactId(), organisation); |
| 452 | + //Idempotency - if there is already an open invitation with the same roles for this contact / organisation then do nothing |
| 453 | + List<Invitation> invitations = invitationRepository |
| 454 | + .findByCrmContactIdAndCrmOrganisationId(crmContact.getContactId(), organisation.getCrmOrganisationId()); |
| 455 | + boolean duplicateInvitation = invitations.stream().anyMatch(invitation -> invitation.getStatus().equals(Status.OPEN) && |
| 456 | + invitation.getRoles().stream() |
| 457 | + .allMatch(invitationRole -> crmContact.getRoles().stream() |
| 458 | + .anyMatch(crmRole -> crmRole.getRoleId().equals(invitationRole.getRole().getCrmRoleId())))); |
| 459 | + if (duplicateInvitation) { |
| 460 | + LOG.info(String.format("Not sending invitation to %s as there is already an outstanding invitation with roles %s", |
| 461 | + crmContact.getEmail(), |
| 462 | + crmContact.getRoles().stream().map(crmRole -> crmRole.getName()).collect(Collectors.joining(", ")))); |
| 463 | + return false; |
| 464 | + } |
| 465 | + |
451 | 466 | List<CRMRole> newCrmRoles = syncCrmRoles(crmContact, optionalUser.orElse(new User())); |
452 | 467 | //Only save the user when the user already existed |
453 | 468 | optionalUser.ifPresent(user -> userRepository.save(user)); |
|
0 commit comments