feat(tickets): staff order actions, order emails and hold expiry job

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:39:28 +08:00
1 parent 6dca31510e
commit 687f054acf
14 files changed
+844 -4

No files matched your search

@@ -1,21 +1,60 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.service.TicketOrderService;
import com.solvway.services.counter.service.TicketOrderStaffService;
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;
/** Ticket orders (add-event-ticket-orders). request and byToken are the public paths. */
/** Ticket orders (add-event-ticket-orders). request and byToken are the public paths; the rest are staff calls from mobile-api. */
@RestController
@RequestMapping("/counter/ticketOrder")
@AllArgsConstructor
public class TicketOrderController {
private final TicketOrderService service;
private final TicketOrderStaffService staff;
@PostMapping("/request")
public TicketOrderService.Result request(@RequestBody TicketOrderService.Request req) {
return service.request(req);
}
@GetMapping("/byToken/{token}")
public TicketOrderService.OrderView byToken(@PathVariable String token) {
return service.byToken(token);
}
@PostMapping("/list")
public TicketOrderStaffService.Page list(@RequestBody TicketOrderStaffService.ListRequest req) {
return staff.list(req);
}
@PostMapping("/get")
public TicketOrderStaffService.Detail get(@RequestBody TicketOrderStaffService.OrderRef req) {
return staff.get(req);
}
@PostMapping("/markPaid")
public void markPaid(@RequestBody TicketOrderStaffService.PayRequest req) {
staff.markPaid(req);
}
@PostMapping("/cancel")
public void cancel(@RequestBody TicketOrderStaffService.ActionRequest req) {
staff.cancel(req);
}
@PostMapping("/cancelTicket")
public void cancelTicket(@RequestBody TicketOrderStaffService.ActionRequest req) {
staff.cancelTicket(req);
}
@PostMapping("/resend")
public void resend(@RequestBody TicketOrderStaffService.OrderRef req) {
staff.resend(req);
}
}
@@ -1,9 +1,17 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.ShopOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@Repository
@@ -13,4 +21,21 @@ public interface ShopOrderRepository extends JpaRepository<ShopOrder, Long> {
long countByEventUuidAndBuyerEmailAndStatus(Long eventUuid, String buyerEmail, String status);
boolean existsByCompanyIdAndReference(long companyId, String reference);
/** Staff list: q is a lower-case LIKE pattern or null; status null means every state. */
@Query("select o from ShopOrder o where o.companyId = :companyId and o.eventUuid = :eventUuid"
+ " and (:status is null or o.status = :status)"
+ " and (:q is null or lower(o.reference) like :q or lower(o.buyerName) like :q or lower(o.buyerEmail) like :q"
+ " or o.buyerMobileE164 like :q)")
Page<ShopOrder> search(@Param("companyId") long companyId, @Param("eventUuid") long eventUuid, @Param("status") String status,
@Param("q") String q, Pageable pageable);
List<ShopOrder> findTop100ByStatusAndHoldUntilBeforeOrderByIdAsc(String status, LocalDateTime now);
/** Expires one order only if it still awaits payment, so it never overwrites a payment made meanwhile. */
@Modifying
@Transactional
@Query("update ShopOrder o set o.status = 'EXPIRED', o.expiredAt = :now, o.lastEmail = 'EXPIRED'"
+ " where o.id = :id and o.status = 'AWAITING'")
int expireIfAwaiting(@Param("id") long id, @Param("now") LocalDateTime now);
}
@@ -0,0 +1,4 @@
package com.solvway.services.counter.repo;
/** Active tickets of one order. */
public record TicketCount(Long orderId, Long tickets) {}
@@ -21,4 +21,9 @@ public interface TicketRepository extends JpaRepository<Ticket, Long> {
long countHeld(@Param("eventUuid") long eventUuid);
List<Ticket> findByOrderIdOrderByIdAsc(long orderId);
/** 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")
List<TicketCount> activeByOrder(@Param("orderIds") java.util.Collection<Long> orderIds);
}
@@ -0,0 +1,44 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.ShopOrder;
import com.solvway.services.counter.repo.ShopOrderRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
/** Expires ticket orders whose hold ran out, freeing their seats (add-event-ticket-orders). Every 10 minutes. */
@Slf4j
@Service
@AllArgsConstructor
public class TicketOrderExpiryJob {
private final ShopOrderRepository orders;
private final TicketOrderMailer mailer;
@Scheduled(cron = "${tickets.expiry.cron:0 */10 * * * *}", zone = "Asia/Kuala_Lumpur")
public void scheduled() {
int n = run();
if (n > 0) log.info("Expired {} ticket orders", n);
}
int run() {
int expired = 0;
List<ShopOrder> due;
do {
LocalDateTime now = LocalDateTime.now();
due = orders.findTop100ByStatusAndHoldUntilBeforeOrderByIdAsc(ShopOrder.AWAITING, now);
for (ShopOrder o : due) {
if (orders.expireIfAwaiting(o.getId(), now) == 1) {
o.setStatus(ShopOrder.EXPIRED);
o.setExpiredAt(now);
mailer.send(o, TicketOrderMailer.EXPIRED);
expired++;
}
}
} while (due.size() == 100);
return expired;
}
}
@@ -0,0 +1,131 @@
package com.solvway.services.counter.service;
import com.solvway.core.enums.EmailEnum;
import com.solvway.core.model.Email;
import com.solvway.core.model.Recipient;
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.repo.EventRepository;
import com.solvway.services.counter.repo.ShopOrderLineRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.util.HtmlUtils;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* Buyer emails of a ticket order (add-event-ticket-orders), English then Bahasa Malaysia like the invite email.
* Sent after the surrounding transaction commits; best effort: a failure is logged by order id and never undoes the order.
*/
@Slf4j
@Service
public class TicketOrderMailer {
public static final String RECEIVED = "RECEIVED";
public static final String PAID = "PAID";
public static final String EXPIRED = "EXPIRED";
public static final String CANCELLED = "CANCELLED";
private static final DateTimeFormatter WHEN = DateTimeFormatter.ofPattern("d MMM yyyy, h:mm a");
private final EmailService emailService;
private final EventRepository events;
private final ShopOrderLineRepository lines;
private final String portalBase;
public TicketOrderMailer(EmailService emailService, EventRepository events, ShopOrderLineRepository lines,
@Value("${app.admin-portal-base-url}") String portalBase) {
this.emailService = emailService;
this.events = events;
this.lines = lines;
this.portalBase = portalBase;
}
public void send(ShopOrder order, String kind) {
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
deliver(order, kind);
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override public void afterCommit() { deliver(order, kind); }
});
}
private void deliver(ShopOrder o, String kind) {
try {
Event event = o.getEventUuid() == null ? null : events.findByUuid(o.getEventUuid()).orElse(null);
Email email = new Email();
email.setCompanyId(o.getCompanyId());
email.setSubject(subject(o, kind));
email.setBody(body(o, kind, event, lines.findByOrderIdOrderByIdAsc(o.getId())));
email.setStatus(EmailEnum.StatusType.P);
email.setRecipients(List.of(new Recipient(null, o.getBuyerEmail(), EmailEnum.RecipientType.R, EmailEnum.RecipientStatusType.Y)));
emailService.send(email);
} catch (RuntimeException e) {
log.warn("Ticket order {} email {} failed: {}", o.getId(), kind, e.getClass().getSimpleName());
}
}
private static String subject(ShopOrder o, String kind) {
String ref = o.getReference();
return switch (kind) {
case PAID -> "Order " + ref + " confirmed / Pesanan " + ref + " disahkan";
case EXPIRED -> "Order " + ref + " expired / Pesanan " + ref + " tamat tempoh";
case CANCELLED -> "Order " + ref + " cancelled / Pesanan " + ref + " dibatalkan";
default -> "Your ticket order " + ref + " / Pesanan tiket anda " + ref;
};
}
private String body(ShopOrder o, String kind, Event event, List<ShopOrderLine> orderLines) {
String name = esc(o.getBuyerName());
String link = esc(portalBase + "/o/" + o.getToken());
StringBuilder items = new StringBuilder("<p>");
for (ShopOrderLine l : orderLines) {
if (l.getQuantity() > 0) items.append(l.getQuantity()).append(" × ").append(esc(l.getName())).append(" — ")
.append(money(l.getUnitPriceSen() * l.getQuantity())).append("<br>");
}
items.append("<strong>Total: ").append(money(o.getTotalSen())).append("</strong></p>");
String eventLine = event == null ? "" : "<p><strong>" + esc(event.getName()) + "</strong>"
+ (event.getLocation() == null ? "" : "<br>" + esc(event.getLocation())) + "</p>";
String instructions = event == null || event.getPaymentInstructions() == null ? ""
: esc(event.getPaymentInstructions()).replace("\n", "<br>");
String hold = o.getHoldUntil() == null ? "" : esc(o.getHoldUntil().format(WHEN));
String orderLink = "<p><a href=\"" + link + "\">" + link + "</a></p>";
String en, ms;
switch (kind) {
case PAID -> {
en = "<p>Your order " + esc(o.getReference()) + " is confirmed.</p>";
ms = "<p>Pesanan anda " + esc(o.getReference()) + " telah disahkan.</p>";
}
case EXPIRED -> {
en = "<p>Your order " + esc(o.getReference()) + " was not paid in time, so its tickets were released.</p>";
ms = "<p>Pesanan anda " + esc(o.getReference()) + " tidak dibayar dalam tempoh, jadi tiketnya telah dilepaskan.</p>";
}
case CANCELLED -> {
en = "<p>Your order " + esc(o.getReference()) + " was cancelled.</p>";
ms = "<p>Pesanan anda " + esc(o.getReference()) + " telah dibatalkan.</p>";
}
default -> {
en = "<p>We received your order " + esc(o.getReference()) + ". Please pay by " + hold + " to keep your tickets:</p><p>"
+ instructions + "</p>";
ms = "<p>Kami telah menerima pesanan anda " + esc(o.getReference()) + ". Sila bayar sebelum " + hold
+ " untuk menyimpan tiket anda:</p><p>" + instructions + "</p>";
}
}
return "<p>Dear " + name + ",</p>" + en + eventLine + items + orderLink
+ "<hr><p><i>Bahasa Malaysia</i></p><p>Tuan/Puan " + name + ",</p>" + ms + eventLine + items + orderLink;
}
static String money(int sen) {
return "RM " + new DecimalFormat("#,##0.00").format(BigDecimal.valueOf(sen, 2));
}
private static String esc(Object value) {
return HtmlUtils.htmlEscape(String.valueOf(value == null ? "" : value));
}
}
@@ -58,6 +58,7 @@ public class TicketOrderService {
private final EventGuestRepository guests;
private final EventLeadRepository eventLeads;
private final RegistrationService registration;
private final TicketOrderMailer mailer;
public record LineRequest(Long ticketTypeId, Integer quantity) {}
@@ -73,6 +74,18 @@ public class TicketOrderService {
private record Created(ShopOrder order, Result result) {}
/** The public order page: the buyer's name but no other personal details. */
public record OrderView(long companyId, Long eventUuid, String reference, String status, String buyerName, int totalSen,
LocalDateTime holdUntil, LocalDateTime createdAt, List<LineView> lines) {}
public OrderView byToken(String token) {
ShopOrder o = orders.findByToken(token).orElseThrow(() -> status(HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND"));
List<LineView> views = lines.findByOrderIdOrderByIdAsc(o.getId()).stream()
.map(l -> new LineView(l.getName(), l.getUnitPriceSen(), l.getQuantity())).toList();
return new OrderView(o.getCompanyId(), o.getEventUuid(), o.getReference(), o.getStatus(), o.getBuyerName(), o.getTotalSen(),
o.getHoldUntil(), o.getCreatedAt(), views);
}
public Result request(Request r) {
Created created = transactionTemplate.execute(s -> create(r));
attachBuyerLead(r, created.order());
@@ -129,9 +142,11 @@ public class TicketOrderService {
o.setStatus(ShopOrder.PAID);
o.setPaidAt(now);
o.setPaidBy("system");
o.setLastEmail(TicketOrderMailer.PAID);
} else {
o.setStatus(ShopOrder.AWAITING);
o.setHoldUntil(now.plusDays(event.getHoldDays()));
o.setLastEmail(TicketOrderMailer.RECEIVED);
}
o.setConsentNoticeId(r.consentNoticeId());
o.setConsentAt(r.consentAt());
@@ -164,6 +179,7 @@ public class TicketOrderService {
}
views.add(new LineView(t.getName(), t.getPriceSen(), l.quantity()));
}
mailer.send(o, o.getLastEmail()); // delivered after commit
return new Created(o, new Result(o.getReference(), o.getToken(), o.getStatus(), total, o.getHoldUntil(), views,
event.getPaymentInstructions()));
}
@@ -0,0 +1,167 @@
package com.solvway.services.counter.service;
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.EventRepository;
import com.solvway.services.counter.repo.ShopOrderLineRepository;
import com.solvway.services.counter.repo.ShopOrderRepository;
import com.solvway.services.counter.repo.TicketCount;
import com.solvway.services.counter.repo.TicketRepository;
import com.solvway.services.counter.repo.TicketTypeRepository;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.solvway.services.counter.service.TicketTypeService.status;
/** Staff side of ticket orders (add-event-ticket-orders): list, detail, mark paid, cancel, resend. */
@Service
@AllArgsConstructor
public class TicketOrderStaffService {
private static final int PAGE_MAX = 50;
private static final List<String> STATES = List.of(ShopOrder.AWAITING, ShopOrder.PAID, ShopOrder.CANCELLED, ShopOrder.EXPIRED);
private final EventRepository events;
private final TicketTypeService typeService;
private final TicketTypeRepository types;
private final TicketRepository tickets;
private final ShopOrderRepository orders;
private final ShopOrderLineRepository lines;
private final TicketOrderMailer mailer;
public record ListRequest(Long companyId, long eventUuid, String status, String q, int page, int size) {}
public record OrderRow(Long id, String reference, String buyerName, String buyerEmail, long tickets, int totalSen,
String status, LocalDateTime createdAt) {}
public record Page(List<OrderRow> content, long totalElements, int totalPages, int number, int size) {}
public record OrderRef(Long companyId, long eventUuid, long orderId) {}
public record PayRequest(Long companyId, long eventUuid, long orderId, String paymentRef, String doneBy) {}
/** ticketId is used by cancelTicket only. */
public record ActionRequest(Long companyId, long eventUuid, long orderId, Long ticketId, String doneBy) {}
public record TicketView(Long id, String typeName, String status, LocalDateTime cancelledAt, String cancelledBy) {}
public record Detail(ShopOrder order, List<ShopOrderLine> lines, List<TicketView> tickets) {}
public Page list(ListRequest r) {
String state = r.status() == null || r.status().isBlank() ? null : r.status().toUpperCase(Locale.ROOT);
if (state != null && !STATES.contains(state)) throw status(HttpStatus.BAD_REQUEST, "STATUS_INVALID");
String q = r.q() == null || r.q().isBlank() ? null : "%" + r.q().strip().toLowerCase(Locale.ROOT)
.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%";
int size = Math.min(Math.max(r.size(), 1), PAGE_MAX);
var page = orders.search(r.companyId() == null ? -1 : r.companyId(), r.eventUuid(), state, q,
PageRequest.of(Math.max(r.page(), 0), size, Sort.by(Sort.Direction.DESC, "id")));
List<Long> ids = page.getContent().stream().map(ShopOrder::getId).toList();
Map<Long, Long> counts = ids.isEmpty() ? Map.of()
: tickets.activeByOrder(ids).stream().collect(Collectors.toMap(TicketCount::orderId, TicketCount::tickets));
List<OrderRow> rows = page.getContent().stream().map(o -> new OrderRow(o.getId(), o.getReference(), o.getBuyerName(),
o.getBuyerEmail(), counts.getOrDefault(o.getId(), 0L), o.getTotalSen(), o.getStatus(), o.getCreatedAt())).toList();
return new Page(rows, page.getTotalElements(), page.getTotalPages(), page.getNumber(), size);
}
public Detail get(OrderRef r) {
ShopOrder o = order(r.companyId(), r.eventUuid(), r.orderId());
Map<Long, String> typeNames = types.findByEventUuidOrderBySortAscIdAsc(r.eventUuid()).stream()
.collect(Collectors.toMap(TicketType::getId, TicketType::getName));
List<TicketView> views = tickets.findByOrderIdOrderByIdAsc(o.getId()).stream().map(t -> new TicketView(t.getId(),
typeNames.get(t.getTicketTypeId()), t.getStatus(), t.getCancelledAt(), t.getCancelledBy())).toList();
return new Detail(o, lines.findByOrderIdOrderByIdAsc(o.getId()), views);
}
@Transactional
public void markPaid(PayRequest r) {
String ref = r.paymentRef() == null || r.paymentRef().isBlank() ? null : r.paymentRef().strip();
if (ref != null && ref.length() > 100) throw status(HttpStatus.BAD_REQUEST, "PAYMENT_REF_TOO_LONG");
lock(r.companyId(), r.eventUuid()); // an expired order's seats are re-checked against concurrent requests
ShopOrder o = order(r.companyId(), r.eventUuid(), r.orderId());
if (ShopOrder.EXPIRED.equals(o.getStatus())) {
Map<Long, Long> held = typeService.held(r.eventUuid());
Map<Long, TicketType> byId = types.findByEventUuidOrderBySortAscIdAsc(r.eventUuid()).stream()
.collect(Collectors.toMap(TicketType::getId, Function.identity()));
Map<Long, Long> needed = tickets.findByOrderIdOrderByIdAsc(o.getId()).stream().filter(t -> Ticket.ACTIVE.equals(t.getStatus()))
.collect(Collectors.groupingBy(Ticket::getTicketTypeId, Collectors.counting()));
for (var e : needed.entrySet()) {
TicketType t = byId.get(e.getKey());
long left = t == null ? 0 : t.getQuantity() - held.getOrDefault(e.getKey(), 0L);
if (e.getValue() > left) throw status(HttpStatus.CONFLICT, "SEATS_GONE");
}
} else if (!ShopOrder.AWAITING.equals(o.getStatus())) {
throw status(HttpStatus.CONFLICT, "NOT_PAYABLE");
}
o.setStatus(ShopOrder.PAID);
o.setPaidAt(LocalDateTime.now());
o.setPaidBy(r.doneBy());
o.setPaymentRef(ref);
o.setLastEmail(TicketOrderMailer.PAID);
orders.save(o);
mailer.send(o, TicketOrderMailer.PAID);
}
@Transactional
public void cancel(ActionRequest r) {
ShopOrder o = order(r.companyId(), r.eventUuid(), r.orderId());
if (!cancellable(o)) throw status(HttpStatus.CONFLICT, "NOT_CANCELLABLE");
o.setStatus(ShopOrder.CANCELLED);
o.setCancelledAt(LocalDateTime.now());
o.setCancelledBy(r.doneBy());
o.setLastEmail(TicketOrderMailer.CANCELLED);
orders.save(o);
mailer.send(o, TicketOrderMailer.CANCELLED);
}
@Transactional
public void cancelTicket(ActionRequest r) {
ShopOrder o = order(r.companyId(), r.eventUuid(), r.orderId());
List<Ticket> all = tickets.findByOrderIdOrderByIdAsc(o.getId());
Ticket t = all.stream().filter(x -> x.getId().equals(r.ticketId())).findFirst()
.orElseThrow(() -> status(HttpStatus.NOT_FOUND, "TICKET_NOT_FOUND"));
if (!cancellable(o) || !Ticket.ACTIVE.equals(t.getStatus())) throw status(HttpStatus.CONFLICT, "NOT_CANCELLABLE");
if (all.stream().filter(x -> Ticket.ACTIVE.equals(x.getStatus())).count() < 2) throw status(HttpStatus.CONFLICT, "LAST_TICKET");
ShopOrderLine line = lines.findByOrderIdOrderByIdAsc(o.getId()).stream().filter(l -> l.getId().equals(t.getOrderLineId()))
.findFirst().orElseThrow(() -> status(HttpStatus.CONFLICT, "NOT_CANCELLABLE"));
t.setStatus(Ticket.CANCELLED);
t.setCancelledAt(LocalDateTime.now());
t.setCancelledBy(r.doneBy());
tickets.save(t);
line.setQuantity(line.getQuantity() - 1);
lines.save(line);
o.setTotalSen(o.getTotalSen() - line.getUnitPriceSen());
orders.save(o);
}
public void resend(OrderRef r) {
ShopOrder o = order(r.companyId(), r.eventUuid(), r.orderId());
mailer.send(o, o.getLastEmail() == null ? TicketOrderMailer.RECEIVED : o.getLastEmail());
}
private static boolean cancellable(ShopOrder o) {
return ShopOrder.AWAITING.equals(o.getStatus()) || ShopOrder.PAID.equals(o.getStatus());
}
private void lock(Long companyId, long eventUuid) {
events.lockByUuid(eventUuid).filter(e -> companyId != null && companyId.equals(e.getCompanyId()))
.orElseThrow(() -> status(HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND"));
}
private ShopOrder order(Long companyId, long eventUuid, long orderId) {
return orders.findById(orderId)
.filter(o -> companyId != null && companyId == o.getCompanyId() && o.getEventUuid() != null && o.getEventUuid() == eventUuid)
.orElseThrow(() -> status(HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND"));
}
}