feat(tickets): ticket order request with seat locking, capacity and buyer lead

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-04 15:31:05 +08:00
1 parent b8a1873266
commit 6dca31510e
15 files changed
+775 -14

No files matched your search

@@ -0,0 +1,21 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.service.TicketOrderService;
import lombok.AllArgsConstructor;
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;
/** Ticket orders (add-event-ticket-orders). request and byToken are the public paths. */
@RestController
@RequestMapping("/counter/ticketOrder")
@AllArgsConstructor
public class TicketOrderController {
private final TicketOrderService service;
@PostMapping("/request")
public TicketOrderService.Result request(@RequestBody TicketOrderService.Request req) {
return service.request(req);
}
}
@@ -45,8 +45,8 @@ public interface EventLeadRepository extends JpaRepository<EventLead, Long> {
long countByEventUuidAndAttendedAtIsNotNull(long eventUuid);
/** Event leads of the event that no guest row links to. */
@Query("SELECT COUNT(e) FROM EventLead e WHERE e.eventUuid = :eventUuid"
/** Event leads of the event that no guest row links to and no ticket order created (their seats count as held tickets). */
@Query("SELECT COUNT(e) FROM EventLead e WHERE e.eventUuid = :eventUuid AND (e.source IS NULL OR e.source <> 'TICKET')"
+ " AND NOT EXISTS (SELECT 1 FROM EventGuest g WHERE g.eventLeadId = e.id)")
long countWalkIns(@Param("eventUuid") long eventUuid);
@@ -9,4 +9,8 @@ import java.util.Optional;
@Repository
public interface ShopOrderRepository extends JpaRepository<ShopOrder, Long> {
Optional<ShopOrder> findByToken(String token);
long countByEventUuidAndBuyerEmailAndStatus(Long eventUuid, String buyerEmail, String status);
boolean existsByCompanyIdAndReference(long companyId, String reference);
}
@@ -16,5 +16,9 @@ public interface TicketRepository extends JpaRepository<Ticket, Long> {
+ " group by t.ticketTypeId")
List<TicketHeld> heldByType(@Param("eventUuid") long eventUuid);
@Query("select count(t) from Ticket t, ShopOrder o where o.id = t.orderId and t.eventUuid = :eventUuid"
+ " and t.status = 'ACTIVE' and o.status in ('AWAITING', 'PAID')")
long countHeld(@Param("eventUuid") long eventUuid);
List<Ticket> findByOrderIdOrderByIdAsc(long orderId);
}
@@ -8,6 +8,7 @@ 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 com.solvway.services.counter.repo.TicketRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
@@ -28,7 +29,6 @@ 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) {}
@@ -51,6 +51,25 @@ public class EventGuestService {
private final EventLeadRepository eventLeadRepository;
private final EventSalespersonRepository eventSalespersonRepository;
private final RegistrationService registrationService;
private final TicketRepository ticketRepository;
@org.springframework.beans.factory.annotation.Autowired
public EventGuestService(EventRepository eventRepository, EventGuestRepository guestRepository, EventLeadRepository eventLeadRepository,
EventSalespersonRepository eventSalespersonRepository, RegistrationService registrationService,
TicketRepository ticketRepository) {
this.eventRepository = eventRepository;
this.guestRepository = guestRepository;
this.eventLeadRepository = eventLeadRepository;
this.eventSalespersonRepository = eventSalespersonRepository;
this.registrationService = registrationService;
this.ticketRepository = ticketRepository;
}
// ponytail: null ticket repository keeps the pre-ticketing wiring of older tests; held tickets then count 0.
public EventGuestService(EventRepository eventRepository, EventGuestRepository guestRepository, EventLeadRepository eventLeadRepository,
EventSalespersonRepository eventSalespersonRepository, RegistrationService registrationService) {
this(eventRepository, guestRepository, eventLeadRepository, eventSalespersonRepository, registrationService, null);
}
private static ResponseStatusException notFound(String code) {
return new ResponseStatusException(HttpStatus.NOT_FOUND, code);
@@ -191,7 +210,8 @@ public class EventGuestService {
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()) {
+ eventLeadRepository.countWalkIns(g.getEventUuid())
+ (ticketRepository == null ? 0 : ticketRepository.countHeld(g.getEventUuid())) >= event.getCapacity()) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "EVENT_FULL");
}
Long stored = g.getSalespersonUserId();
@@ -3,22 +3,41 @@ package com.solvway.services.counter.service;
import com.solvway.services.counter.repo.EventGuestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventRepository;
import lombok.AllArgsConstructor;
import com.solvway.services.counter.repo.TicketRepository;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
/** Invited / registered / attended numbers of one event. */
@Service
@AllArgsConstructor
public class EventHeadcountService {
public record Request(Long companyId, long eventUuid) {}
/** total = registered guests + walk-ins (event leads with no guest row). */
public record Headcount(long invited, Integer cap, long registered, long attended, long walkIns, long total, Integer capacity) {}
/** 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) {
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);
}
}
private final EventRepository eventRepository;
private final EventGuestRepository guestRepository;
private final EventLeadRepository eventLeadRepository;
private final TicketRepository ticketRepository;
@org.springframework.beans.factory.annotation.Autowired
public EventHeadcountService(EventRepository eventRepository, EventGuestRepository guestRepository,
EventLeadRepository eventLeadRepository, TicketRepository ticketRepository) {
this.eventRepository = eventRepository;
this.guestRepository = guestRepository;
this.eventLeadRepository = eventLeadRepository;
this.ticketRepository = ticketRepository;
}
// ponytail: null ticket repository keeps the pre-ticketing wiring of older tests; held tickets are then 0.
public EventHeadcountService(EventRepository eventRepository, EventGuestRepository guestRepository, EventLeadRepository eventLeadRepository) {
this(eventRepository, guestRepository, eventLeadRepository, null);
}
public Headcount headcount(Request req) {
var event = eventRepository.findByUuid(req.eventUuid())
@@ -26,8 +45,9 @@ public class EventHeadcountService {
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"));
long registered = guestRepository.countByEventUuidAndEventLeadIdIsNotNull(req.eventUuid());
long walkIns = eventLeadRepository.countWalkIns(req.eventUuid());
long held = ticketRepository == null ? 0 : ticketRepository.countHeld(req.eventUuid());
return new Headcount(guestRepository.countByEventUuid(req.eventUuid()), event.getInvitationCap(), registered,
eventLeadRepository.countByEventUuidAndAttendedAtIsNotNull(req.eventUuid()), walkIns, registered + walkIns,
event.getCapacity());
eventLeadRepository.countByEventUuidAndAttendedAtIsNotNull(req.eventUuid()), walkIns, registered + walkIns + held,
event.getCapacity(), held);
}
}
@@ -51,6 +51,7 @@ public class RegistrationService {
private static final String QR = "qr";
private static final String WEB = "WEB";
private static final String TICKET = "TICKET";
private static final int UTM_MAX = 100;
private final TransactionTemplate transactionTemplate;
@@ -105,7 +106,7 @@ public class RegistrationService {
lead = match.get();
Optional<EventLead> captured = eventLeadRepository.findByEventUuidAndLeadUuid(req.eventUuid(), lead.getUuid());
if (captured.isPresent()) return alreadyCaptured(captured.get(), lead, req);
notes = differences(lead, req, WEB.equals(req.source()) ? "web page" : "QR");
notes = differences(lead, req, WEB.equals(req.source()) ? "web page" : TICKET.equals(req.source()) ? "ticket order" : "QR");
leadType = "EXISTING";
}
@@ -127,7 +128,9 @@ public class RegistrationService {
e.setUtmCampaign(cut(req.utmCampaign()));
// An invite link can be opened anywhere, so an invite registration never counts as attending; the guest checks in.
// A web page sign-up neither: a standing enquiries event is always running.
boolean atVenue = !"INVITE".equals(req.source()) && !WEB.equals(req.source()) && eventLeadService.isDuringEvent(req.eventUuid());
// A ticket buyer neither: holding a ticket is not being at the venue (add-event-tickets checks tickets in).
boolean atVenue = !"INVITE".equals(req.source()) && !WEB.equals(req.source()) && !TICKET.equals(req.source())
&& eventLeadService.isDuringEvent(req.eventUuid());
if (req.attend() || atVenue) e.setAttendedAt(LocalDateTime.now());
e = eventLeadRepository.saveAndFlush(e);
eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR);
@@ -0,0 +1,224 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Event;
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.model.TicketType;
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.ShopOrderLineRepository;
import com.solvway.services.counter.repo.ShopOrderRepository;
import com.solvway.services.counter.repo.TicketRepository;
import com.solvway.services.counter.repo.TicketTypeRepository;
import com.solvway.services.counter.util.EventDays;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.server.ResponseStatusException;
import java.security.SecureRandom;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.solvway.services.counter.service.TicketTypeService.MALAYSIA;
import static com.solvway.services.counter.service.TicketTypeService.status;
/**
* Ticket orders (add-event-ticket-orders). A request locks its event row, so the seat count and the insert of one
* event's requests run one at a time and a ticket type never oversells. Never log a buyer's name, mobile or email.
*/
@Slf4j
@Service
@AllArgsConstructor
public class TicketOrderService {
static final int MAX_TICKETS = 10;
static final int MAX_AWAITING = 3;
private static final String REFERENCE_CHARS = "23456789ABCDEFGHJKMNPQRSTUVWXYZ";
private static final SecureRandom RANDOM = new SecureRandom();
private final TransactionTemplate transactionTemplate;
private final EventRepository events;
private final TicketTypeService typeService;
private final TicketTypeRepository types;
private final ShopOrderRepository orders;
private final ShopOrderLineRepository lines;
private final TicketRepository tickets;
private final EventGuestRepository guests;
private final EventLeadRepository eventLeads;
private final RegistrationService registration;
public record LineRequest(Long ticketTypeId, Integer quantity) {}
/** Values arrive normalised by mobile-api; the counter re-checks what the order's correctness depends on. */
public record Request(Long companyId, long eventUuid, List<LineRequest> lines, String buyerName, String buyerEmail,
String buyerMobileE164, String buyerCompany, Long consentNoticeId, LocalDateTime consentAt,
String pagePath, String utmSource, String utmMedium, String utmCampaign) {}
public record LineView(String name, int unitPriceSen, int quantity) {}
public record Result(String reference, String token, String status, int totalSen, LocalDateTime holdUntil,
List<LineView> lines, String paymentInstructions) {}
private record Created(ShopOrder order, Result result) {}
public Result request(Request r) {
Created created = transactionTemplate.execute(s -> create(r));
attachBuyerLead(r, created.order());
return created.result();
}
private Created create(Request r) {
if (r.buyerName() == null || r.buyerName().isBlank()) throw status(HttpStatus.BAD_REQUEST, "NAME_REQUIRED");
if (r.buyerEmail() == null || r.buyerEmail().isBlank()) throw status(HttpStatus.BAD_REQUEST, "EMAIL_REQUIRED");
if (r.consentNoticeId() == null || r.consentAt() == null) throw status(HttpStatus.BAD_REQUEST, "CONSENT_REQUIRED");
List<LineRequest> wanted = checkedQuantities(r.lines());
Event event = events.lockByUuid(r.eventUuid())
.filter(e -> r.companyId() != null && r.companyId().equals(e.getCompanyId()))
.orElseThrow(() -> status(HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"));
LocalDate today = LocalDate.now(MALAYSIA);
if (!TicketTypeService.ticketsOpen(event, today)) throw status(HttpStatus.CONFLICT, "TICKETS_CLOSED");
if (orders.countByEventUuidAndBuyerEmailAndStatus(event.getUuid(), r.buyerEmail(), ShopOrder.AWAITING) >= MAX_AWAITING) {
throw status(HttpStatus.CONFLICT, "TOO_MANY_AWAITING");
}
Map<Long, Long> held = typeService.held(event.getUuid());
Map<Long, TicketType> byId = types.findByEventUuidOrderBySortAscIdAsc(event.getUuid()).stream()
.collect(Collectors.toMap(TicketType::getId, Function.identity()));
int seats = 0;
for (LineRequest l : wanted) {
TicketType t = byId.get(l.ticketTypeId());
long left = t == null ? 0 : Math.max(0, t.getQuantity() - held.getOrDefault(t.getId(), 0L));
if (t == null || !t.isEnabled() || TicketTypeService.salesEnded(t, event, today) || l.quantity() > left) {
throw status(HttpStatus.CONFLICT, "TYPE_UNAVAILABLE|" + l.ticketTypeId() + "|" + left);
}
seats += l.quantity();
}
if (event.getCapacity() != null && !EventDays.isDuring(event, LocalDateTime.now())) {
long used = guests.countByEventUuidAndEventLeadIdIsNotNull(event.getUuid()) + eventLeads.countWalkIns(event.getUuid())
+ held.values().stream().mapToLong(Long::longValue).sum();
if (used + seats > event.getCapacity()) {
throw status(HttpStatus.CONFLICT, "EVENT_FULL|" + Math.max(0, event.getCapacity() - used));
}
}
LocalDateTime now = LocalDateTime.now();
int total = wanted.stream().mapToInt(l -> byId.get(l.ticketTypeId()).getPriceSen() * l.quantity()).sum();
ShopOrder o = new ShopOrder();
o.setCompanyId(event.getCompanyId());
o.setEventUuid(event.getUuid());
o.setReference(newReference(event.getCompanyId()));
o.setToken(newToken());
o.setBuyerName(r.buyerName().strip());
o.setBuyerEmail(r.buyerEmail());
o.setBuyerMobileE164(r.buyerMobileE164());
o.setBuyerCompany(r.buyerCompany());
o.setTotalSen(total);
if (total == 0) {
o.setStatus(ShopOrder.PAID);
o.setPaidAt(now);
o.setPaidBy("system");
} else {
o.setStatus(ShopOrder.AWAITING);
o.setHoldUntil(now.plusDays(event.getHoldDays()));
}
o.setConsentNoticeId(r.consentNoticeId());
o.setConsentAt(r.consentAt());
o.setPagePath(r.pagePath());
o.setUtmSource(r.utmSource());
o.setUtmMedium(r.utmMedium());
o.setUtmCampaign(r.utmCampaign());
o.setCreatedAt(now);
o = orders.saveAndFlush(o);
List<LineView> views = new ArrayList<>();
for (LineRequest l : wanted) {
TicketType t = byId.get(l.ticketTypeId());
ShopOrderLine line = new ShopOrderLine();
line.setOrderId(o.getId());
line.setKind(ShopOrderLine.TICKET);
line.setItemId(t.getId());
line.setName(t.getName());
line.setUnitPriceSen(t.getPriceSen());
line.setQuantity(l.quantity());
line = lines.save(line);
for (int i = 0; i < l.quantity(); i++) {
Ticket ticket = new Ticket();
ticket.setCompanyId(o.getCompanyId());
ticket.setEventUuid(event.getUuid());
ticket.setOrderId(o.getId());
ticket.setOrderLineId(line.getId());
ticket.setTicketTypeId(t.getId());
tickets.save(ticket);
}
views.add(new LineView(t.getName(), t.getPriceSen(), l.quantity()));
}
return new Created(o, new Result(o.getReference(), o.getToken(), o.getStatus(), total, o.getHoldUntil(), views,
event.getPaymentInstructions()));
}
/** 1 to 10 seats in all, each line 1 to 10, no type twice; lines asking for 0 are dropped. */
private static List<LineRequest> checkedQuantities(List<LineRequest> requested) {
if (requested == null) throw status(HttpStatus.BAD_REQUEST, "BAD_QUANTITY");
List<LineRequest> wanted = new ArrayList<>();
Set<Long> seen = new HashSet<>();
int total = 0;
for (LineRequest l : requested) {
if (l == null || l.ticketTypeId() == null || l.quantity() == null || l.quantity() < 0 || l.quantity() > MAX_TICKETS
|| !seen.add(l.ticketTypeId())) {
throw status(HttpStatus.BAD_REQUEST, "BAD_QUANTITY");
}
if (l.quantity() > 0) wanted.add(l);
total += l.quantity();
}
if (total < 1 || total > MAX_TICKETS) throw status(HttpStatus.BAD_REQUEST, "BAD_QUANTITY");
return wanted;
}
/** The buyer becomes an event lead after the order commits; a failure here never loses the order. */
private void attachBuyerLead(Request r, ShopOrder o) {
try {
RegistrationService.RegisterResult reg = registration.register(new RegistrationService.RegisterRequest(r.companyId(),
r.eventUuid(), null, r.buyerName().strip(), r.buyerMobileE164(), r.buyerEmail(), r.buyerCompany(), null, List.of(),
r.consentNoticeId(), r.consentAt(), false, "TICKET", null, r.pagePath(), r.utmSource(), r.utmMedium(), r.utmCampaign()));
if (reg == null || reg.eventLeadUuid() == null) return;
eventLeads.findByUuid(Long.parseLong(reg.eventLeadUuid())).ifPresent(el -> {
String note = "Ticket order " + o.getReference();
el.setNotes(el.getNotes() == null || el.getNotes().isBlank() ? note : el.getNotes() + "\n" + note);
eventLeads.save(el);
o.setEventLeadUuid(el.getUuid());
o.setLeadUuid(el.getLeadUuid());
orders.save(o);
});
} catch (RuntimeException e) {
log.warn("Ticket order {}: buyer lead capture failed: {}", o.getId(), e.getClass().getSimpleName());
}
}
private String newReference(long companyId) {
String ref;
do {
StringBuilder b = new StringBuilder("T-");
for (int i = 0; i < 6; i++) b.append(REFERENCE_CHARS.charAt(RANDOM.nextInt(REFERENCE_CHARS.length())));
ref = b.toString();
} while (orders.existsByCompanyIdAndReference(companyId, ref));
return ref;
}
static String newToken() {
byte[] bytes = new byte[16];
RANDOM.nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
}