From 85b40424cefc2bd53b42ae8033e884591ba327ff Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:15:13 +0800 Subject: [PATCH] feat(counter): registration links and QR self-registration capture Registration links (event code and personal codes, oldest wins on a duplicate), lookup by token, the caller's own codes, and the capture that matches by mobile then email, never edits a matched lead, and records the source and consent. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../controller/RegistrationController.java | 46 +++ .../services/counter/model/EventLead.java | 7 + .../counter/model/RegistrationLink.java | 40 +++ .../counter/repo/EventRepository.java | 1 + .../repo/EventSalespersonRepository.java | 2 + .../services/counter/repo/LeadRepository.java | 4 + .../repo/RegistrationLinkRepository.java | 17 ++ .../counter/service/EventLeadService.java | 4 +- .../service/RegistrationLinkService.java | 128 +++++++++ .../counter/service/RegistrationService.java | 123 ++++++++ .../service/RegistrationLinkServiceTest.java | 243 ++++++++++++++++ .../service/RegistrationServiceTest.java | 264 ++++++++++++++++++ 12 files changed, 877 insertions(+), 2 deletions(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/controller/RegistrationController.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/model/RegistrationLink.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/repo/RegistrationLinkRepository.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkServiceTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationServiceTest.java diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/RegistrationController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/RegistrationController.java new file mode 100644 index 0000000..45c51ae --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/RegistrationController.java @@ -0,0 +1,46 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.service.RegistrationLinkService; +import com.solvway.services.counter.service.RegistrationService; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/counter") +@AllArgsConstructor +public class RegistrationController { + private final RegistrationLinkService linkService; + private final RegistrationService registrationService; + + @PostMapping("/registrationLink/ensure") + public List ensure(@RequestBody RegistrationLinkService.EnsureRequest req) { + return linkService.ensure(req); + } + + @PostMapping("/registrationLink/setEnabled") + public RegistrationLinkService.LinkView setEnabled(@RequestBody RegistrationLinkService.SetEnabledRequest req) { + return linkService.setEnabled(req); + } + + @GetMapping("/registrationLink/findByToken/{token}") + public RegistrationLinkService.LinkLookup findByToken(@PathVariable("token") String token) { + return linkService.findByToken(token); + } + + @PostMapping("/registrationLink/mine") + public List mine(@RequestBody RegistrationLinkService.MineRequest req) { + return linkService.mine(req); + } + + @PostMapping("/registration/register") + public RegistrationService.RegisterResult register(@RequestBody RegistrationService.RegisterRequest req) { + return registrationService.register(req); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java index 82c44b6..692f642 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java @@ -48,6 +48,13 @@ public class EventLead { private String capturedBy; + /** STAFF (captured in the portal) or QR (self-registered). */ + private String source = "STAFF"; + + private LocalDateTime consentAt; + + private Long consentNoticeId; + @Column(updatable = false) private LocalDateTime capturedAt = LocalDateTime.now(); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/RegistrationLink.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/RegistrationLink.java new file mode 100644 index 0000000..7b82e3b --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/RegistrationLink.java @@ -0,0 +1,40 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +/** A QR registration code: salespersonUserId null is the event code, otherwise a salesperson's personal code. */ +@Getter +@Setter +@Entity +@Table(name = "registration_link") +public class RegistrationLink { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private long companyId; + + @Column(name = "event_uuid") + private long eventUuid; + + @Column(name = "salesperson_user_id") + private Long salespersonUserId; + + private String token; + + private boolean enabled = true; + + @Column(updatable = false) + private String createdBy; + + @Column(updatable = false) + private LocalDateTime createdAt = LocalDateTime.now(); + + private String updatedBy; + + private LocalDateTime updatedAt; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java index c6f7cdf..07ac178 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java @@ -12,6 +12,7 @@ import java.util.Optional; @Repository public interface EventRepository extends JpaRepository , JpaRepositoryCustom{ Optional findByUuid(long uuid); + java.util.List findByCompanyIdAndUuidIn(Long companyId, java.util.Collection uuids); Optional findTop1ByDateStartLessThanEqualAndDateEndGreaterThanEqualAndEnabledOrderByDateStartDesc(LocalDateTime dateStart, LocalDateTime dateEnd, GeneralEnum.FlagYesNo enabled); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java index de84937..40f8116 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventSalespersonRepository.java @@ -13,6 +13,8 @@ import java.util.List; public interface EventSalespersonRepository extends JpaRepository { List findByEventUuid(long eventUuid); + List findByCompanyIdAndUserId(long companyId, long userId); + @Modifying @Query("delete from EventSalesperson e where e.eventUuid = :eventUuid") void deleteByEventUuid(@Param("eventUuid") long eventUuid); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java index 2539fa8..62a4a4a 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java @@ -19,6 +19,10 @@ public interface LeadRepository extends JpaRepository { List findMatches(@Param("companyId") long companyId, @Param("mobile") String mobile, @Param("email") String email, Pageable pageable); + Optional findFirstByCompanyIdAndMobileE164OrderByIdDesc(long companyId, String mobileE164); + + Optional findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(long companyId, String emailNormalised); + Optional findByUuidAndCompanyId(long uuid, long companyId); Optional findByUuid(long uuid); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/RegistrationLinkRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/RegistrationLinkRepository.java new file mode 100644 index 0000000..1364322 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/RegistrationLinkRepository.java @@ -0,0 +1,17 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.RegistrationLink; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface RegistrationLinkRepository extends JpaRepository { + Optional findByToken(String token); + + Optional findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(long eventUuid, long salespersonUserId); + + List findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(long eventUuid); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java index f73f635..06c8df0 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java @@ -175,7 +175,7 @@ public class EventLeadService { return detail(eventLead, lead, interestIds); } - private void recordStatusChange(EventLead e, String from, String to, LocalDateTime at, String by) { + public void recordStatusChange(EventLead e, String from, String to, LocalDateTime at, String by) { EventLeadStatusChange row = new EventLeadStatusChange(); row.setCompanyId(e.getCompanyId()); row.setEventLeadId(e.getId()); @@ -190,7 +190,7 @@ public class EventLeadService { if (companyId == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); } - private List saveInterests(long eventLeadId, long companyId, List requested) { + public List saveInterests(long eventLeadId, long companyId, List requested) { List ids = requested == null ? List.of() : requested.stream().filter(Objects::nonNull).distinct().toList(); if (!ids.isEmpty()) { eventLeadInterestRepository.saveAll(ids.stream().map(id -> { diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java new file mode 100644 index 0000000..276027d --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationLinkService.java @@ -0,0 +1,128 @@ +package com.solvway.services.counter.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventSalesperson; +import com.solvway.services.counter.model.RegistrationLink; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.EventSalespersonRepository; +import com.solvway.services.counter.repo.RegistrationLinkRepository; +import lombok.AllArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.security.SecureRandom; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + +/** QR registration codes per event: one event code and one personal code per salesperson. */ +@Service +@AllArgsConstructor +public class RegistrationLinkService { + private static final SecureRandom RANDOM = new SecureRandom(); + + public record EnsureRequest(Long companyId, long eventUuid, List salespersonUserIds) {} + public record SetEnabledRequest(Long companyId, long eventUuid, String token, boolean enabled, String doneBy) {} + public record MineRequest(Long companyId, long userId, String today) {} + public record LinkView(long eventUuid, Long salespersonUserId, String token, boolean enabled) {} + public record LinkLookup(long companyId, long eventUuid, Long salespersonUserId, String token, boolean enabled) {} + public record MineRow(String eventUuid, String eventName, String startDate, String endDate, String location, + String token, boolean enabled) {} + + private final RegistrationLinkRepository linkRepository; + private final EventRepository eventRepository; + private final EventSalespersonRepository eventSalespersonRepository; + + @Transactional + public List ensure(EnsureRequest req) { + requireEvent(req.companyId(), req.eventUuid()); + List out = new ArrayList<>(); + out.add(eventCode(req.companyId(), req.eventUuid())); + if (req.salespersonUserIds() != null) { + req.salespersonUserIds().stream().filter(Objects::nonNull).distinct() + .forEach(uid -> out.add(personal(req.companyId(), req.eventUuid(), uid))); + } + return out.stream().map(RegistrationLinkService::view).toList(); + } + + @Transactional + public LinkView setEnabled(SetEnabledRequest req) { + requireEvent(req.companyId(), req.eventUuid()); + RegistrationLink link = linkRepository.findByToken(req.token()) + .filter(l -> l.getEventUuid() == req.eventUuid() && l.getCompanyId() == req.companyId()) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + link.setEnabled(req.enabled()); + link.setUpdatedBy(req.doneBy()); + link.setUpdatedAt(LocalDateTime.now()); + return view(linkRepository.save(link)); + } + + public LinkLookup findByToken(String token) { + RegistrationLink l = linkRepository.findByToken(token) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + return new LinkLookup(l.getCompanyId(), l.getEventUuid(), l.getSalespersonUserId(), l.getToken(), l.isEnabled()); + } + + @Transactional + public List mine(MineRequest req) { + LocalDate today = LocalDate.parse(req.today()); + List uuids = eventSalespersonRepository.findByCompanyIdAndUserId(req.companyId(), req.userId()).stream() + .map(EventSalesperson::getEventUuid).toList(); + if (uuids.isEmpty()) return List.of(); + return eventRepository.findByCompanyIdAndUuidIn(req.companyId(), uuids).stream() + .filter(e -> e.getEnabled() == GeneralEnum.FlagYesNo.Y && !e.getDateEnd().toLocalDate().isBefore(today)) + .sorted(Comparator.comparing(Event::getDateStart)) + .map(e -> { + RegistrationLink l = personal(req.companyId(), e.getUuid(), req.userId()); + return new MineRow(String.valueOf(e.getUuid()), e.getName(), e.getDateStart().toLocalDate().toString(), + e.getDateEnd().toLocalDate().toString(), e.getLocation(), l.getToken(), l.isEnabled()); + }).toList(); + } + + private void requireEvent(Long companyId, long eventUuid) { + eventRepository.findByUuid(eventUuid) + .filter(e -> companyId != null && companyId.equals(e.getCompanyId())) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND")); + } + + private RegistrationLink eventCode(long companyId, long eventUuid) { + List codes = linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(eventUuid); + if (codes.isEmpty()) { + // The key is not unique, so concurrent first calls can each insert a code and each return its own once + // (REPEATABLE READ hides the other insert from this re-read). Later calls converge on the oldest row; + // the losing token stays enabled but is never shown. + // ponytail: no unique key for personal/event codes; add one, or re-read in a new transaction, if it matters. + linkRepository.save(newLink(companyId, eventUuid, null)); + codes = linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(eventUuid); + } + return codes.get(0); + } + + private RegistrationLink personal(long companyId, long eventUuid, long userId) { + return linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(eventUuid, userId) + .orElseGet(() -> linkRepository.save(newLink(companyId, eventUuid, userId))); + } + + private static RegistrationLink newLink(long companyId, long eventUuid, Long userId) { + byte[] bytes = new byte[16]; + RANDOM.nextBytes(bytes); + RegistrationLink l = new RegistrationLink(); + l.setCompanyId(companyId); + l.setEventUuid(eventUuid); + l.setSalespersonUserId(userId); + l.setToken(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); + l.setCreatedBy("system"); + return l; + } + + private static LinkView view(RegistrationLink l) { + return new LinkView(l.getEventUuid(), l.getSalespersonUserId(), l.getToken(), l.isEnabled()); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java new file mode 100644 index 0000000..b2d4eb0 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java @@ -0,0 +1,123 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import lombok.AllArgsConstructor; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * QR self-registration. Values arrive validated and normalised by mobile-api, which also picks the salesperson. + * Never log a lead's name, mobile or email. + */ +@Service +@AllArgsConstructor +public class RegistrationService { + public record RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164, + String email, String companyName, String jobTitle, List interestIds, + Long consentNoticeId, LocalDateTime consentAt) {} + public record RegisterResult(String outcome, String eventLeadUuid) {} + + private static final String QR = "qr"; + + private final TransactionTemplate transactionTemplate; + private final LeadRepository leadRepository; + private final EventLeadRepository eventLeadRepository; + private final EventLeadService eventLeadService; + + public RegisterResult register(RegisterRequest req) { + try { + return transactionTemplate.execute(s -> registerOnce(req)); + } catch (DataIntegrityViolationException e) { + // Any constraint violation lands here, not only uk_event_lead_event_lead (the same person captured at + // this event between our lookup and insert); one retry, then the exception propagates. + // The failed flush leaves the transaction rollback-only and the session unusable, so the exception + // must not be handled inside it. It has been rolled back by now; a second run in a fresh transaction + // finds the winner's row by the normal lookup and reports ALREADY_CAPTURED or ASSIGNED. + return transactionTemplate.execute(s -> registerOnce(req)); + } + } + + private RegisterResult registerOnce(RegisterRequest req) { + Optional match = Optional.empty(); + if (req.mobileE164() != null) { + match = leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(req.companyId(), req.mobileE164()); + } + if (match.isEmpty() && req.email() != null) { + match = leadRepository.findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(req.companyId(), req.email()); + } + + Lead lead; + String leadType; + String notes = null; + if (match.isEmpty()) { + lead = new Lead(); + lead.setCompanyId(req.companyId()); + lead.setName(req.name()); + lead.setMobileE164(req.mobileE164()); + lead.setEmailNormalised(req.email()); + lead.setCompanyName(req.companyName()); + lead.setJobTitle(req.jobTitle()); + lead.setCreatedBy(QR); + lead = leadRepository.saveAndFlush(lead); + leadType = "NEW"; + } else { + lead = match.get(); + Optional captured = eventLeadRepository.findByEventUuidAndLeadUuid(req.eventUuid(), lead.getUuid()); + if (captured.isPresent()) return alreadyCaptured(captured.get(), req.salespersonUserId()); + notes = differences(lead, req); + leadType = "EXISTING"; + } + + EventLead e = new EventLead(); + e.setCompanyId(req.companyId()); + e.setEventUuid(req.eventUuid()); + e.setLeadUuid(lead.getUuid()); + e.setSalespersonUserId(req.salespersonUserId()); + e.setLeadType(leadType); + e.setStatus("OPEN"); + e.setNotes(notes); + e.setSource("QR"); + e.setCapturedBy(QR); + e.setConsentAt(req.consentAt()); + e.setConsentNoticeId(req.consentNoticeId()); + e = eventLeadRepository.saveAndFlush(e); + eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR); + eventLeadService.saveInterests(e.getId(), req.companyId(), req.interestIds()); + return new RegisterResult(match.isEmpty() ? "CREATED" : "LINKED", String.valueOf(e.getUuid())); + } + + private RegisterResult alreadyCaptured(EventLead e, Long salespersonUserId) { + if (e.getSalespersonUserId() == null && salespersonUserId != null) { + e.setSalespersonUserId(salespersonUserId); + e.setUpdatedBy(QR); + e.setUpdatedAt(LocalDateTime.now()); + eventLeadRepository.save(e); + return new RegisterResult("ASSIGNED", String.valueOf(e.getUuid())); + } + return new RegisterResult("ALREADY_CAPTURED", String.valueOf(e.getUuid())); + } + + /** Submitted non-blank values that differ from the lead's, as an event-lead note; null when nothing differs. */ + private static String differences(Lead lead, RegisterRequest req) { + List parts = new ArrayList<>(); + diff(parts, "name", req.name(), lead.getName()); + diff(parts, "mobile", req.mobileE164(), lead.getMobileE164()); + diff(parts, "email", req.email(), lead.getEmailNormalised()); + diff(parts, "company", req.companyName(), lead.getCompanyName()); + diff(parts, "job title", req.jobTitle(), lead.getJobTitle()); + return parts.isEmpty() ? null : "Registered by QR with: " + String.join("; ", parts); + } + + private static void diff(List parts, String label, String submitted, String current) { + if (submitted != null && !submitted.isBlank() && !submitted.equals(current)) parts.add(label + " " + submitted); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkServiceTest.java new file mode 100644 index 0000000..264147b --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationLinkServiceTest.java @@ -0,0 +1,243 @@ +package com.solvway.services.counter.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventSalesperson; +import com.solvway.services.counter.model.RegistrationLink; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.EventSalespersonRepository; +import com.solvway.services.counter.repo.RegistrationLinkRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.AdditionalAnswers.returnsFirstArg; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class RegistrationLinkServiceTest { + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + + @Mock private RegistrationLinkRepository linkRepository; + @Mock private EventRepository eventRepository; + @Mock private EventSalespersonRepository eventSalespersonRepository; + + private RegistrationLinkService service; + + @BeforeEach + void setUp() { + service = new RegistrationLinkService(linkRepository, eventRepository, eventSalespersonRepository); + lenient().when(linkRepository.save(any(RegistrationLink.class))).then(returnsFirstArg()); + } + + private static Event event(long uuid, long company, String name, LocalDateTime start, LocalDateTime end, GeneralEnum.FlagYesNo enabled) { + Event e = new Event(); + // uuid is a field with a default; set through reflection-free route: the setter exists via Lombok + e.setUuid(uuid); + e.setName(name); + e.setLocation("KLCC"); + e.setDateStart(start); + e.setDateEnd(end); + e.setEnabled(enabled); + try { + var f = Event.class.getDeclaredField("companyId"); + f.setAccessible(true); + f.set(e, company); + } catch (ReflectiveOperationException ex) { + throw new IllegalStateException(ex); + } + return e; + } + + private static RegistrationLink link(Long salesperson, String token, boolean enabled) { + RegistrationLink l = new RegistrationLink(); + l.setCompanyId(COMPANY); + l.setEventUuid(EVENT); + l.setSalespersonUserId(salesperson); + l.setToken(token); + l.setEnabled(enabled); + return l; + } + + private void eventInCompany() { + when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(event(EVENT, COMPANY, "Expo", LocalDateTime.now(), LocalDateTime.now(), GeneralEnum.FlagYesNo.Y))); + } + + // --- ensure --- + + @Test + void ensureCreatesEventCodeThenPersonalCodesInGivenOrderWith22CharTokens() { + eventInCompany(); + RegistrationLink code = link(null, "EVENTCODE", true); + when(linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(EVENT)).thenReturn(List.of()).thenReturn(List.of(code)); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(eq(EVENT), anyLong())).thenReturn(Optional.empty()); + + List out = service.ensure(new RegistrationLinkService.EnsureRequest(COMPANY, EVENT, List.of(9L, 7L))); + + assertThat(out).extracting(RegistrationLinkService.LinkView::salespersonUserId).containsExactly(null, 9L, 7L); + assertThat(out.get(0).token()).isEqualTo("EVENTCODE"); + assertThat(out.get(1).token()).hasSize(22).matches("[A-Za-z0-9_-]{22}"); + assertThat(out.get(1).token()).isNotEqualTo(out.get(2).token()); + assertThat(out).allMatch(RegistrationLinkService.LinkView::enabled); + ArgumentCaptor saved = ArgumentCaptor.forClass(RegistrationLink.class); + verify(linkRepository, times(3)).save(saved.capture()); + assertThat(saved.getAllValues()).allMatch(l -> l.getCompanyId() == COMPANY && l.getEventUuid() == EVENT && "system".equals(l.getCreatedBy())); + } + + @Test + void ensureCreatesNothingWhenAllCodesExist() { + eventInCompany(); + when(linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(EVENT)).thenReturn(List.of(link(null, "E", true))); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(EVENT, 9L)).thenReturn(Optional.of(link(9L, "P9", false))); + + List out = service.ensure(new RegistrationLinkService.EnsureRequest(COMPANY, EVENT, List.of(9L))); + + assertThat(out).extracting(RegistrationLinkService.LinkView::token).containsExactly("E", "P9"); + assertThat(out.get(1).enabled()).isFalse(); + verify(linkRepository, never()).save(any()); + } + + @Test + void ensureUsesOldestEventCodeWhenAConcurrentEnsureInsertedAnother() { + eventInCompany(); + when(linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(EVENT)) + .thenReturn(List.of()) + .thenReturn(List.of(link(null, "OLDEST", true), link(null, "NEWER", true))); + + List out = service.ensure(new RegistrationLinkService.EnsureRequest(COMPANY, EVENT, List.of())); + + assertThat(out).extracting(RegistrationLinkService.LinkView::token).containsExactly("OLDEST"); + } + + @Test + void ensureIs404WhenEventIsInAnotherCompany() { + when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(event(EVENT, 99L, "Expo", LocalDateTime.now(), LocalDateTime.now(), GeneralEnum.FlagYesNo.Y))); + + assertThatThrownBy(() -> service.ensure(new RegistrationLinkService.EnsureRequest(COMPANY, EVENT, List.of()))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + verify(linkRepository, never()).save(any()); + } + + // --- setEnabled --- + + @Test + void setEnabledUpdatesLinkAndAudit() { + eventInCompany(); + RegistrationLink l = link(null, "T", true); + when(linkRepository.findByToken("T")).thenReturn(Optional.of(l)); + + RegistrationLinkService.LinkView v = service.setEnabled(new RegistrationLinkService.SetEnabledRequest(COMPANY, EVENT, "T", false, "admin")); + + assertThat(v.enabled()).isFalse(); + assertThat(l.getUpdatedBy()).isEqualTo("admin"); + assertThat(l.getUpdatedAt()).isNotNull(); + verify(linkRepository).save(l); + } + + @Test + void setEnabledRefusesAnotherCompanysToken() { + eventInCompany(); + RegistrationLink l = link(null, "T", true); + l.setCompanyId(99L); + when(linkRepository.findByToken("T")).thenReturn(Optional.of(l)); + + assertThatThrownBy(() -> service.setEnabled(new RegistrationLinkService.SetEnabledRequest(COMPANY, EVENT, "T", false, "a"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + verify(linkRepository, never()).save(any()); + } + + @Test + void setEnabledRefusesAnotherEventsToken() { + eventInCompany(); + RegistrationLink l = link(null, "T", true); + l.setEventUuid(555L); + when(linkRepository.findByToken("T")).thenReturn(Optional.of(l)); + + assertThatThrownBy(() -> service.setEnabled(new RegistrationLinkService.SetEnabledRequest(COMPANY, EVENT, "T", false, "a"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + // --- findByToken --- + + @Test + void findByTokenReturnsTheLink() { + when(linkRepository.findByToken("T")).thenReturn(Optional.of(link(7L, "T", true))); + + RegistrationLinkService.LinkLookup v = service.findByToken("T"); + + assertThat(v.companyId()).isEqualTo(COMPANY); + assertThat(v.eventUuid()).isEqualTo(EVENT); + assertThat(v.salespersonUserId()).isEqualTo(7L); + assertThat(v.enabled()).isTrue(); + } + + @Test + void findByTokenIs404WhenUnknown() { + when(linkRepository.findByToken("X")).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.findByToken("X")) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + // --- mine --- + + @Test + void ensureUsesOldestPersonalCodeFirstLookupSoDuplicatesNeverBreakIt() { + eventInCompany(); + when(linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(EVENT)).thenReturn(List.of(link(null, "E", true))); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(EVENT, 9L)).thenReturn(Optional.of(link(9L, "OLDEST", true))); + + List out = service.ensure(new RegistrationLinkService.EnsureRequest(COMPANY, EVENT, List.of(9L))); + + assertThat(out).extracting(RegistrationLinkService.LinkView::token).containsExactly("E", "OLDEST"); + verify(linkRepository, never()).save(any()); + } + + @Test + void mineListsOnlyEnabledNotEndedTeamEventsOrderedByStartAndCreatesMissingLinks() { + EventSalesperson r1 = new EventSalesperson(); r1.setEventUuid(1L); + EventSalesperson r2 = new EventSalesperson(); r2.setEventUuid(2L); + EventSalesperson r3 = new EventSalesperson(); r3.setEventUuid(3L); + EventSalesperson r4 = new EventSalesperson(); r4.setEventUuid(4L); + when(eventSalespersonRepository.findByCompanyIdAndUserId(COMPANY, 7L)).thenReturn(List.of(r1, r2, r3, r4)); + Event later = event(1L, COMPANY, "Later", LocalDateTime.of(2026, 12, 10, 9, 0), LocalDateTime.of(2026, 12, 12, 18, 0), GeneralEnum.FlagYesNo.Y); + Event endsToday = event(2L, COMPANY, "EndsToday", LocalDateTime.of(2026, 12, 1, 9, 0), LocalDateTime.of(2026, 12, 1, 1, 0), GeneralEnum.FlagYesNo.Y); + Event ended = event(3L, COMPANY, "Ended", LocalDateTime.of(2026, 11, 1, 9, 0), LocalDateTime.of(2026, 11, 30, 23, 59), GeneralEnum.FlagYesNo.Y); + Event disabled = event(4L, COMPANY, "Off", LocalDateTime.of(2026, 12, 5, 9, 0), LocalDateTime.of(2026, 12, 6, 9, 0), GeneralEnum.FlagYesNo.N); + when(eventRepository.findByCompanyIdAndUuidIn(eq(COMPANY), anyCollection())).thenReturn(List.of(later, endsToday, ended, disabled)); + RegistrationLink existing = link(7L, "HAVE", true); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(1L, 7L)).thenReturn(Optional.of(existing)); + when(linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(2L, 7L)).thenReturn(Optional.empty()); + + List out = service.mine(new RegistrationLinkService.MineRequest(COMPANY, 7L, "2026-12-01")); + + assertThat(out).extracting(RegistrationLinkService.MineRow::eventName).containsExactly("EndsToday", "Later"); + assertThat(out.get(1).eventUuid()).isEqualTo("1"); + assertThat(out.get(1).startDate()).isEqualTo("2026-12-10"); + assertThat(out.get(1).endDate()).isEqualTo("2026-12-12"); + assertThat(out.get(1).location()).isEqualTo("KLCC"); + assertThat(out.get(1).token()).isEqualTo("HAVE"); + assertThat(out.get(0).token()).hasSize(22); + verify(linkRepository, times(1)).save(any()); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationServiceTest.java new file mode 100644 index 0000000..8f902f6 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationServiceTest.java @@ -0,0 +1,264 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.EventLeadInterest; +import com.solvway.services.counter.model.EventLeadStatusChange; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadInterestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventLeadStatusChangeRepository; +import com.solvway.services.counter.repo.LeadRepository; +import com.solvway.services.counter.dto.EventLeadCaptureRequest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.AdditionalAnswers.returnsFirstArg; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class RegistrationServiceTest { + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + private static final String MOBILE = "+60123456789"; + private static final String EMAIL = "aisyah@example.com"; + private static final LocalDateTime CONSENT_AT = LocalDateTime.of(2026, 12, 1, 10, 0); + + @Mock private LeadRepository leadRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private EventLeadInterestRepository interestRepository; + @Mock private EventLeadStatusChangeRepository statusChangeRepository; + + private RegistrationService service; + private EventLeadService eventLeadService; + + @BeforeEach + void setUp() { + eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, interestRepository, statusChangeRepository); + service = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)), + leadRepository, eventLeadRepository, eventLeadService); + lenient().when(leadRepository.saveAndFlush(any(Lead.class))).then(returnsFirstArg()); + lenient().when(eventLeadRepository.saveAndFlush(any(EventLead.class))).then(i -> { + EventLead e = i.getArgument(0); + e.setId(1L); + return e; + }); + } + + private static Lead lead(String name, String mobile, String email, String company, String job) { + Lead l = new Lead(); + l.setCompanyId(COMPANY); + l.setName(name); + l.setMobileE164(mobile); + l.setEmailNormalised(email); + l.setCompanyName(company); + l.setJobTitle(job); + return l; + } + + private static RegistrationService.RegisterRequest req(String name, String mobile, String email, String company, String job, Long salesperson) { + return new RegistrationService.RegisterRequest(COMPANY, EVENT, salesperson, name, mobile, email, company, job, + List.of(5L, 6L), 77L, CONSENT_AT); + } + + private EventLead savedEventLead() { + ArgumentCaptor c = ArgumentCaptor.forClass(EventLead.class); + verify(eventLeadRepository).saveAndFlush(c.capture()); + return c.getValue(); + } + + @Test + void newPersonCreatesLeadAndEventLeadWithHistoryInterestsAndConsent() { + RegistrationService.RegisterResult r = service.register(req("Aisyah", MOBILE, EMAIL, "Acme", "CEO", 7L)); + + assertThat(r.outcome()).isEqualTo("CREATED"); + ArgumentCaptor lc = ArgumentCaptor.forClass(Lead.class); + verify(leadRepository).saveAndFlush(lc.capture()); + Lead l = lc.getValue(); + assertThat(l.getCompanyId()).isEqualTo(COMPANY); + assertThat(l.getName()).isEqualTo("Aisyah"); + assertThat(l.getMobileE164()).isEqualTo(MOBILE); + assertThat(l.getEmailNormalised()).isEqualTo(EMAIL); + assertThat(l.getCompanyName()).isEqualTo("Acme"); + assertThat(l.getJobTitle()).isEqualTo("CEO"); + assertThat(l.getCreatedBy()).isEqualTo("qr"); + EventLead e = savedEventLead(); + assertThat(r.eventLeadUuid()).isEqualTo(String.valueOf(e.getUuid())); + assertThat(e.getLeadUuid()).isEqualTo(l.getUuid()); + assertThat(e.getLeadType()).isEqualTo("NEW"); + assertThat(e.getStatus()).isEqualTo("OPEN"); + assertThat(e.getSource()).isEqualTo("QR"); + assertThat(e.getCapturedBy()).isEqualTo("qr"); + assertThat(e.getSalespersonUserId()).isEqualTo(7L); + assertThat(e.getConsentAt()).isEqualTo(CONSENT_AT); + assertThat(e.getConsentNoticeId()).isEqualTo(77L); + assertThat(e.getNotes()).isNull(); + ArgumentCaptor hc = ArgumentCaptor.forClass(EventLeadStatusChange.class); + verify(statusChangeRepository).save(hc.capture()); + assertThat(hc.getValue().getFromStatus()).isNull(); + assertThat(hc.getValue().getToStatus()).isEqualTo("OPEN"); + assertThat(hc.getValue().getChangedBy()).isEqualTo("qr"); + @SuppressWarnings("unchecked") ArgumentCaptor> ic = ArgumentCaptor.forClass(Iterable.class); + verify(interestRepository).saveAll(ic.capture()); + assertThat(ic.getValue()).hasSize(2); + } + + @Test + void knownByMobileLeavesLeadUntouchedAndNotesOnlyDifferingValues() { + Lead existing = lead("Aisyah", MOBILE, "old@example.com", "Acme", null); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + + RegistrationService.RegisterResult r = service.register(req("Aisyah Binti", MOBILE, EMAIL, "Acme", "CEO", null)); + + assertThat(r.outcome()).isEqualTo("LINKED"); + verify(leadRepository, never()).saveAndFlush(any()); + verify(leadRepository, never()).save(any()); + assertThat(existing.getName()).isEqualTo("Aisyah"); + assertThat(existing.getUpdatedAt()).isNull(); + EventLead e = savedEventLead(); + assertThat(e.getLeadType()).isEqualTo("EXISTING"); + assertThat(e.getLeadUuid()).isEqualTo(existing.getUuid()); + assertThat(e.getSource()).isEqualTo("QR"); + assertThat(e.getNotes()).isEqualTo("Registered by QR with: name Aisyah Binti; email aisyah@example.com; job title CEO"); + } + + @Test + void knownPersonWithNothingDifferingHasNullNotes() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, "Acme", "CEO"); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + + service.register(req("Aisyah", MOBILE, EMAIL, "Acme", "CEO", null)); + + assertThat(savedEventLead().getNotes()).isNull(); + } + + @Test + void blankSubmittedValuesAreNotNoted() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, "Acme", "CEO"); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + + service.register(req("Aisyah", MOBILE, EMAIL, " ", null, null)); + + assertThat(savedEventLead().getNotes()).isNull(); + } + + @Test + void mobileMatchBeatsEmailMatch() { + Lead byMobile = lead("ByMobile", MOBILE, null, null, null); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(byMobile)); + + service.register(req("X", MOBILE, EMAIL, null, null, null)); + + assertThat(savedEventLead().getLeadUuid()).isEqualTo(byMobile.getUuid()); + verify(leadRepository, never()).findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(any(Long.class), any()); + } + + @Test + void fallsBackToEmailWhenMobileMatchesNothingOrIsNull() { + Lead byEmail = lead("ByEmail", null, EMAIL, null, null); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.empty()); + when(leadRepository.findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(COMPANY, EMAIL)).thenReturn(Optional.of(byEmail)); + + service.register(req("ByEmail", MOBILE, EMAIL, null, null, null)); + + assertThat(savedEventLead().getLeadUuid()).isEqualTo(byEmail.getUuid()); + } + + @Test + void nullMobileAndEmailMatchNothing() { + RegistrationService.RegisterResult r = service.register(req("Aisyah", null, null, null, null, null)); + + assertThat(r.outcome()).isEqualTo("CREATED"); + verify(leadRepository, never()).findFirstByCompanyIdAndMobileE164OrderByIdDesc(any(Long.class), any()); + verify(leadRepository, never()).findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(any(Long.class), any()); + } + + @Test + void alreadyCapturedUnassignedGetsTheSalesperson() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, null, null); + EventLead captured = new EventLead(); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, existing.getUuid())).thenReturn(Optional.of(captured)); + + RegistrationService.RegisterResult r = service.register(req("Aisyah", MOBILE, EMAIL, null, null, 7L)); + + assertThat(r.outcome()).isEqualTo("ASSIGNED"); + assertThat(r.eventLeadUuid()).isEqualTo(String.valueOf(captured.getUuid())); + assertThat(captured.getSalespersonUserId()).isEqualTo(7L); + assertThat(captured.getUpdatedBy()).isEqualTo("qr"); + assertThat(captured.getUpdatedAt()).isNotNull(); + verify(eventLeadRepository).save(captured); + verify(statusChangeRepository, never()).save(any()); + } + + @Test + void alreadyCapturedWithSalespersonChangesNothing() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, null, null); + EventLead captured = new EventLead(); + captured.setSalespersonUserId(3L); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, existing.getUuid())).thenReturn(Optional.of(captured)); + + RegistrationService.RegisterResult r = service.register(req("Aisyah", MOBILE, EMAIL, null, null, 7L)); + + assertThat(r.outcome()).isEqualTo("ALREADY_CAPTURED"); + assertThat(captured.getSalespersonUserId()).isEqualTo(3L); + assertThat(captured.getUpdatedAt()).isNull(); + verify(eventLeadRepository, never()).save(any()); + verify(eventLeadRepository, never()).saveAndFlush(any()); + } + + @Test + void alreadyCapturedUnassignedWithNoSalespersonChangesNothing() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, null, null); + EventLead captured = new EventLead(); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, existing.getUuid())).thenReturn(Optional.of(captured)); + + assertThat(service.register(req("Aisyah", MOBILE, EMAIL, null, null, null)).outcome()).isEqualTo("ALREADY_CAPTURED"); + verify(eventLeadRepository, never()).save(any()); + } + + @Test + void uniqueKeyRaceRetriesInAFreshTransactionAndReportsAlreadyCaptured() { + Lead existing = lead("Aisyah", MOBILE, EMAIL, null, null); + EventLead winner = new EventLead(); + winner.setSalespersonUserId(3L); + when(leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(existing)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, existing.getUuid())) + .thenReturn(Optional.empty()).thenReturn(Optional.of(winner)); + when(eventLeadRepository.saveAndFlush(any(EventLead.class))).thenThrow(new DataIntegrityViolationException("uk_event_lead_event_lead")); + + RegistrationService.RegisterResult r = service.register(req("Aisyah", MOBILE, EMAIL, null, null, 7L)); + + assertThat(r.outcome()).isEqualTo("ALREADY_CAPTURED"); + assertThat(r.eventLeadUuid()).isEqualTo(String.valueOf(winner.getUuid())); + verify(eventLeadRepository, times(1)).saveAndFlush(any()); + verify(statusChangeRepository, never()).save(any()); + } + + @Test + void staffCaptureStillSourcesStaff() { + eventLeadService.capture(new EventLeadCaptureRequest(COMPANY, EVENT, null, "Aisyah", MOBILE, EMAIL, null, null, + 7L, null, null, List.of(), null, null, "staff1")); + + assertThat(savedEventLead().getSource()).isEqualTo("STAFF"); + } +}