From c700e1286584e6e40a356cd11c2a5853d347d778 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 17:08:54 +0800 Subject: [PATCH] feat: counter guest, invite registration and check-in endpoints Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../counter/controller/ApiErrorAdvice.java | 18 + .../controller/EventCheckInController.java | 37 ++ .../controller/EventGuestController.java | 50 +++ .../solvway/services/counter/model/Event.java | 2 + .../counter/repo/EventGuestRepository.java | 10 + .../counter/repo/EventLeadRepository.java | 10 + .../counter/repo/EventRepository.java | 11 + .../counter/service/EventCheckInService.java | 111 +++++ .../counter/service/EventGuestService.java | 201 +++++++++ .../services/counter/service/GuestLinker.java | 10 + .../service/RegistrationLinkService.java | 9 +- .../counter/service/RegistrationService.java | 18 +- .../controller/ApiErrorAdviceTest.java | 66 +++ .../service/EventCheckInServiceTest.java | 264 +++++++++++ .../service/EventGuestServiceTest.java | 417 ++++++++++++++++++ .../service/RegistrationInviteLinkTest.java | 107 +++++ 16 files changed, 1335 insertions(+), 6 deletions(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/controller/ApiErrorAdvice.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventCheckInController.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventGuestController.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventCheckInService.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventGuestService.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/controller/ApiErrorAdviceTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventCheckInServiceTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventGuestServiceTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationInviteLinkTest.java diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/ApiErrorAdvice.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/ApiErrorAdvice.java new file mode 100644 index 0000000..d57ea3d --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/ApiErrorAdvice.java @@ -0,0 +1,18 @@ +package com.solvway.services.counter.controller; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Map; + +/** Puts the reason of a ResponseStatusException into the body as `code`, which mobile-api reads. Limited to the invitation feature. */ +@RestControllerAdvice(assignableTypes = {EventGuestController.class, EventCheckInController.class, EventController.class}) +public class ApiErrorAdvice { + @ExceptionHandler(ResponseStatusException.class) + public ResponseEntity> handle(ResponseStatusException e) { + String reason = e.getReason() == null ? "" : e.getReason(); + return ResponseEntity.status(e.getStatusCode()).body(Map.of("code", reason, "message", reason)); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventCheckInController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventCheckInController.java new file mode 100644 index 0000000..8a0c851 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventCheckInController.java @@ -0,0 +1,37 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.service.EventCheckInService; +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; + +@RestController +@RequestMapping("/counter/checkin") +@AllArgsConstructor +public class EventCheckInController { + private final EventCheckInService service; + + @GetMapping("/findEvent/{token}") + public EventCheckInService.EventRef findEvent(@PathVariable("token") String token) { + return service.findEvent(token); + } + + @PostMapping("/ensureToken") + public EventCheckInService.TokenView ensureToken(@RequestBody EventCheckInService.EnsureRequest req) { + return service.ensureToken(req); + } + + @PostMapping("/lookup") + public EventCheckInService.LookupResult lookup(@RequestBody EventCheckInService.LookupRequest req) { + return service.lookup(req); + } + + @PostMapping("/byGuest") + public EventCheckInService.NameView byGuest(@RequestBody EventCheckInService.ByGuestRequest req) { + return service.byGuest(req); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventGuestController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventGuestController.java new file mode 100644 index 0000000..201aac5 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventGuestController.java @@ -0,0 +1,50 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.service.EventGuestService; +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/eventGuest") +@AllArgsConstructor +public class EventGuestController { + private final EventGuestService service; + + @PostMapping("/list") + public List list(@RequestBody EventGuestService.ListRequest req) { + return service.list(req); + } + + @PostMapping("/add") + public EventGuestService.AddResult add(@RequestBody EventGuestService.AddRequest req) { + return service.add(req); + } + + @PostMapping("/remove") + public void remove(@RequestBody EventGuestService.RemoveRequest req) { + service.remove(req); + } + + @PostMapping("/markSent") + public void markSent(@RequestBody EventGuestService.MarkSentRequest req) { + service.markSent(req); + } + + @GetMapping("/findByToken/{token}") + public EventGuestService.GuestLookup findByToken(@PathVariable("token") String token) { + return service.findByToken(token); + } + + @PostMapping("/register") + public RegistrationService.RegisterResult register(@RequestBody EventGuestService.GuestRegisterRequest req) { + return service.register(req); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java index 19ff6db..68c4b05 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java @@ -26,6 +26,8 @@ public class Event implements Serializable { private Long companyId; private Integer capacity; private Integer invitationCap; + @Column(name = "checkin_token", updatable = false) + private String checkinToken; private String uploadFloorPlan; private String uploadStageActivities; private String uploadLuckyDraw; diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventGuestRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventGuestRepository.java index 5e71d3c..d37d64e 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventGuestRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventGuestRepository.java @@ -4,6 +4,8 @@ import com.solvway.services.counter.model.EventGuest; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import java.util.Collection; +import java.util.List; import java.util.Optional; @Repository @@ -17,4 +19,12 @@ public interface EventGuestRepository extends JpaRepository { long countByEventUuid(long eventUuid); long countByEventUuidAndEventLeadIdIsNotNull(long eventUuid); + + List findByEventUuidOrderByNameAsc(long eventUuid); + + Optional findByToken(String token); + + Optional findByIdAndEventUuidAndCompanyId(Long id, long eventUuid, long companyId); + + List findByEventUuidAndCompanyIdAndIdIn(long eventUuid, long companyId, Collection ids); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java index 15724d4..3a215e5 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java @@ -51,4 +51,14 @@ public interface EventLeadRepository extends JpaRepository { @Query("SELECT e, ev FROM EventLead e LEFT JOIN Event ev ON ev.uuid = e.eventUuid" + " WHERE e.companyId = :companyId AND e.leadUuid = :leadUuid ORDER BY e.capturedAt DESC, e.id DESC") List history(@Param("companyId") long companyId, @Param("leadUuid") long leadUuid); + + /** Rows are [EventLead, Lead] of this event whose lead has the mobile. */ + @Query("SELECT e, l FROM EventLead e, Lead l WHERE l.uuid = e.leadUuid AND l.companyId = e.companyId" + + " AND e.eventUuid = :eventUuid AND l.mobileE164 = :mobile") + List findByEventAndMobile(@Param("eventUuid") long eventUuid, @Param("mobile") String mobile); + + /** Rows are [EventLead, Lead] of this event whose lead has the email. */ + @Query("SELECT e, l FROM EventLead e, Lead l WHERE l.uuid = e.leadUuid AND l.companyId = e.companyId" + + " AND e.eventUuid = :eventUuid AND l.emailNormalised = :email") + List findByEventAndEmail(@Param("eventUuid") long eventUuid, @Param("email") String email); } 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 07ac178..4866b33 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 @@ -4,6 +4,10 @@ import com.solvway.core.enums.GeneralEnum; import com.solvway.services.counter.configuration.JpaRepositoryCustom; import com.solvway.services.counter.model.Event; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; import org.springframework.stereotype.Repository; import java.time.LocalDateTime; @@ -12,6 +16,13 @@ import java.util.Optional; @Repository public interface EventRepository extends JpaRepository , JpaRepositoryCustom{ Optional findByUuid(long uuid); + Optional findByCheckinToken(String checkinToken); + + /** Sets the check-in token only while none exists; returns rows changed. Atomic, so concurrent callers agree on one token. */ + @Modifying(clearAutomatically = true) + @Transactional + @Query("UPDATE Event e SET e.checkinToken = :token WHERE e.uuid = :uuid AND e.checkinToken IS NULL") + int setCheckinTokenIfAbsent(@Param("uuid") long uuid, @Param("token") String token); 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/service/EventCheckInService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventCheckInService.java new file mode 100644 index 0000000..e729108 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventCheckInService.java @@ -0,0 +1,111 @@ +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.EventGuest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventGuestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.LeadRepository; +import lombok.AllArgsConstructor; +import com.solvway.services.counter.util.EventDays; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.List; + +/** Event-day check-in. Reveals a first name only, nothing else about a person. Never log contact data. */ +@Service +@AllArgsConstructor +public class EventCheckInService { + public record EventRef(long companyId, long eventUuid) {} + public record EnsureRequest(Long companyId, long eventUuid) {} + public record TokenView(String token) {} + public record LookupRequest(Long companyId, long eventUuid, String mobileE164, String email) {} + public record LookupResult(String result, String firstName) {} + public record ByGuestRequest(Long companyId, String guestToken) {} + public record NameView(String firstName) {} + + private final EventRepository eventRepository; + private final EventGuestRepository guestRepository; + private final EventLeadRepository eventLeadRepository; + private final LeadRepository leadRepository; + + private static ResponseStatusException notFound(String code) { + return new ResponseStatusException(HttpStatus.NOT_FOUND, code); + } + + private static long requireCompany(Long companyId) { + if (companyId == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); + return companyId; + } + + private Event event(Long companyId, long eventUuid) { + long company = requireCompany(companyId); + return eventRepository.findByUuid(eventUuid) + .filter(e -> company == e.getCompanyId()) + .orElseThrow(() -> notFound("EVENT_NOT_FOUND")); + } + + private static String firstName(String name) { + if (name == null) return null; + String t = name.trim(); + int sp = t.indexOf(' '); + return sp < 0 ? t : t.substring(0, sp); + } + + public EventRef findEvent(String token) { + Event e = eventRepository.findByCheckinToken(token).orElseThrow(() -> notFound("EVENT_NOT_FOUND")); + return new EventRef(e.getCompanyId(), e.getUuid()); + } + + public TokenView ensureToken(EnsureRequest req) { + Event e = event(req.companyId(), req.eventUuid()); + if (e.getCheckinToken() == null) { + // atomic: only the first writer wins; re-read so every caller returns the stored token + eventRepository.setCheckinTokenIfAbsent(req.eventUuid(), RegistrationLinkService.newToken()); + e = event(req.companyId(), req.eventUuid()); + } + return new TokenView(e.getCheckinToken()); + } + + public LookupResult lookup(LookupRequest req) { + Event event = event(req.companyId(), req.eventUuid()); + if (event.getEnabled() != GeneralEnum.FlagYesNo.Y) throw notFound("EVENT_NOT_FOUND"); + if (!EventDays.isDuring(event, LocalDateTime.now())) throw new ResponseStatusException(HttpStatus.CONFLICT, "NOT_EVENT_DAY"); + boolean hasMobile = req.mobileE164() != null && !req.mobileE164().isBlank(); + boolean hasEmail = req.email() != null && !req.email().isBlank(); + if (hasMobile == hasEmail) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "MOBILE_OR_EMAIL_REQUIRED"); + List rows = hasMobile ? eventLeadRepository.findByEventAndMobile(req.eventUuid(), req.mobileE164()) + : eventLeadRepository.findByEventAndEmail(req.eventUuid(), req.email()); + if (rows.isEmpty()) return new LookupResult("FORM", null); + EventLead el = (EventLead) rows.get(0)[0]; + Lead lead = (Lead) rows.get(0)[1]; + markAttended(el); + return new LookupResult("CHECKED_IN", firstName(lead.getName())); + } + + public NameView byGuest(ByGuestRequest req) { + long company = requireCompany(req.companyId()); + EventGuest g = guestRepository.findByToken(req.guestToken()) + .filter(x -> company == x.getCompanyId()) + .orElseThrow(() -> notFound("GUEST_NOT_FOUND")); + if (g.getEventLeadId() == null) throw new ResponseStatusException(HttpStatus.CONFLICT, "NOT_REGISTERED"); + if (!EventDays.isDuring(event(g.getCompanyId(), g.getEventUuid()), LocalDateTime.now())) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "NOT_EVENT_DAY"); + } + EventLead el = eventLeadRepository.findById(g.getEventLeadId()).orElseThrow(() -> notFound("GUEST_NOT_FOUND")); + markAttended(el); + return new NameView(leadRepository.findByUuid(el.getLeadUuid()).map(l -> firstName(l.getName())).orElse(null)); + } + + private void markAttended(EventLead el) { + if (el.getAttendedAt() != null) return; + el.setAttendedAt(LocalDateTime.now()); + eventLeadRepository.save(el); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventGuestService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventGuestService.java new file mode 100644 index 0000000..386e3af --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventGuestService.java @@ -0,0 +1,201 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventGuest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.EventSalesperson; +import com.solvway.services.counter.repo.EventGuestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.EventSalespersonRepository; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + +import com.solvway.services.counter.util.EventDays; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** Invitation list of an event and registration through a guest's personal link. Never log contact data. */ +@Service +@AllArgsConstructor +public class EventGuestService { + public record ListRequest(Long companyId, long eventUuid) {} + public record GuestInput(String name, String mobileE164, String email, String companyName, Long salespersonUserId) {} + public record AddRequest(Long companyId, long eventUuid, List guests, String doneBy) {} + public record RemoveRequest(Long companyId, long eventUuid, long guestId, String doneBy) {} + public record MarkSentRequest(Long companyId, long eventUuid, List guestIds, String doneBy) {} + public record GuestRow(long id, String name, String mobileE164, String email, String companyName, Long salespersonUserId, + String token, LocalDateTime invitedAt, int inviteSentCount, LocalDateTime registeredAt, + boolean attended, String eventLeadUuid) {} + public record Rejection(int index, String code, String field, String message) {} + public record AddResult(List added, List rejected) {} + public record GuestLookup(long companyId, long eventUuid, long guestId, String name, String mobileE164, String email, + String companyName, Long salespersonUserId, boolean registered, boolean attended) {} + public record GuestRegisterRequest(Long companyId, String guestToken, String name, String mobileE164, String email, + String companyName, String jobTitle, List interestIds, Long consentNoticeId, + LocalDateTime consentAt) {} + + private final EventRepository eventRepository; + private final EventGuestRepository guestRepository; + private final EventLeadRepository eventLeadRepository; + private final EventSalespersonRepository eventSalespersonRepository; + private final RegistrationService registrationService; + + private static ResponseStatusException notFound(String code) { + return new ResponseStatusException(HttpStatus.NOT_FOUND, code); + } + + private static long requireCompany(Long companyId) { + if (companyId == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); + return companyId; + } + + private Event event(Long companyId, long eventUuid) { + long company = requireCompany(companyId); + return eventRepository.findByUuid(eventUuid) + .filter(e -> company == e.getCompanyId()) + .orElseThrow(() -> notFound("EVENT_NOT_FOUND")); + } + + private static boolean sameCompany(Long companyId, EventGuest g) { + return requireCompany(companyId) == g.getCompanyId(); + } + + public List list(ListRequest req) { + event(req.companyId(), req.eventUuid()); + List guests = guestRepository.findByEventUuidOrderByNameAsc(req.eventUuid()); + List leadIds = guests.stream().map(EventGuest::getEventLeadId).filter(Objects::nonNull).toList(); + Map leads = leadIds.isEmpty() ? Map.of() + : eventLeadRepository.findAllById(leadIds).stream().collect(Collectors.toMap(EventLead::getId, l -> l)); + return guests.stream().map(g -> row(g, leads.get(g.getEventLeadId()))).toList(); + } + + private static GuestRow row(EventGuest g, EventLead lead) { + return new GuestRow(g.getId(), g.getName(), g.getMobileE164(), g.getEmail(), g.getCompanyName(), + g.getSalespersonUserId(), g.getToken(), g.getInvitedAt(), g.getInviteSentCount(), g.getRegisteredAt(), + lead != null && lead.getAttendedAt() != null, lead == null ? null : String.valueOf(lead.getUuid())); + } + + // ponytail: deliberately not @Transactional. A unique-key race makes saveAndFlush throw; inside one transaction that + // would mark it rollback-only and lose the guests saved earlier in this request. Each save commits on its own. + // ponytail: the cap check below is unlocked; two concurrent adds can exceed the cap. Upgrade: lock the event row FOR UPDATE. + public AddResult add(AddRequest req) { + Event event = event(req.companyId(), req.eventUuid()); + Set team = eventSalespersonRepository.findByEventUuid(req.eventUuid()).stream() + .map(EventSalesperson::getUserId).collect(Collectors.toSet()); + Map byMobile = new HashMap<>(); + Map byEmail = new HashMap<>(); + List existing = guestRepository.findByEventUuidOrderByNameAsc(req.eventUuid()); + existing.forEach(g -> index(g, byMobile, byEmail)); + int count = existing.size(); + List added = new ArrayList<>(); + List rejected = new ArrayList<>(); + for (int i = 0; i < req.guests().size(); i++) { + GuestInput in = req.guests().get(i); + if (in.salespersonUserId() != null && !team.contains(in.salespersonUserId())) { + rejected.add(new Rejection(i, "NOT_ON_TEAM", "salespersonUserId", "Salesperson is not on the event team")); + continue; + } + EventGuest dup = in.mobileE164() != null && byMobile.containsKey(in.mobileE164()) ? byMobile.get(in.mobileE164()) + : in.email() != null ? byEmail.get(in.email()) : null; + if (dup != null) { + boolean mobile = in.mobileE164() != null && byMobile.get(in.mobileE164()) == dup; + rejected.add(new Rejection(i, "DUPLICATE", mobile ? "mobile" : "email", + "Already invited as " + dup.getName())); + continue; + } + if (event.getInvitationCap() != null && count >= event.getInvitationCap()) { + rejected.add(new Rejection(i, "CAP_REACHED", null, "Invitation cap reached (" + event.getInvitationCap() + ")")); + continue; + } + EventGuest g = new EventGuest(); + g.setCompanyId(event.getCompanyId()); + g.setEventUuid(req.eventUuid()); + g.setName(in.name()); + g.setMobileE164(in.mobileE164()); + g.setEmail(in.email()); + g.setCompanyName(in.companyName()); + g.setSalespersonUserId(in.salespersonUserId()); + g.setToken(RegistrationLinkService.newToken()); + g.setCreatedBy(req.doneBy()); + try { + g = guestRepository.saveAndFlush(g); + } catch (DataIntegrityViolationException e) { + String m = String.valueOf(e.getMostSpecificCause().getMessage()); + if (!m.contains("uk_event_guest_mobile") && !m.contains("uk_event_guest_email")) throw e; + rejected.add(new Rejection(i, "DUPLICATE", null, "Already invited")); + continue; + } + index(g, byMobile, byEmail); + count++; + added.add(row(g, null)); + } + return new AddResult(added, rejected); + } + + private static void index(EventGuest g, Map byMobile, Map byEmail) { + if (g.getMobileE164() != null) byMobile.put(g.getMobileE164(), g); + if (g.getEmail() != null) byEmail.put(g.getEmail(), g); + } + + public void remove(RemoveRequest req) { + Event event = event(req.companyId(), req.eventUuid()); + EventGuest g = guestRepository.findByIdAndEventUuidAndCompanyId(req.guestId(), req.eventUuid(), event.getCompanyId()) + .orElseThrow(() -> notFound("GUEST_NOT_FOUND")); + if (g.getEventLeadId() != null) throw new ResponseStatusException(HttpStatus.CONFLICT, "GUEST_REGISTERED"); + guestRepository.delete(g); + } + + @Transactional + public void markSent(MarkSentRequest req) { + Event event = event(req.companyId(), req.eventUuid()); + LocalDateTime now = LocalDateTime.now(); + for (EventGuest g : guestRepository.findByEventUuidAndCompanyIdAndIdIn(req.eventUuid(), event.getCompanyId(), req.guestIds())) { + if (g.getInvitedAt() == null) g.setInvitedAt(now); + g.setInviteSentCount(g.getInviteSentCount() + 1); + g.setUpdatedBy(req.doneBy()); + g.setUpdatedAt(now); + guestRepository.save(g); + } + } + + public GuestLookup findByToken(String token) { + EventGuest g = guestRepository.findByToken(token).orElseThrow(() -> notFound("GUEST_NOT_FOUND")); + EventLead lead = g.getEventLeadId() == null ? null : eventLeadRepository.findById(g.getEventLeadId()).orElse(null); + return new GuestLookup(g.getCompanyId(), g.getEventUuid(), g.getId(), g.getName(), g.getMobileE164(), g.getEmail(), + g.getCompanyName(), g.getSalespersonUserId(), g.getEventLeadId() != null, + lead != null && lead.getAttendedAt() != null); + } + + public RegistrationService.RegisterResult register(GuestRegisterRequest req) { + requireCompany(req.companyId()); + EventGuest g = guestRepository.findByToken(req.guestToken()).filter(x -> sameCompany(req.companyId(), x)) + .orElseThrow(() -> notFound("GUEST_NOT_FOUND")); + // ponytail: ALREADY_REGISTERED/EVENT_FULL checks run before the registration transaction; a concurrent double + // submit is harmless but the second answer may differ. + if (g.getEventLeadId() != null) { + String uuid = eventLeadRepository.findById(g.getEventLeadId()).map(l -> String.valueOf(l.getUuid())).orElse(null); + return new RegistrationService.RegisterResult("ALREADY_REGISTERED", uuid); + } + Event event = event(g.getCompanyId(), g.getEventUuid()); + if (event.getCapacity() != null && !EventDays.isDuring(event, LocalDateTime.now()) + && guestRepository.countByEventUuidAndEventLeadIdIsNotNull(g.getEventUuid()) + + eventLeadRepository.countWalkIns(g.getEventUuid()) >= event.getCapacity()) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "EVENT_FULL"); + } + return registrationService.register(new RegistrationService.RegisterRequest(g.getCompanyId(), g.getEventUuid(), + g.getSalespersonUserId(), req.name(), req.mobileE164(), req.email(), req.companyName(), req.jobTitle(), + req.interestIds(), req.consentNoticeId(), req.consentAt(), false, "INVITE", g.getId())); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/GuestLinker.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/GuestLinker.java index b4e4ee6..5e4b919 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/GuestLinker.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/GuestLinker.java @@ -30,4 +30,14 @@ public class GuestLinker { guests.save(g); }); } + + /** Links the invited guest the registration came through; skipped when either side is already linked. */ + public void linkGuest(long guestId, EventLead eventLead) { + guests.findById(guestId).ifPresent(g -> { + if (g.getEventLeadId() != null || guests.existsByEventLeadId(eventLead.getId())) return; + g.setEventLeadId(eventLead.getId()); + if (g.getRegisteredAt() == null) g.setRegisteredAt(LocalDateTime.now()); + guests.save(g); + }); + } } 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 index 92606c1..de61a73 100644 --- 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 @@ -114,14 +114,19 @@ public class RegistrationLinkService { .orElseGet(() -> linkRepository.save(newLink(companyId, eventUuid, userId))); } - private static RegistrationLink newLink(long companyId, long eventUuid, Long userId) { + /** 22-char unguessable base64url token. */ + static String newToken() { byte[] bytes = new byte[16]; RANDOM.nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private static RegistrationLink newLink(long companyId, long eventUuid, Long userId) { RegistrationLink l = new RegistrationLink(); l.setCompanyId(companyId); l.setEventUuid(eventUuid); l.setSalespersonUserId(userId); - l.setToken(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); + l.setToken(newToken()); l.setCreatedBy("system"); return l; } 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 index 73ca77f..395435b 100644 --- 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 @@ -24,12 +24,20 @@ import java.util.Optional; 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, boolean attend) { + Long consentNoticeId, LocalDateTime consentAt, boolean attend, + String source, Long guestId) { + /** source null means QR; guestId, when set, is the invited guest this registration links to. */ + public RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164, + String email, String companyName, String jobTitle, List interestIds, + Long consentNoticeId, LocalDateTime consentAt, boolean attend) { + this(companyId, eventUuid, salespersonUserId, name, mobileE164, email, companyName, jobTitle, interestIds, + consentNoticeId, consentAt, attend, null, null); + } public RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164, String email, String companyName, String jobTitle, List interestIds, Long consentNoticeId, LocalDateTime consentAt) { this(companyId, eventUuid, salespersonUserId, name, mobileE164, email, companyName, jobTitle, interestIds, - consentNoticeId, consentAt, false); + consentNoticeId, consentAt, false, null, null); } } public record RegisterResult(String outcome, String eventLeadUuid) {} @@ -100,7 +108,7 @@ public class RegistrationService { e.setLeadType(leadType); e.setStatus("OPEN"); e.setNotes(notes); - e.setSource("QR"); + e.setSource(req.source() == null ? "QR" : req.source()); e.setCapturedBy(QR); e.setConsentAt(req.consentAt()); e.setConsentNoticeId(req.consentNoticeId()); @@ -127,7 +135,9 @@ public class RegistrationService { } private void link(RegisterRequest req, EventLead e, Lead lead) { - if (guestLinker != null) guestLinker.link(req.eventUuid(), e, lead); + if (guestLinker == null) return; + if (req.guestId() != null) guestLinker.linkGuest(req.guestId(), e); + else guestLinker.link(req.eventUuid(), e, lead); } /** Submitted non-blank values that differ from the lead's, as an event-lead note; null when nothing differs. */ diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/ApiErrorAdviceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/ApiErrorAdviceTest.java new file mode 100644 index 0000000..0094598 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/ApiErrorAdviceTest.java @@ -0,0 +1,66 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.service.EventCheckInService; +import com.solvway.services.counter.service.EventGuestService; +import com.solvway.services.counter.service.EventHeadcountService; +import com.solvway.services.counter.service.EventService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.modelmapper.ModelMapper; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.server.ResponseStatusException; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** mobile-api reads the JSON `code` of counter 4xx bodies, so the reason must reach the body. */ +@ExtendWith(MockitoExtension.class) +class ApiErrorAdviceTest { + @Mock private EventGuestService guestService; + @Mock private EventCheckInService checkInService; + @Mock private EventService eventService; + @Mock private ModelMapper modelMapper; + @Mock private EventHeadcountService headcountService; + + private MockMvc mvc() { + return MockMvcBuilders.standaloneSetup(new EventGuestController(guestService), + new EventCheckInController(checkInService), new EventController(eventService, modelMapper, headcountService)) + .setControllerAdvice(new ApiErrorAdvice()).build(); + } + + @Test + void guestRegisterEventFullIs409WithCode() throws Exception { + when(guestService.register(any())).thenThrow(new ResponseStatusException(HttpStatus.CONFLICT, "EVENT_FULL")); + mvc().perform(post("/counter/eventGuest/register").contentType(MediaType.APPLICATION_JSON) + .content("{\"companyId\":42,\"guestToken\":\"t\"}")) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.code").value("EVENT_FULL")) + .andExpect(jsonPath("$.message").value("EVENT_FULL")); + } + + @Test + void checkinCompanyRequiredIs400WithCode() throws Exception { + when(checkInService.ensureToken(any())).thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED")); + mvc().perform(post("/counter/checkin/ensureToken").contentType(MediaType.APPLICATION_JSON) + .content("{\"eventUuid\":1}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("COMPANY_REQUIRED")); + } + + @Test + void eventSaveCapBelowGuestsIs409WithCode() throws Exception { + when(eventService.save(any(Event.class))).thenThrow(new ResponseStatusException(HttpStatus.CONFLICT, "CAP_BELOW_GUESTS")); + mvc().perform(post("/counter/event/save").contentType(MediaType.APPLICATION_JSON).content("{}")) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.code").value("CAP_BELOW_GUESTS")); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventCheckInServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventCheckInServiceTest.java new file mode 100644 index 0000000..ef609de --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventCheckInServiceTest.java @@ -0,0 +1,264 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventGuest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventGuestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.LeadRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +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 java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class EventCheckInServiceTest { + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + + @Mock private EventRepository eventRepository; + @Mock private EventGuestRepository guestRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private LeadRepository leadRepository; + + private EventCheckInService service; + private Event event; + + @BeforeEach + void setUp() { + service = new EventCheckInService(eventRepository, guestRepository, eventLeadRepository, leadRepository); + event = new Event(); + event.setCompanyId(COMPANY); + event.setDateStart(LocalDateTime.now().minusDays(1)); + event.setDateEnd(LocalDateTime.now().plusDays(1)); + lenient().when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(event)); + lenient().when(eventRepository.save(any(Event.class))).then(i -> i.getArgument(0)); + } + + private static void assertStatus(Throwable t, HttpStatus status, String reason) { + assertThat(t).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + if (reason != null) assertThat(e.getReason()).isEqualTo(reason); + }); + } + + // ---- token / findEvent + + @Test + void ensureTokenWritesThroughTheAtomicUpdateAndReturnsTheStoredValue() { + when(eventRepository.setCheckinTokenIfAbsent(org.mockito.ArgumentMatchers.eq(EVENT), org.mockito.ArgumentMatchers.anyString())) + .then(i -> { + event.setCheckinToken(i.getArgument(1)); + return 1; + }); + + String token = service.ensureToken(new EventCheckInService.EnsureRequest(COMPANY, EVENT)).token(); + + assertThat(token).hasSize(22).isEqualTo(event.getCheckinToken()); + verify(eventRepository).setCheckinTokenIfAbsent(org.mockito.ArgumentMatchers.eq(EVENT), org.mockito.ArgumentMatchers.eq(token)); + verify(eventRepository, never()).save(any()); + } + + @Test + void ensureTokenKeepsAnExistingToken() { + event.setCheckinToken("existing"); + + assertThat(service.ensureToken(new EventCheckInService.EnsureRequest(COMPANY, EVENT)).token()).isEqualTo("existing"); + verify(eventRepository, never()).setCheckinTokenIfAbsent(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void checkinTokenStaysOutOfEntityUpdatesSoEventServiceSaveCannotWipeIt() throws Exception { + assertThat(Event.class.getDeclaredField("checkinToken").getAnnotation(jakarta.persistence.Column.class).updatable()).isFalse(); + } + + @Test + void lookupIsNotEventDayOutsideTheEventDays() { + event.setDateStart(LocalDateTime.now().plusDays(5)); + event.setDateEnd(LocalDateTime.now().plusDays(6)); + + assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+601", null))) + .satisfies(t -> assertStatus(t, HttpStatus.CONFLICT, "NOT_EVENT_DAY")); + verify(eventLeadRepository, never()).save(any()); + } + + @Test + void lookupIs404ForADisabledEvent() { + event.setEnabled(com.solvway.core.enums.GeneralEnum.FlagYesNo.N); + + assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+601", null))) + .satisfies(t -> assertStatus(t, HttpStatus.NOT_FOUND, null)); + } + + @Test + void companyIsRequiredOnEnsureTokenLookupAndByGuest() { + assertThatThrownBy(() -> service.ensureToken(new EventCheckInService.EnsureRequest(null, EVENT))) + .satisfies(t -> assertStatus(t, HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED")); + assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(null, EVENT, "+601", null))) + .satisfies(t -> assertStatus(t, HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED")); + assertThatThrownBy(() -> service.byGuest(new EventCheckInService.ByGuestRequest(null, "gt"))) + .satisfies(t -> assertStatus(t, HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED")); + } + + @Test + void ensureTokenIs404ForAnotherCompanysEvent() { + event.setCompanyId(COMPANY + 1); + + assertThatThrownBy(() -> service.ensureToken(new EventCheckInService.EnsureRequest(COMPANY, EVENT))) + .satisfies(t -> assertStatus(t, HttpStatus.NOT_FOUND, null)); + } + + @Test + void findEventReturnsTheEvent() { + event.setCheckinToken("abc"); + when(eventRepository.findByCheckinToken("abc")).thenReturn(Optional.of(event)); + + assertThat(service.findEvent("abc")).isEqualTo(new EventCheckInService.EventRef(COMPANY, event.getUuid())); + } + + @Test + void findEventIs404WhenUnknown() { + when(eventRepository.findByCheckinToken("nope")).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.findEvent("nope")).satisfies(t -> assertStatus(t, HttpStatus.NOT_FOUND, null)); + } + + // ---- lookup + + private EventLead leadRow(String name, String mobile, String email, LocalDateTime attendedAt) { + EventLead el = new EventLead(); + el.setAttendedAt(attendedAt); + Lead l = new Lead(); + l.setName(name); + List rows = Collections.singletonList(new Object[]{el, l}); + lenient().when(eventLeadRepository.findByEventAndMobile(EVENT, mobile)).thenReturn(mobile == null ? List.of() : rows); + lenient().when(eventLeadRepository.findByEventAndEmail(EVENT, email)).thenReturn(email == null ? List.of() : rows); + return el; + } + + @Test + void lookupByMobileChecksInAndGivesTheFirstName() { + EventLead el = leadRow("Aisyah binti Ali", "+601", null, null); + + EventCheckInService.LookupResult r = service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+601", null)); + + assertThat(r).isEqualTo(new EventCheckInService.LookupResult("CHECKED_IN", "Aisyah")); + assertThat(el.getAttendedAt()).isNotNull(); + verify(eventLeadRepository).save(el); + } + + @Test + void lookupByEmailWorksAndKeepsAnEarlierAttendanceTime() { + LocalDateTime earlier = LocalDateTime.of(2026, 12, 1, 9, 0); + EventLead el = leadRow("Ben", null, "b@x.com", earlier); + + EventCheckInService.LookupResult r = service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, null, "b@x.com")); + + assertThat(r).isEqualTo(new EventCheckInService.LookupResult("CHECKED_IN", "Ben")); + assertThat(el.getAttendedAt()).isEqualTo(earlier); + verify(eventLeadRepository, never()).save(any()); + } + + @Test + void lookupGivesFormForAnInvitedGuestWhoHasNotRegisteredOrAnUnknownPerson() { + lenient().when(eventLeadRepository.findByEventAndMobile(EVENT, "+699")).thenReturn(List.of()); + lenient().when(guestRepository.findByEventUuidOrderByNameAsc(EVENT)).thenReturn(List.of()); + + EventCheckInService.LookupResult r = service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+699", null)); + + assertThat(r.result()).isEqualTo("FORM"); + assertThat(r.firstName()).isNull(); + verify(eventLeadRepository, never()).save(any()); + } + + @Test + void lookupNeedsExactlyOneOfMobileAndEmail() { + assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+601", "a@x.com"))) + .satisfies(t -> assertStatus(t, HttpStatus.BAD_REQUEST, null)); + assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, null, " "))) + .satisfies(t -> assertStatus(t, HttpStatus.BAD_REQUEST, null)); + } + + @Test + void lookupIs404ForAnotherCompanysEvent() { + event.setCompanyId(COMPANY + 1); + + assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+601", null))) + .satisfies(t -> assertStatus(t, HttpStatus.NOT_FOUND, null)); + } + + // ---- byGuest + + private EventGuest guest(Long eventLeadId) { + EventGuest g = new EventGuest(); + g.setCompanyId(COMPANY); + g.setEventUuid(EVENT); + g.setEventLeadId(eventLeadId); + when(guestRepository.findByToken("gt")).thenReturn(Optional.of(g)); + return g; + } + + @Test + void byGuestChecksInARegisteredGuestOnAnEventDay() { + guest(9L); + EventLead el = new EventLead(); + el.setId(9L); + Lead l = new Lead(); + l.setName("Aisyah binti Ali"); + el.setLeadUuid(l.getUuid()); + when(eventLeadRepository.findById(9L)).thenReturn(Optional.of(el)); + when(leadRepository.findByUuid(l.getUuid())).thenReturn(Optional.of(l)); + + EventCheckInService.NameView n = service.byGuest(new EventCheckInService.ByGuestRequest(COMPANY, "gt")); + + assertThat(n.firstName()).isEqualTo("Aisyah"); + assertThat(el.getAttendedAt()).isNotNull(); + verify(eventLeadRepository).save(el); + } + + @Test + void byGuestRefusesAGuestWhoHasNotRegistered() { + guest(null); + + assertThatThrownBy(() -> service.byGuest(new EventCheckInService.ByGuestRequest(COMPANY, "gt"))) + .satisfies(t -> assertStatus(t, HttpStatus.CONFLICT, "NOT_REGISTERED")); + } + + @Test + void byGuestRefusesOutsideTheEventDays() { + guest(9L); + event.setDateStart(LocalDateTime.now().plusDays(5)); + event.setDateEnd(LocalDateTime.now().plusDays(6)); + + assertThatThrownBy(() -> service.byGuest(new EventCheckInService.ByGuestRequest(COMPANY, "gt"))) + .satisfies(t -> assertStatus(t, HttpStatus.CONFLICT, "NOT_EVENT_DAY")); + verify(eventLeadRepository, never()).save(any()); + } + + @Test + void byGuestIs404ForAnUnknownOrForeignGuest() { + EventGuest g = guest(9L); + g.setCompanyId(COMPANY + 1); + + assertThatThrownBy(() -> service.byGuest(new EventCheckInService.ByGuestRequest(COMPANY, "gt"))) + .satisfies(t -> assertStatus(t, HttpStatus.NOT_FOUND, null)); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventGuestServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventGuestServiceTest.java new file mode 100644 index 0000000..9b7f2e3 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventGuestServiceTest.java @@ -0,0 +1,417 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.EventGuest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.EventSalesperson; +import com.solvway.services.counter.repo.EventGuestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.EventSalespersonRepository; +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.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.ArrayList; +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.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 EventGuestServiceTest { + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + private static final String TOKEN = "tok-1"; + + @Mock private EventRepository eventRepository; + @Mock private EventGuestRepository guestRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private EventSalespersonRepository eventSalespersonRepository; + @Mock private RegistrationService registrationService; + + private EventGuestService service; + private Event event; + + @BeforeEach + void setUp() { + service = new EventGuestService(eventRepository, guestRepository, eventLeadRepository, eventSalespersonRepository, + registrationService); + event = new Event(); + event.setCompanyId(COMPANY); + event.setDateStart(LocalDateTime.now().plusDays(10)); + event.setDateEnd(LocalDateTime.now().plusDays(11)); + lenient().when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(event)); + lenient().when(guestRepository.findByEventUuidOrderByNameAsc(EVENT)).thenReturn(List.of()); + lenient().when(guestRepository.save(any(EventGuest.class))).then(i -> { + EventGuest g = i.getArgument(0); + if (g.getId() == null) g.setId(100L + g.getName().length()); + return g; + }); + lenient().when(guestRepository.saveAndFlush(any(EventGuest.class))).then(i -> guestRepository.save(i.getArgument(0))); + EventSalesperson sp = new EventSalesperson(); + sp.setUserId(7L); + lenient().when(eventSalespersonRepository.findByEventUuid(EVENT)).thenReturn(List.of(sp)); + } + + private static EventGuestService.GuestInput in(String name, String mobile, String email, Long sp) { + return new EventGuestService.GuestInput(name, mobile, email, "Acme", sp); + } + + private static EventGuest guest(long id, String name, String mobile, String email) { + EventGuest g = new EventGuest(); + g.setId(id); + g.setCompanyId(COMPANY); + g.setEventUuid(EVENT); + g.setName(name); + g.setMobileE164(mobile); + g.setEmail(email); + g.setToken("t" + id); + return g; + } + + private EventGuestService.AddResult add(EventGuestService.GuestInput... guests) { + return service.add(new EventGuestService.AddRequest(COMPANY, EVENT, List.of(guests), "admin")); + } + + // ---- add + + @Test + void addSavesInOrderWithFreshTokens() { + EventGuestService.AddResult r = add(in("Bee", "+601", "b@x.com", 7L), in("Aaa", "+602", "a@x.com", null)); + + assertThat(r.rejected()).isEmpty(); + assertThat(r.added()).extracting(EventGuestService.GuestRow::name).containsExactly("Bee", "Aaa"); + ArgumentCaptor c = ArgumentCaptor.forClass(EventGuest.class); + verify(guestRepository, times(2)).saveAndFlush(c.capture()); + EventGuest first = c.getAllValues().get(0); + assertThat(first.getCompanyId()).isEqualTo(COMPANY); + assertThat(first.getEventUuid()).isEqualTo(EVENT); + assertThat(first.getSalespersonUserId()).isEqualTo(7L); + assertThat(first.getCreatedBy()).isEqualTo("admin"); + assertThat(first.getToken()).hasSize(22); + assertThat(first.getToken()).isNotEqualTo(c.getAllValues().get(1).getToken()); + assertThat(r.added().get(0).token()).isEqualTo(first.getToken()); + } + + @Test + void addRejectsDuplicateNamingTheExistingGuest() { + when(guestRepository.findByEventUuidOrderByNameAsc(EVENT)).thenReturn(List.of(guest(1, "Existing Eve", "+601", "e@x.com"))); + + EventGuestService.AddResult r = add(in("New", "+601", "n@x.com", null), in("New2", "+609", "e@x.com", null)); + + assertThat(r.added()).isEmpty(); + assertThat(r.rejected()).extracting(EventGuestService.Rejection::index, EventGuestService.Rejection::code, + EventGuestService.Rejection::field).containsExactly( + org.assertj.core.groups.Tuple.tuple(0, "DUPLICATE", "mobile"), + org.assertj.core.groups.Tuple.tuple(1, "DUPLICATE", "email")); + assertThat(r.rejected().get(0).message()).contains("Existing Eve"); + verify(guestRepository, never()).saveAndFlush(any()); + } + + @Test + void addRejectsDuplicateEarlierInTheSameRequest() { + EventGuestService.AddResult r = add(in("First One", "+601", "a@x.com", null), in("Second", "+601", "b@x.com", null)); + + assertThat(r.added()).hasSize(1); + assertThat(r.rejected()).hasSize(1); + assertThat(r.rejected().get(0).index()).isEqualTo(1); + assertThat(r.rejected().get(0).code()).isEqualTo("DUPLICATE"); + assertThat(r.rejected().get(0).message()).contains("First One"); + } + + @Test + void addTreatsUniqueKeyRaceAsDuplicate() { + when(guestRepository.saveAndFlush(any(EventGuest.class))) + .thenThrow(new DataIntegrityViolationException("Duplicate entry for key 'event_guest.uk_event_guest_mobile'")); + + EventGuestService.AddResult r = add(in("Racer", "+601", "r@x.com", null)); + + assertThat(r.added()).isEmpty(); + assertThat(r.rejected()).extracting(EventGuestService.Rejection::code).containsExactly("DUPLICATE"); + } + + @Test + void addRethrowsOtherIntegrityViolations() { + when(guestRepository.saveAndFlush(any(EventGuest.class))) + .thenThrow(new DataIntegrityViolationException("Data too long for column 'name'")); + + assertThatThrownBy(() -> add(in("Racer", "+601", "r@x.com", null))).isInstanceOf(DataIntegrityViolationException.class); + } + + @Test + void companyIsRequiredOnEveryEndpoint() { + List calls = List.of( + () -> service.list(new EventGuestService.ListRequest(null, EVENT)), + () -> service.add(new EventGuestService.AddRequest(null, EVENT, List.of(), "a")), + () -> service.remove(new EventGuestService.RemoveRequest(null, EVENT, 1L, "a")), + () -> service.markSent(new EventGuestService.MarkSentRequest(null, EVENT, List.of(1L), "a")), + () -> service.register(new EventGuestService.GuestRegisterRequest(null, TOKEN, "n", "+601", null, null, null, null, null, null))); + for (var c : calls) { + assertThatThrownBy(c::execute).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(e.getReason()).isEqualTo("COMPANY_REQUIRED"); + }); + } + } + + @Test + void addStopsAtTheInvitationCap() { + event.setInvitationCap(2); + when(guestRepository.findByEventUuidOrderByNameAsc(EVENT)).thenReturn(List.of(guest(1, "Old", "+600", "o@x.com"))); + + EventGuestService.AddResult r = add(in("A", "+601", "a@x.com", null), in("B", "+602", "b@x.com", null)); + + assertThat(r.added()).extracting(EventGuestService.GuestRow::name).containsExactly("A"); + assertThat(r.rejected()).extracting(EventGuestService.Rejection::index, EventGuestService.Rejection::code) + .containsExactly(org.assertj.core.groups.Tuple.tuple(1, "CAP_REACHED")); + assertThat(r.rejected().get(0).message()).isEqualTo("Invitation cap reached (2)"); + } + + @Test + void addRejectsSalespersonNotOnTheTeam() { + EventGuestService.AddResult r = add(in("A", "+601", "a@x.com", 99L)); + + assertThat(r.added()).isEmpty(); + assertThat(r.rejected()).extracting(EventGuestService.Rejection::code, EventGuestService.Rejection::field) + .containsExactly(org.assertj.core.groups.Tuple.tuple("NOT_ON_TEAM", "salespersonUserId")); + } + + @Test + void addIs404ForAnotherCompanysEvent() { + event.setCompanyId(COMPANY + 1); + + assertThatThrownBy(() -> add(in("A", "+601", "a@x.com", null))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + verify(guestRepository, never()).saveAndFlush(any()); + } + + // ---- remove / markSent + + @Test + void removeRefusesALinkedGuest() { + EventGuest g = guest(5, "Linked", "+601", null); + g.setEventLeadId(9L); + when(guestRepository.findByIdAndEventUuidAndCompanyId(5L, EVENT, COMPANY)).thenReturn(Optional.of(g)); + + assertThatThrownBy(() -> service.remove(new EventGuestService.RemoveRequest(COMPANY, EVENT, 5L, "admin"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getReason()).isEqualTo("GUEST_REGISTERED"); + }); + verify(guestRepository, never()).delete(any()); + } + + @Test + void removeDeletesAnUnlinkedGuest() { + EventGuest g = guest(5, "Free", "+601", null); + when(guestRepository.findByIdAndEventUuidAndCompanyId(5L, EVENT, COMPANY)).thenReturn(Optional.of(g)); + + service.remove(new EventGuestService.RemoveRequest(COMPANY, EVENT, 5L, "admin")); + + verify(guestRepository).delete(g); + } + + @Test + void removeIs404WhenTheGuestIsNotOfThisEvent() { + when(guestRepository.findByIdAndEventUuidAndCompanyId(5L, EVENT, COMPANY)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.remove(new EventGuestService.RemoveRequest(COMPANY, EVENT, 5L, "admin"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + @Test + void markSentSetsInvitedAtOnceAndCountsEverySend() { + EventGuest fresh = guest(1, "Fresh", "+601", null); + EventGuest resent = guest(2, "Resent", "+602", null); + LocalDateTime first = LocalDateTime.of(2026, 11, 1, 9, 0); + resent.setInvitedAt(first); + resent.setInviteSentCount(1); + when(guestRepository.findByEventUuidAndCompanyIdAndIdIn(anyLong(), anyLong(), anyCollection())).thenReturn(List.of(fresh, resent)); + + service.markSent(new EventGuestService.MarkSentRequest(COMPANY, EVENT, List.of(1L, 2L, 3L), "admin")); + + assertThat(fresh.getInvitedAt()).isNotNull(); + assertThat(fresh.getInviteSentCount()).isEqualTo(1); + assertThat(resent.getInvitedAt()).isEqualTo(first); + assertThat(resent.getInviteSentCount()).isEqualTo(2); + } + + // ---- findByToken + + @Test + void findByTokenReturnsTheGuest() { + EventGuest g = guest(5, "Aisyah", "+601", "a@x.com"); + g.setSalespersonUserId(7L); + g.setEventLeadId(9L); + EventLead lead = new EventLead(); + lead.setAttendedAt(LocalDateTime.now()); + when(guestRepository.findByToken(TOKEN)).thenReturn(Optional.of(g)); + when(eventLeadRepository.findById(9L)).thenReturn(Optional.of(lead)); + + EventGuestService.GuestLookup l = service.findByToken(TOKEN); + + assertThat(l).isEqualTo(new EventGuestService.GuestLookup(COMPANY, EVENT, 5L, "Aisyah", "+601", "a@x.com", "Acme" + .equals(g.getCompanyName()) ? "Acme" : null, 7L, true, true)); + } + + @Test + void findByTokenIs404WhenUnknown() { + when(guestRepository.findByToken(TOKEN)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.findByToken(TOKEN)) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + // ---- list + + @Test + void listDerivesAttendedAndEventLeadWithOneLeadQuery() { + EventGuest a = guest(1, "Aaa", "+601", null); + a.setEventLeadId(10L); + EventGuest b = guest(2, "Bbb", "+602", null); + b.setEventLeadId(11L); + EventGuest c = guest(3, "Ccc", "+603", null); + EventLead l10 = new EventLead(); + l10.setId(10L); + l10.setAttendedAt(LocalDateTime.now()); + EventLead l11 = new EventLead(); + l11.setId(11L); + when(guestRepository.findByEventUuidOrderByNameAsc(EVENT)).thenReturn(List.of(a, b, c)); + when(eventLeadRepository.findAllById(anyCollection())).thenReturn(List.of(l10, l11)); + + List rows = service.list(new EventGuestService.ListRequest(COMPANY, EVENT)); + + assertThat(rows).extracting(EventGuestService.GuestRow::name).containsExactly("Aaa", "Bbb", "Ccc"); + assertThat(rows).extracting(EventGuestService.GuestRow::attended).containsExactly(true, false, false); + assertThat(rows.get(0).eventLeadUuid()).isEqualTo(String.valueOf(l10.getUuid())); + assertThat(rows.get(1).eventLeadUuid()).isEqualTo(String.valueOf(l11.getUuid())); + assertThat(rows.get(2).eventLeadUuid()).isNull(); + verify(eventLeadRepository, times(1)).findAllById(anyCollection()); + verify(eventLeadRepository, never()).findById(any()); + } + + @Test + void listIs404ForAnotherCompanysEvent() { + event.setCompanyId(COMPANY + 1); + + assertThatThrownBy(() -> service.list(new EventGuestService.ListRequest(COMPANY, EVENT))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + // ---- register + + private EventGuestService.GuestRegisterRequest reg() { + return new EventGuestService.GuestRegisterRequest(COMPANY, TOKEN, "Aisyah", "+601", "a@x.com", "Acme", "CEO", + List.of(3L), 5L, LocalDateTime.of(2026, 12, 1, 10, 0)); + } + + private EventGuest registrable() { + EventGuest g = guest(5, "Aisyah", "+601", "a@x.com"); + g.setSalespersonUserId(7L); + when(guestRepository.findByToken(TOKEN)).thenReturn(Optional.of(g)); + return g; + } + + @Test + void registerUsesSourceInviteTheGuestsSalespersonAndLinksTheTokenGuest() { + registrable(); + when(registrationService.register(any())).thenReturn(new RegistrationService.RegisterResult("CREATED", "555")); + + EventGuestService.GuestRegisterRequest r = reg(); + RegistrationService.RegisterResult out = service.register(r); + + assertThat(out).isEqualTo(new RegistrationService.RegisterResult("CREATED", "555")); + ArgumentCaptor c = ArgumentCaptor.forClass(RegistrationService.RegisterRequest.class); + verify(registrationService).register(c.capture()); + RegistrationService.RegisterRequest q = c.getValue(); + assertThat(q.source()).isEqualTo("INVITE"); + assertThat(q.guestId()).isEqualTo(5L); + assertThat(q.salespersonUserId()).isEqualTo(7L); + assertThat(q.attend()).isFalse(); + assertThat(q.eventUuid()).isEqualTo(EVENT); + assertThat(q.companyId()).isEqualTo(COMPANY); + assertThat(q.name()).isEqualTo("Aisyah"); + assertThat(q.interestIds()).containsExactly(3L); + } + + @Test + void registerIs404ForAnotherCompanysGuest() { + EventGuest g = registrable(); + g.setCompanyId(COMPANY + 1); + + assertThatThrownBy(() -> service.register(reg())) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + verify(registrationService, never()).register(any()); + } + + @Test + void registerAgainReportsAlreadyRegisteredAndChangesNothing() { + EventGuest g = registrable(); + g.setEventLeadId(9L); + EventLead lead = new EventLead(); + lead.setId(9L); + when(eventLeadRepository.findById(9L)).thenReturn(Optional.of(lead)); + + RegistrationService.RegisterResult out = service.register(reg()); + + assertThat(out).isEqualTo(new RegistrationService.RegisterResult("ALREADY_REGISTERED", String.valueOf(lead.getUuid()))); + verify(registrationService, never()).register(any()); + } + + @Test + void registerIsEventFullBeforeTheEventDaysAtCapacity() { + registrable(); + event.setCapacity(10); + when(guestRepository.countByEventUuidAndEventLeadIdIsNotNull(EVENT)).thenReturn(7L); + when(eventLeadRepository.countWalkIns(EVENT)).thenReturn(3L); + + assertThatThrownBy(() -> service.register(reg())) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getReason()).isEqualTo("EVENT_FULL"); + }); + verify(registrationService, never()).register(any()); + } + + @Test + void registerBelowCapacityGoesThrough() { + registrable(); + event.setCapacity(10); + when(guestRepository.countByEventUuidAndEventLeadIdIsNotNull(EVENT)).thenReturn(7L); + when(eventLeadRepository.countWalkIns(EVENT)).thenReturn(2L); + when(registrationService.register(any())).thenReturn(new RegistrationService.RegisterResult("CREATED", "1")); + + assertThat(service.register(reg()).outcome()).isEqualTo("CREATED"); + } + + @Test + void registerIsNeverEventFullOnTheEventDays() { + registrable(); + event.setDateStart(LocalDateTime.now().minusDays(1)); + event.setDateEnd(LocalDateTime.now().plusDays(1)); + event.setCapacity(10); + lenient().when(guestRepository.countByEventUuidAndEventLeadIdIsNotNull(EVENT)).thenReturn(10L); + lenient().when(eventLeadRepository.countWalkIns(EVENT)).thenReturn(5L); + when(registrationService.register(any())).thenReturn(new RegistrationService.RegisterResult("CREATED", "1")); + + assertThat(service.register(reg()).outcome()).isEqualTo("CREATED"); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationInviteLinkTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationInviteLinkTest.java new file mode 100644 index 0000000..5b3a2c5 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/RegistrationInviteLinkTest.java @@ -0,0 +1,107 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.EventGuest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventGuestRepository; +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 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.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +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.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class RegistrationInviteLinkTest { + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + + @Mock private LeadRepository leadRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private EventLeadInterestRepository interestRepository; + @Mock private EventLeadStatusChangeRepository statusChangeRepository; + @Mock private EventGuestRepository guests; + + private RegistrationService registration; + + @BeforeEach + void setUp() { + EventLeadService eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, interestRepository, statusChangeRepository); + registration = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)), + leadRepository, eventLeadRepository, eventLeadService, new GuestLinker(guests)); + 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 RegistrationService.RegisterRequest invite(Long guestId) { + return new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "Aisyah", "+601", "a@x.com", null, null, + List.of(), null, null, false, "INVITE", guestId); + } + + @Test + void inviteRegistrationSavesSourceInviteAndLinksOnlyTheTokenGuest() { + EventGuest tokenGuest = new EventGuest(); + tokenGuest.setId(5L); + when(guests.findById(5L)).thenReturn(Optional.of(tokenGuest)); + + registration.register(invite(5L)); + + ArgumentCaptor c = ArgumentCaptor.forClass(EventLead.class); + verify(eventLeadRepository).saveAndFlush(c.capture()); + assertThat(c.getValue().getSource()).isEqualTo("INVITE"); + assertThat(tokenGuest.getEventLeadId()).isEqualTo(1L); + assertThat(tokenGuest.getRegisteredAt()).isNotNull(); + verify(guests, never()).findFirstByEventUuidAndEventLeadIdIsNullAndMobileE164(any(Long.class), any()); + verify(guests, never()).findFirstByEventUuidAndEventLeadIdIsNullAndEmail(any(Long.class), any()); + } + + @Test + void qrRegistrationKeepsSourceQr() { + registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", "+601", null, null, null, + List.of(), null, null)); + + ArgumentCaptor c = ArgumentCaptor.forClass(EventLead.class); + verify(eventLeadRepository).saveAndFlush(c.capture()); + assertThat(c.getValue().getSource()).isEqualTo("QR"); + } + + @Test + void linkGuestDoesNotStealAnEventLeadAlreadyLinkedToAnotherGuest() { + EventGuest tokenGuest = new EventGuest(); + tokenGuest.setId(5L); + when(guests.findById(5L)).thenReturn(Optional.of(tokenGuest)); + when(guests.existsByEventLeadId(1L)).thenReturn(true); + + new GuestLinker(guests).linkGuest(5L, leadWithId(1L)); + + assertThat(tokenGuest.getEventLeadId()).isNull(); + } + + private static EventLead leadWithId(long id) { + EventLead e = new EventLead(); + e.setId(id); + return e; + } +}