diff --git a/openspec/changes/add-event-tickets/design.md b/openspec/changes/add-event-tickets/design.md index ea57035..c40256f 100644 --- a/openspec/changes/add-event-tickets/design.md +++ b/openspec/changes/add-event-tickets/design.md @@ -100,7 +100,7 @@ ALTER TABLE `ticket` | counter | `GET ticket/byCode/{code}` | public via gateway | | counter | `POST ticket/attendee` (order token, ticket id, attendee, permission) | public via gateway | | counter | `POST ticket/consent` (code, notice id) | public via gateway | -| counter | `GET ticket/staff/{code}`, `POST ticket/checkin` | JWT (from mobile-api admin) | +| counter | `POST ticket/staff` and `POST ticket/checkin` (company id and code in the body) | JWT (from mobile-api admin) | | counter | `POST ticketOrder/{id}/tickets/{ticketId}/resend` | JWT | | mobile-api | `GET /api/public/tickets/{code}`, `GET .../qr.png`, `POST .../consent` | public | | mobile-api | `POST /api/public/orders/{token}/tickets/{ticketId}/attendee` | public | diff --git a/openspec/changes/add-event-tickets/tasks.md b/openspec/changes/add-event-tickets/tasks.md index 33b9479..eae0244 100644 --- a/openspec/changes/add-event-tickets/tasks.md +++ b/openspec/changes/add-event-tickets/tasks.md @@ -49,7 +49,7 @@ Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-04 - **Resend ticket:** goes to the attendee's email, else the buyer; refused for an invalid ticket. - Scope: `solvway-services-counter/src/**` - Verify: `mvn -T 1C -q -pl solvway-services-counter verify` -- [ ] 2.3 Door check-in, self check-in rules and the counts. +- [x] 2.3 Door check-in, self check-in rules and the counts. - Depends on: 2.2 - Tests first: - **Staff check-in:** diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/TicketController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/TicketController.java index f94f961..1696f3b 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/TicketController.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/TicketController.java @@ -28,6 +28,18 @@ public class TicketController { return service.nameAttendee(req); } + /** Staff (JWT): mobile-api has checked BO_EVENTS and the event's company. */ + @PostMapping("/staff") + public TicketService.StaffView staff(@RequestBody TicketService.StaffRequest req) { + return service.staffView(req); + } + + /** Staff (JWT): door check-in. */ + @PostMapping("/checkin") + public TicketService.StaffView checkIn(@RequestBody TicketService.CheckInRequest req) { + return service.checkIn(req); + } + /** Public: the attendee opts in on their ticket page. */ @PostMapping("/consent") public void consent(@RequestBody TicketService.ConsentRequest req) { diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketRepository.java index 118134c..5f023aa 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketRepository.java @@ -24,6 +24,25 @@ public interface TicketRepository extends JpaRepository { java.util.Optional findByCode(String code); + /** Checks a ticket in only if nobody has yet: two scanners cannot both win. Returns 1 for the winner, 0 otherwise. */ + @org.springframework.transaction.annotation.Transactional + @org.springframework.data.jpa.repository.Modifying + @Query("update Ticket t set t.checkedInAt = :at, t.checkedInBy = :by where t.id = :id and t.checkedInAt is null") + int checkIn(@Param("id") long id, @Param("at") java.time.LocalDateTime at, @Param("by") String by); + + /** Valid unchecked tickets of an event matching a mobile or email, oldest first, with the buyer's name. A named ticket matches its + * attendee, an unnamed one its buyer. Rows are [Ticket, buyerName]. */ + @Query("select t, o.buyerName from Ticket t, ShopOrder o where o.id = t.orderId and t.eventUuid = :eventUuid" + + " and t.status = 'ACTIVE' and o.status = 'PAID' and t.checkedInAt is null and (" + + " (t.attendeeName is not null and (t.attendeeMobileE164 = :mobile or t.attendeeEmail = :email))" + + " or (t.attendeeName is null and (o.buyerMobileE164 = :mobile or o.buyerEmail = :email))) order by t.id") + List selfCheckIn(@Param("eventUuid") long eventUuid, @Param("mobile") String mobile, @Param("email") String email); + + /** Active tickets of an event per order status (AWAITING, PAID) with how many are checked in: rows are [status, count, checkedIn]. */ + @Query("select o.status, count(t), count(t.checkedInAt) from Ticket t, ShopOrder o where o.id = t.orderId" + + " and t.eventUuid = :eventUuid and t.status = 'ACTIVE' and o.status in ('AWAITING', 'PAID') group by o.status") + List countsByOrderStatus(@Param("eventUuid") long eventUuid); + /** Active tickets per order for one page of the staff list: one query, no N+1. */ @Query("select new com.solvway.services.counter.repo.TicketCount(t.orderId, count(t)) from Ticket t" + " where t.orderId in :orderIds and t.status = 'ACTIVE' group by t.orderId") 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 index 3d0abb8..ed810d7 100644 --- 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 @@ -9,7 +9,9 @@ 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.model.Ticket; +import com.solvway.services.counter.repo.TicketRepository; +import org.springframework.beans.factory.annotation.Autowired; import com.solvway.services.counter.util.EventDays; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; @@ -20,7 +22,6 @@ 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) {} @@ -34,6 +35,23 @@ public class EventCheckInService { private final EventGuestRepository guestRepository; private final EventLeadRepository eventLeadRepository; private final LeadRepository leadRepository; + private final TicketRepository ticketRepository; + + @Autowired + public EventCheckInService(EventRepository eventRepository, EventGuestRepository guestRepository, + EventLeadRepository eventLeadRepository, LeadRepository leadRepository, TicketRepository ticketRepository) { + this.eventRepository = eventRepository; + this.guestRepository = guestRepository; + this.eventLeadRepository = eventLeadRepository; + this.leadRepository = leadRepository; + this.ticketRepository = ticketRepository; + } + + // ponytail: null ticket repository keeps the pre-ticketing wiring of older tests; ticketed events then never match a ticket. + public EventCheckInService(EventRepository eventRepository, EventGuestRepository guestRepository, + EventLeadRepository eventLeadRepository, LeadRepository leadRepository) { + this(eventRepository, guestRepository, eventLeadRepository, leadRepository, null); + } private static ResponseStatusException notFound(String code) { return new ResponseStatusException(HttpStatus.NOT_FOUND, code); @@ -80,8 +98,10 @@ public class EventCheckInService { 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()); + String mobile = hasMobile ? req.mobileE164() : null, email = hasMobile ? null : req.email(); + if (event.isTicketsEnabled() && ticketRepository != null) return ticketed(req.eventUuid(), mobile, email); + List rows = hasMobile ? eventLeadRepository.findByEventAndMobile(req.eventUuid(), mobile) + : eventLeadRepository.findByEventAndEmail(req.eventUuid(), email); if (rows.isEmpty()) return new LookupResult("FORM", null); EventLead el = (EventLead) rows.get(0)[0]; Lead lead = (Lead) rows.get(0)[1]; @@ -89,6 +109,26 @@ public class EventCheckInService { return new LookupResult("CHECKED_IN", firstName(lead.getName())); } + /** A ticketed event: the oldest valid unchecked ticket of this person, else a registered guest, else show the ticket. */ + private LookupResult ticketed(long eventUuid, String mobile, String email) { + LocalDateTime now = LocalDateTime.now(); + for (Object[] row : ticketRepository.selfCheckIn(eventUuid, mobile, email)) { + Ticket t = (Ticket) row[0]; + if (ticketRepository.checkIn(t.getId(), now, "self") == 0) continue; // checked in elsewhere meanwhile + if (t.getEventLeadUuid() != null) eventLeadRepository.findByUuid(t.getEventLeadUuid()).ifPresent(this::markAttended); + return new LookupResult("CHECKED_IN", firstName(t.getAttendeeName() != null ? t.getAttendeeName() : (String) row[1])); + } + List rows = mobile != null ? eventLeadRepository.findByEventAndMobile(eventUuid, mobile) + : eventLeadRepository.findByEventAndEmail(eventUuid, email); + for (Object[] row : rows) { + EventLead el = (EventLead) row[0]; + if (!guestRepository.existsByEventLeadId(el.getId())) continue; + markAttended(el); + return new LookupResult("CHECKED_IN", firstName(((Lead) row[1]).getName())); + } + return new LookupResult("SHOW_TICKET", null); + } + public NameView byGuest(ByGuestRequest req) { long company = requireCompany(req.companyId()); EventGuest g = guestRepository.findByToken(req.guestToken()) diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventHeadcountService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventHeadcountService.java index f67e96f..72e4243 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventHeadcountService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventHeadcountService.java @@ -8,15 +8,17 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; +import java.util.List; + /** Invited / registered / attended numbers of one event. */ @Service public class EventHeadcountService { public record Request(Long companyId, long eventUuid) {} /** total = registered guests + walk-ins (event leads with no guest row and no ticket order) + held tickets. */ public record Headcount(long invited, Integer cap, long registered, long attended, long walkIns, long total, Integer capacity, - long heldTickets) { + long heldTickets, long ticketsAwaiting, long ticketsPaid, long ticketsCheckedIn) { public Headcount(long invited, Integer cap, long registered, long attended, long walkIns, long total, Integer capacity) { - this(invited, cap, registered, attended, walkIns, total, capacity, 0); + this(invited, cap, registered, attended, walkIns, total, capacity, 0, 0, 0, 0); } } @@ -46,8 +48,16 @@ public class EventHeadcountService { long registered = guestRepository.countByEventUuidAndEventLeadIdIsNotNull(req.eventUuid()); long walkIns = eventLeadRepository.countWalkIns(req.eventUuid()); long held = ticketRepository == null ? 0 : ticketRepository.countHeld(req.eventUuid()); + long awaiting = 0, paid = 0, checkedIn = 0; + for (Object[] row : ticketRepository == null ? List.of() : ticketRepository.countsByOrderStatus(req.eventUuid())) { + if ("AWAITING".equals(row[0])) awaiting = ((Number) row[1]).longValue(); + if ("PAID".equals(row[0])) { + paid = ((Number) row[1]).longValue(); + checkedIn = ((Number) row[2]).longValue(); + } + } return new Headcount(guestRepository.countByEventUuid(req.eventUuid()), event.getInvitationCap(), registered, eventLeadRepository.countByEventUuidAndAttendedAtIsNotNull(req.eventUuid()), walkIns, registered + walkIns + held, - event.getCapacity(), held); + event.getCapacity(), held, awaiting, paid, checkedIn); } } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java index 7b2e703..fd73c32 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java @@ -102,6 +102,11 @@ public class EventLeadService { .map(e -> EventDays.isDuring(e, LocalDateTime.now())).orElse(false); } + /** add-event-tickets: a ticketed event takes no walk-ins. */ + public boolean sellsTickets(long eventUuid) { + return eventRepository != null && eventRepository.findByUuid(eventUuid).map(e -> e.isTicketsEnabled()).orElse(false); + } + public void linkGuest(long eventUuid, EventLead eventLead, Lead lead) { if (guestLinker != null) guestLinker.link(eventUuid, eventLead, lead); } 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 970e140..9b49d95 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 @@ -8,7 +8,9 @@ import lombok.AllArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; +import org.springframework.http.HttpStatus; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.server.ResponseStatusException; import java.time.LocalDateTime; import java.util.ArrayList; @@ -67,6 +69,10 @@ public class RegistrationService { } public RegisterResult register(RegisterRequest req) { + // A walk-in (attending, no source) on a ticketed event must show a ticket instead (add-event-tickets). + if (req.attend() && req.source() == null && eventLeadService.sellsTickets(req.eventUuid())) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "TICKETS_ONLY"); + } try { return transactionTemplate.execute(s -> registerOnce(req)); } catch (DataIntegrityViolationException e) { diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketService.java index 4c3b417..5594523 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketService.java @@ -1,6 +1,10 @@ package com.solvway.services.counter.service; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventRepository; import com.solvway.services.counter.repo.ShopOrderLineRepository; +import com.solvway.services.counter.util.EventDays; import com.solvway.services.counter.repo.ShopOrderRepository; import com.solvway.services.counter.repo.TicketRepository; import lombok.AllArgsConstructor; @@ -26,6 +30,8 @@ public class TicketService { private final ShopOrderLineRepository lines; private final RegistrationService registration; private final TicketOrderMailer mailer; + private final EventRepository events; + private final EventLeadRepository eventLeads; public record AttendeeRequest(String orderToken, long ticketId, String name, String mobileE164, String email, boolean permission) {} @@ -35,11 +41,7 @@ public class TicketService { @Transactional public TicketOrderService.OrderTicket nameAttendee(AttendeeRequest r) { if (!r.permission()) throw status(HttpStatus.BAD_REQUEST, "PERMISSION_REQUIRED"); - String name = r.name() == null ? "" : r.name().strip(); - if (name.isEmpty()) throw status(HttpStatus.BAD_REQUEST, "NAME_REQUIRED"); - if (name.length() > 100) throw status(HttpStatus.BAD_REQUEST, "NAME_TOO_LONG"); - String mobile = blankToNull(r.mobileE164()), email = blankToNull(r.email()); - if (mobile == null && email == null) throw status(HttpStatus.BAD_REQUEST, "MOBILE_OR_EMAIL_REQUIRED"); + Attendee a = attendee(r.name(), r.mobileE164(), r.email()); ShopOrder o = r.orderToken() == null ? null : orders.findByToken(r.orderToken()).orElse(null); Ticket t = o == null ? null : tickets.findById(r.ticketId()).filter(x -> x.getOrderId() == o.getId()).orElse(null); if (t == null) throw status(HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND"); @@ -47,17 +49,14 @@ public class TicketService { if (Ticket.CANCELLED.equals(t.getStatus())) throw status(HttpStatus.CONFLICT, "TICKET_CANCELLED"); if (t.getCheckedInAt() != null) throw status(HttpStatus.CONFLICT, "ALREADY_CHECKED_IN"); t.setCode(TicketState.newCode()); - t.setAttendeeName(name); - t.setAttendeeMobileE164(mobile); - t.setAttendeeEmail(email); - t.setAttendeeNamedAt(LocalDateTime.now()); + a.applyTo(t); t.setAttendeeConsentAt(null); t.setAttendeeNoticeId(null); t.setEventLeadUuid(null); tickets.save(t); - if (email != null) mailer.sendTicket(t, email); // delivered after commit + if (a.email() != null) mailer.sendTicket(t, a.email()); // delivered after commit String typeName = lines.findById(t.getOrderLineId()).map(ShopOrderLine::getName).orElse(null); - return new TicketOrderService.OrderTicket(t.getId(), typeName, name, t.getCode(), TicketState.of(o, t), null); + return new TicketOrderService.OrderTicket(t.getId(), typeName, a.name(), t.getCode(), TicketState.of(o, t), null); } /** The attendee opts in on their ticket page: they become a TICKET event lead (spec: Attendee Consent). */ @@ -85,6 +84,82 @@ public class TicketService { tickets.save(t); } + /** A checked attendee: a name of up to 100 characters and a mobile or an email (mobile-api has normalised them). */ + private record Attendee(String name, String mobile, String email) { + void applyTo(Ticket t) { + t.setAttendeeName(name); + t.setAttendeeMobileE164(mobile); + t.setAttendeeEmail(email); + t.setAttendeeNamedAt(LocalDateTime.now()); + } + } + + private static Attendee attendee(String rawName, String rawMobile, String rawEmail) { + String name = rawName == null ? "" : rawName.strip(); + if (name.isEmpty()) throw status(HttpStatus.BAD_REQUEST, "NAME_REQUIRED"); + if (name.length() > 100) throw status(HttpStatus.BAD_REQUEST, "NAME_TOO_LONG"); + String mobile = blankToNull(rawMobile), email = blankToNull(rawEmail); + if (mobile == null && email == null) throw status(HttpStatus.BAD_REQUEST, "MOBILE_OR_EMAIL_REQUIRED"); + return new Attendee(name, mobile, email); + } + + /** Staff calls carry the event's company; another company's ticket is not found. */ + public record StaffRequest(Long companyId, String code) {} + + /** name, mobile and email are needed only for an unnamed ticket; noticeId is the attendee's consent, ticked at the door. */ + public record CheckInRequest(Long companyId, String code, String name, String mobileE164, String email, Long noticeId, String doneBy) {} + + public record StaffView(long companyId, long eventUuid, String typeName, String attendeeName, boolean named, boolean consented, + String state, LocalDateTime checkedInAt, String checkedInBy) {} + + public StaffView staffView(StaffRequest r) { + Ticket t = staffTicket(r.companyId(), r.code()); + return staffView(t, orders.findById(t.getOrderId()).orElseThrow(TicketService::notFound)); + } + + /** Door check-in (spec: Door Check-In, Door Check-In Refusals). The conditional update lets only one scanner win. */ + @Transactional + public StaffView checkIn(CheckInRequest r) { + Ticket t = staffTicket(r.companyId(), r.code()); + ShopOrder o = orders.findById(t.getOrderId()).orElseThrow(TicketService::notFound); + String state = TicketState.of(o, t); + if (TicketState.CHECKED_IN.equals(state)) throw status(HttpStatus.CONFLICT, "ALREADY_CHECKED_IN|" + t.getCheckedInAt()); + if (!TicketState.VALID.equals(state)) throw status(HttpStatus.CONFLICT, "NOT_VALID|" + state); + LocalDateTime now = LocalDateTime.now(); + Event e = events.findByUuid(t.getEventUuid()).orElseThrow(TicketService::notFound); + if (!EventDays.isDuring(e, now)) throw status(HttpStatus.CONFLICT, "NOT_EVENT_DAY"); + Attendee a = t.getAttendeeName() == null ? attendee(r.name(), r.mobileE164(), r.email()) : null; + // ponytail: the loser of a race is told the time it tried, not the winner's; seconds apart at the same door. + if (tickets.checkIn(t.getId(), now, r.doneBy()) == 0) throw status(HttpStatus.CONFLICT, "ALREADY_CHECKED_IN|" + now); + // keep the entity in step with the update, or a later save would write checked_in_at back to null + t.setCheckedInAt(now); + t.setCheckedInBy(r.doneBy()); + if (a != null) a.applyTo(t); + if (r.noticeId() != null && t.getAttendeeConsentAt() == null) { + capture(t, r.noticeId(), true); + } else { + if (t.getEventLeadUuid() != null) eventLeads.findByUuid(t.getEventLeadUuid()).filter(el -> el.getAttendedAt() == null) + .ifPresent(el -> { + el.setAttendedAt(now); + eventLeads.save(el); + }); + tickets.save(t); + } + return staffView(t, o); + } + + private Ticket staffTicket(Long companyId, String code) { + Ticket t = ticket(code); + if (companyId == null || companyId != t.getCompanyId()) throw notFound(); + return t; + } + + private StaffView staffView(Ticket t, ShopOrder o) { + String typeName = lines.findById(t.getOrderLineId()).map(ShopOrderLine::getName).orElse(null); + return new StaffView(t.getCompanyId(), t.getEventUuid(), typeName, t.getAttendeeName(), t.getAttendeeName() != null, + t.getAttendeeConsentAt() != null, TicketState.of(o, t), t.getCheckedInAt(), t.getCheckedInBy()); + } + private static String blankToNull(String s) { return s == null || s.isBlank() ? null : s.strip(); } diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketAttendeeTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketAttendeeTest.java index a7e45bd..099fa15 100644 --- a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketAttendeeTest.java +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketAttendeeTest.java @@ -54,7 +54,7 @@ class TicketAttendeeTest { @BeforeEach void setUp() { - service = new TicketService(tickets, orders, lines, registration, mailer); + service = new TicketService(tickets, orders, lines, registration, mailer, events, null); staff = new TicketOrderStaffService(events, new TicketTypeService(events, types, tickets, lines), types, tickets, orders, lines, mailer); order = new ShopOrder(); order.setId(300L); diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCheckInTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCheckInTest.java new file mode 100644 index 0000000..e2aa195 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCheckInTest.java @@ -0,0 +1,324 @@ +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.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.model.ShopOrder; +import com.solvway.services.counter.model.ShopOrderLine; +import com.solvway.services.counter.model.Ticket; +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 com.solvway.services.counter.repo.ShopOrderLineRepository; +import com.solvway.services.counter.repo.ShopOrderRepository; +import com.solvway.services.counter.repo.TicketRepository; +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 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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +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; + +/** add-event-tickets: door check-in, self check-in on a ticketed event, no walk-ins, ticket counts + * (spec: Door Check-In, Door Check-In Refusals, Self check-in on a ticketed event, No walk-ins on a ticketed event, Ticket attendance numbers). */ +@ExtendWith(MockitoExtension.class) +class TicketCheckInTest { + private static final long COMPANY = 7L; + private static final long EVENT = 900L; + private static final String CODE = "aaaaaaaaaaaaaaaaaaaaaa"; + + @Mock private TicketRepository tickets; + @Mock private ShopOrderRepository orders; + @Mock private ShopOrderLineRepository lines; + @Mock private EventRepository events; + @Mock private EventLeadRepository eventLeads; + @Mock private EventGuestRepository guests; + @Mock private LeadRepository leads; + @Mock private RegistrationService registration; + @Mock private TicketOrderMailer mailer; + + private TicketService service; + private EventCheckInService venue; + private Event event; + private ShopOrder order; + private Ticket ticket; + + @BeforeEach + void setUp() { + service = new TicketService(tickets, orders, lines, registration, mailer, events, eventLeads); + venue = new EventCheckInService(events, guests, eventLeads, leads, tickets); + event = new Event(); + event.setUuid(EVENT); + event.setCompanyId(COMPANY); + event.setEnabled(GeneralEnum.FlagYesNo.Y); + event.setTicketsEnabled(true); + event.setDateStart(LocalDateTime.now().minusHours(2)); + event.setDateEnd(LocalDateTime.now().plusHours(6)); + lenient().when(events.findByUuid(EVENT)).thenReturn(Optional.of(event)); + order = new ShopOrder(); + order.setId(300L); + order.setCompanyId(COMPANY); + order.setEventUuid(EVENT); + order.setStatus(ShopOrder.PAID); + order.setBuyerName("Aisyah Rahman"); + lenient().when(orders.findById(300L)).thenReturn(Optional.of(order)); + ticket = new Ticket(); + ticket.setId(1L); + ticket.setCompanyId(COMPANY); + ticket.setEventUuid(EVENT); + ticket.setOrderId(300L); + ticket.setOrderLineId(400L); + ticket.setCode(CODE); + lenient().when(tickets.findByCode(CODE)).thenReturn(Optional.of(ticket)); + lenient().when(tickets.save(any(Ticket.class))).thenAnswer(i -> i.getArgument(0)); + lenient().when(tickets.checkIn(eq(1L), any(), any())).thenReturn(1); + ShopOrderLine line = new ShopOrderLine(); + line.setName("General"); + lenient().when(lines.findById(400L)).thenReturn(Optional.of(line)); + lenient().when(registration.register(any())).thenReturn(new RegistrationService.RegisterResult("CREATED", "5000")); + } + + private static void assertStatus(Runnable r, int status, String reason) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(ResponseStatusException.class, ex -> { + assertThat(ex.getStatusCode().value()).isEqualTo(status); + assertThat(ex.getReason()).isEqualTo(reason); + }); + } + + private TicketService.CheckInRequest door(String name, String mobile, String email, Long noticeId) { + return new TicketService.CheckInRequest(COMPANY, CODE, name, mobile, email, noticeId, "staff1"); + } + + private void named() { + ticket.setAttendeeName("Tan Mei Ling"); + ticket.setAttendeeEmail("tan@example.test"); + } + + // ---- staff view and door check-in + + @Test + void theStaffViewShowsTheAttendeeAndStateButAnotherCompanysTicketIsNotFound() { + named(); + TicketService.StaffView v = service.staffView(new TicketService.StaffRequest(COMPANY, CODE)); + assertThat(v.attendeeName()).isEqualTo("Tan Mei Ling"); + assertThat(v.state()).isEqualTo(TicketState.VALID); + assertThat(v.typeName()).isEqualTo("General"); + assertStatus(() -> service.staffView(new TicketService.StaffRequest(8L, CODE)), 404, "TICKET_NOT_FOUND"); + assertStatus(() -> service.checkIn(new TicketService.CheckInRequest(8L, CODE, null, null, null, null, "x")), 404, "TICKET_NOT_FOUND"); + assertStatus(() -> service.staffView(new TicketService.StaffRequest(null, CODE)), 404, "TICKET_NOT_FOUND"); + } + + @Test + void checkInRecordsTheTimeAndTheStaffUserWithAConditionalUpdate() { + named(); + TicketService.StaffView v = service.checkIn(door(null, null, null, null)); + verify(tickets).checkIn(eq(1L), any(LocalDateTime.class), eq("staff1")); + assertThat(v.state()).isEqualTo(TicketState.CHECKED_IN); + assertThat(v.checkedInBy()).isEqualTo("staff1"); + assertThat(ticket.getCheckedInAt()).isNotNull(); + verify(registration, never()).register(any()); + } + + @Test + void aSecondCheckInIsRefusedWithTheFirstTime() { + named(); + LocalDateTime first = LocalDateTime.of(2026, 12, 4, 9, 30); + ticket.setCheckedInAt(first); + assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "ALREADY_CHECKED_IN|" + first); + verify(tickets, never()).checkIn(anyLong(), any(), any()); + } + + @Test + void aScannerThatLosesTheRaceIsRefused() { + named(); + when(tickets.checkIn(eq(1L), any(), any())).thenReturn(0); + assertThatThrownBy(() -> service.checkIn(door(null, null, null, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, ex -> assertThat(ex.getReason()).startsWith("ALREADY_CHECKED_IN|")); + } + + @Test + void anInvalidTicketIsRefusedWithItsState() { + named(); + order.setStatus(ShopOrder.AWAITING); + assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "NOT_VALID|AWAITING"); + order.setStatus(ShopOrder.CANCELLED); + assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "NOT_VALID|ORDER_CANCELLED"); + order.setStatus(ShopOrder.EXPIRED); + assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "NOT_VALID|ORDER_EXPIRED"); + order.setStatus(ShopOrder.PAID); + ticket.setStatus(Ticket.CANCELLED); + assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "NOT_VALID|TICKET_CANCELLED"); + verify(tickets, never()).checkIn(anyLong(), any(), any()); + } + + @Test + void checkInIsRefusedOutsideTheEventDays() { + named(); + event.setDateStart(LocalDateTime.now().plusDays(3)); + event.setDateEnd(LocalDateTime.now().plusDays(4)); + assertStatus(() -> service.checkIn(door(null, null, null, null)), 409, "NOT_EVENT_DAY"); + verify(tickets, never()).checkIn(anyLong(), any(), any()); + } + + @Test + void anUnnamedTicketNeedsANameAndContactAndCreatesNoLeadWithoutConsent() { + assertStatus(() -> service.checkIn(door(null, "+60125550101", null, null)), 400, "NAME_REQUIRED"); + assertStatus(() -> service.checkIn(door("Lim Wei", null, " ", null)), 400, "MOBILE_OR_EMAIL_REQUIRED"); + verify(tickets, never()).checkIn(anyLong(), any(), any()); + service.checkIn(door(" Lim Wei ", "+60125550101", null, null)); + assertThat(ticket.getAttendeeName()).isEqualTo("Lim Wei"); + assertThat(ticket.getAttendeeMobileE164()).isEqualTo("+60125550101"); + assertThat(ticket.getAttendeeNamedAt()).isNotNull(); + assertThat(ticket.getCode()).isEqualTo(CODE); + verify(registration, never()).register(any()); + } + + @Test + void consentAtTheDoorCreatesTheLeadMarkedAttended() { + service.checkIn(door("Lim Wei", "+60125550101", null, 77L)); + ArgumentCaptor r = ArgumentCaptor.forClass(RegistrationService.RegisterRequest.class); + verify(registration).register(r.capture()); + assertThat(r.getValue().source()).isEqualTo("TICKET"); + assertThat(r.getValue().attend()).isTrue(); + assertThat(r.getValue().mobileE164()).isEqualTo("+60125550101"); + assertThat(ticket.getEventLeadUuid()).isEqualTo(5000L); + assertThat(ticket.getAttendeeConsentAt()).isNotNull(); + } + + @Test + void anEarlierConsentMarksTheExistingLeadAttended() { + named(); + ticket.setAttendeeConsentAt(LocalDateTime.now().minusDays(1)); + ticket.setEventLeadUuid(5000L); + EventLead el = new EventLead(); + when(eventLeads.findByUuid(5000L)).thenReturn(Optional.of(el)); + service.checkIn(door(null, null, null, null)); + assertThat(el.getAttendedAt()).isNotNull(); + verify(eventLeads).save(el); + verify(registration, never()).register(any()); + } + + // ---- venue self check-in on a ticketed event + + private EventCheckInService.LookupResult selfCheckIn(String mobile, String email) { + return venue.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, mobile, email)); + } + + @Test + void aNamedAttendeeChecksThemselvesIn() { + ticket.setAttendeeName("Lim Wei"); + ticket.setAttendeeMobileE164("+60125550101"); + when(tickets.selfCheckIn(EVENT, "+60125550101", null)).thenReturn(List.of(new Object[]{ticket, "Aisyah Rahman"})); + EventCheckInService.LookupResult r = selfCheckIn("+60125550101", null); + assertThat(r.result()).isEqualTo("CHECKED_IN"); + assertThat(r.firstName()).isEqualTo("Lim"); + verify(tickets).checkIn(eq(1L), any(LocalDateTime.class), eq("self")); + } + + @Test + void anUnnamedTicketWelcomesItsBuyerAndMarksAConsentedLeadAttended() { + ticket.setEventLeadUuid(5000L); + EventLead el = new EventLead(); + when(eventLeads.findByUuid(5000L)).thenReturn(Optional.of(el)); + when(tickets.selfCheckIn(EVENT, null, "a@example.test")).thenReturn(List.of(new Object[]{ticket, "Aisyah Rahman"})); + EventCheckInService.LookupResult r = selfCheckIn(null, "a@example.test"); + assertThat(r.firstName()).isEqualTo("Aisyah"); + assertThat(el.getAttendedAt()).isNotNull(); + } + + @Test + void theNextTicketIsTakenWhenTheOldestWasJustCheckedInElsewhere() { + Ticket second = new Ticket(); + second.setId(2L); + when(tickets.selfCheckIn(EVENT, "+60125550101", null)) + .thenReturn(List.of(new Object[]{ticket, "Aisyah Rahman"}, new Object[]{second, "Aisyah Rahman"})); + when(tickets.checkIn(eq(1L), any(), any())).thenReturn(0); + when(tickets.checkIn(eq(2L), any(), any())).thenReturn(1); + assertThat(selfCheckIn("+60125550101", null).result()).isEqualTo("CHECKED_IN"); + verify(tickets).checkIn(eq(2L), any(), eq("self")); + } + + @Test + void aRegisteredGuestStillChecksIn() { + EventLead el = new EventLead(); + el.setId(55L); + Lead lead = new Lead(); + lead.setName("Tan Mei Ling"); + when(tickets.selfCheckIn(EVENT, "+60125550102", null)).thenReturn(List.of()); + when(eventLeads.findByEventAndMobile(EVENT, "+60125550102")).thenReturn(List.of(new Object[]{el, lead})); + when(guests.existsByEventLeadId(55L)).thenReturn(true); + EventCheckInService.LookupResult r = selfCheckIn("+60125550102", null); + assertThat(r.result()).isEqualTo("CHECKED_IN"); + assertThat(r.firstName()).isEqualTo("Tan"); + assertThat(el.getAttendedAt()).isNotNull(); + } + + @Test + void anyoneElseIsAskedToShowTheirTicket() { + EventLead el = new EventLead(); + el.setId(56L); + Lead lead = new Lead(); + lead.setName("Buyer Of A Cancelled Order"); + when(tickets.selfCheckIn(EVENT, "+60125550103", null)).thenReturn(List.of()); + when(eventLeads.findByEventAndMobile(EVENT, "+60125550103")).thenReturn(List.of(new Object[]{el, lead})); + when(guests.existsByEventLeadId(56L)).thenReturn(false); + EventCheckInService.LookupResult r = selfCheckIn("+60125550103", null); + assertThat(r.result()).isEqualTo("SHOW_TICKET"); + assertThat(r.firstName()).isNull(); + assertThat(el.getAttendedAt()).isNull(); + verify(eventLeads, never()).save(any()); + } + + @Test + void anEventWithoutTicketsKeepsTheOldResults() { + event.setTicketsEnabled(false); + when(eventLeads.findByEventAndMobile(EVENT, "+60125550104")).thenReturn(List.of()); + assertThat(selfCheckIn("+60125550104", null).result()).isEqualTo("FORM"); + verify(tickets, never()).selfCheckIn(anyLong(), any(), any()); + } + + @Test + void aWalkInRegistrationIsRefusedOnATicketedEvent() { + EventLeadService leadService = mock(EventLeadService.class); + when(leadService.sellsTickets(EVENT)).thenReturn(true); + RegistrationService reg = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)), + leads, eventLeads, leadService); + RegistrationService.RegisterRequest walkIn = new RegistrationService.RegisterRequest(COMPANY, EVENT, null, "Walk In", + "+60125550105", null, null, null, List.of(), 77L, LocalDateTime.now(), true, null, null); + assertStatus(() -> reg.register(walkIn), 409, "TICKETS_ONLY"); + verify(eventLeads, never()).saveAndFlush(any()); + } + + // ---- counts + + @Test + void theHeadcountGivesTicketsAwaitingPaidAndCheckedIn() { + when(tickets.countsByOrderStatus(EVENT)).thenReturn(List.of(new Object[]{ShopOrder.AWAITING, 2L, 0L}, + new Object[]{ShopOrder.PAID, 5L, 3L})); + EventHeadcountService.Headcount h = new EventHeadcountService(events, guests, eventLeads, tickets) + .headcount(new EventHeadcountService.Request(COMPANY, EVENT)); + assertThat(h.ticketsAwaiting()).isEqualTo(2); + assertThat(h.ticketsPaid()).isEqualTo(5); + assertThat(h.ticketsCheckedIn()).isEqualTo(3); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCodesTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCodesTest.java index 025f2c5..ab02b12 100644 --- a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCodesTest.java +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCodesTest.java @@ -68,7 +68,7 @@ class TicketCodesTest { orderService = new TicketOrderService(new TransactionTemplate(mock(PlatformTransactionManager.class)), events, typeService, types, orders, lines, tickets, guests, eventLeads, registration, mailer); staff = new TicketOrderStaffService(events, typeService, types, tickets, orders, lines, mailer); - ticketService = new TicketService(tickets, orders, lines, registration, mailer); + ticketService = new TicketService(tickets, orders, lines, registration, mailer, events, eventLeads); Event event = new Event(); event.setUuid(EVENT); event.setCompanyId(COMPANY);