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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-01 12:15:16 +08:00
1 parent 9c9469f5e5
commit 85b40424ce
12 files changed
+877 -2

No files matched your search

@@ -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<RegistrationLinkService.LinkView> 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<RegistrationLink> 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<RegistrationLinkService.LinkView> 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<RegistrationLinkService.LinkView> 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<RegistrationLinkService.LinkView> 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<RegistrationLinkService.MineRow> 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());
}
}
@@ -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<EventLead> 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<Lead> 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<EventLeadStatusChange> 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<Iterable<EventLeadInterest>> 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");
}
}