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:
1 parent
6dca31510e
commit
687f054acf
14 files changed
+844
-4
No files matched your search
@@ -55,7 +55,7 @@ Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-04
|
||||
- **Headcount:** it adds `heldTickets`, and the invite registration's capacity check counts held tickets.
|
||||
- Scope: `solvway-services-counter/src/**`
|
||||
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
|
||||
- [ ] 2.3 Staff order actions, the expiry job and emails.
|
||||
- [x] 2.3 Staff order actions, the expiry job and emails.
|
||||
- Depends on: 2.2
|
||||
- Tests first:
|
||||
- **`list`:** filter, search and paging.
|
||||
|
||||
+40
-1
@@ -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);
|
||||
}
|
||||
}
|
||||
+25
@@ -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);
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.solvway.services.counter.repo;
|
||||
|
||||
/** Active tickets of one order. */
|
||||
public record TicketCount(Long orderId, Long tickets) {}
|
||||
+5
@@ -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);
|
||||
}
|
||||
+44
@@ -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;
|
||||
}
|
||||
}
|
||||
+131
@@ -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));
|
||||
}
|
||||
}
|
||||
+16
@@ -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()));
|
||||
}
|
||||
|
||||
+167
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -5,3 +5,6 @@ spring:
|
||||
project-id: co-lite-local
|
||||
pubsub:
|
||||
emulator-host: pubsub:8085
|
||||
|
||||
app:
|
||||
admin-portal-base-url: ${ADMIN_PORTAL_BASE_URL:http://localhost:3001}
|
||||
@@ -57,4 +57,6 @@ invoiceConfirmationEmail:
|
||||
BN : EN
|
||||
# Indicate TEST Site
|
||||
test:
|
||||
environment: false
|
||||
environment: false
|
||||
app:
|
||||
admin-portal-base-url: ${ADMIN_PORTAL_BASE_URL}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.core.model.Email;
|
||||
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 com.solvway.services.counter.repo.ShopOrderRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** add-event-ticket-orders: the hold expiry job and the order emails (spec: Order States, Order Emails). */
|
||||
class TicketOrderExpiryAndMailTest {
|
||||
private final ShopOrderRepository orders = mock(ShopOrderRepository.class);
|
||||
private final ShopOrderLineRepository lines = mock(ShopOrderLineRepository.class);
|
||||
private final EventRepository events = mock(EventRepository.class);
|
||||
private final EmailService emailService = mock(EmailService.class);
|
||||
private final TicketOrderMailer mailer = new TicketOrderMailer(emailService, events, lines, "https://co-lite.example");
|
||||
private ShopOrder order;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
order = new ShopOrder();
|
||||
order.setId(300L);
|
||||
order.setCompanyId(7L);
|
||||
order.setEventUuid(900L);
|
||||
order.setReference("T-7K3M9Q");
|
||||
order.setToken("abcdefghijklmnopqrstuv");
|
||||
order.setBuyerName("Aisyah <b>");
|
||||
order.setBuyerEmail("a@example.test");
|
||||
order.setStatus(ShopOrder.AWAITING);
|
||||
order.setTotalSen(100000);
|
||||
order.setHoldUntil(LocalDateTime.of(2026, 12, 7, 10, 0));
|
||||
Event e = new Event();
|
||||
e.setName("KL Hotel Tech Day");
|
||||
e.setLocation("KLCC");
|
||||
e.setPaymentInstructions("Maybank 5140\nRef: your order number");
|
||||
when(events.findByUuid(900L)).thenReturn(Optional.of(e));
|
||||
ShopOrderLine l = new ShopOrderLine();
|
||||
l.setName("General");
|
||||
l.setUnitPriceSen(25000);
|
||||
l.setQuantity(4);
|
||||
when(lines.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(l));
|
||||
when(emailService.send(any())).thenReturn(Optional.of(new Email()));
|
||||
}
|
||||
|
||||
private Email sent() {
|
||||
ArgumentCaptor<Email> e = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService).send(e.capture());
|
||||
return e.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theReceivedEmailHasInstructionsHoldAndTheOrderLinkWithValuesEscaped() {
|
||||
mailer.send(order, "RECEIVED");
|
||||
Email e = sent();
|
||||
assertThat(e.getCompanyId()).isEqualTo(7L);
|
||||
assertThat(e.getRecipients()).extracting(r -> r.getRecipient()).containsExactly("a@example.test");
|
||||
assertThat(e.getSubject()).contains("T-7K3M9Q");
|
||||
assertThat(e.getBody()).contains("https://co-lite.example/o/abcdefghijklmnopqrstuv");
|
||||
assertThat(e.getBody()).contains("Maybank 5140<br>Ref: your order number");
|
||||
assertThat(e.getBody()).contains("RM 1,000.00").contains("General").contains("KL Hotel Tech Day");
|
||||
assertThat(e.getBody()).contains("Aisyah <b>").doesNotContain("Aisyah <b>");
|
||||
assertThat(e.getBody()).contains("Bahasa Malaysia");
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePaidEmailConfirmsWithoutInstructions() {
|
||||
mailer.send(order, "PAID");
|
||||
Email e = sent();
|
||||
assertThat(e.getSubject()).contains("confirmed");
|
||||
assertThat(e.getBody()).doesNotContain("Maybank");
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredAndCancelledEmailsSayWhatHappened() {
|
||||
mailer.send(order, "EXPIRED");
|
||||
mailer.send(order, "CANCELLED");
|
||||
ArgumentCaptor<Email> e = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService, times(2)).send(e.capture());
|
||||
assertThat(e.getAllValues().get(0).getSubject()).contains("expired");
|
||||
assertThat(e.getAllValues().get(1).getSubject()).contains("cancelled");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedSendIsSwallowed() {
|
||||
when(emailService.send(any())).thenThrow(new IllegalStateException("smtp"));
|
||||
mailer.send(order, "RECEIVED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theJobExpiresDueOrdersAndEmailsOnlyThoseItChanged() {
|
||||
TicketOrderMailer jobMailer = mock(TicketOrderMailer.class);
|
||||
TicketOrderExpiryJob job = new TicketOrderExpiryJob(orders, jobMailer);
|
||||
ShopOrder raced = new ShopOrder();
|
||||
raced.setId(301L);
|
||||
when(orders.findTop100ByStatusAndHoldUntilBeforeOrderByIdAsc(eq("AWAITING"), any())).thenReturn(List.of(order, raced), List.of());
|
||||
when(orders.expireIfAwaiting(eq(300L), any())).thenReturn(1);
|
||||
when(orders.expireIfAwaiting(eq(301L), any())).thenReturn(0); // paid meanwhile: the conditional update changes nothing
|
||||
assertThat(job.run()).isEqualTo(1);
|
||||
verify(jobMailer).send(order, "EXPIRED");
|
||||
verify(jobMailer, never()).send(raced, "EXPIRED");
|
||||
assertThat(order.getStatus()).isEqualTo("EXPIRED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theJobDoesNothingWhenNoneAreDue() {
|
||||
TicketOrderMailer jobMailer = mock(TicketOrderMailer.class);
|
||||
when(orders.findTop100ByStatusAndHoldUntilBeforeOrderByIdAsc(eq("AWAITING"), any())).thenReturn(List.of());
|
||||
assertThat(new TicketOrderExpiryJob(orders, jobMailer).run()).isZero();
|
||||
verify(orders, never()).expireIfAwaiting(anyLong(), any());
|
||||
}
|
||||
}
|
||||
+38
-1
@@ -59,6 +59,7 @@ class TicketOrderRequestTest {
|
||||
@Mock private EventGuestRepository guests;
|
||||
@Mock private EventLeadRepository eventLeads;
|
||||
@Mock private RegistrationService registration;
|
||||
@Mock private TicketOrderMailer mailer;
|
||||
|
||||
private TicketOrderService service;
|
||||
private Event event;
|
||||
@@ -69,7 +70,7 @@ class TicketOrderRequestTest {
|
||||
void setUp() {
|
||||
TicketTypeService typeService = new TicketTypeService(events, types, tickets, lines);
|
||||
service = new TicketOrderService(new TransactionTemplate(mock(PlatformTransactionManager.class)), events, typeService, types,
|
||||
orders, lines, tickets, guests, eventLeads, registration);
|
||||
orders, lines, tickets, guests, eventLeads, registration, mailer);
|
||||
event = new Event();
|
||||
event.setUuid(EVENT);
|
||||
event.setCompanyId(COMPANY);
|
||||
@@ -138,6 +139,7 @@ class TicketOrderRequestTest {
|
||||
});
|
||||
verify(orders, never()).saveAndFlush(any());
|
||||
verify(registration, never()).register(any());
|
||||
verify(mailer, never()).send(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -163,6 +165,8 @@ class TicketOrderRequestTest {
|
||||
assertThat(o.getValue().getBuyerEmail()).isEqualTo("a@example.test");
|
||||
assertThat(o.getValue().getConsentNoticeId()).isEqualTo(77L);
|
||||
assertThat(o.getValue().getUtmCampaign()).isEqualTo("launch");
|
||||
assertThat(o.getValue().getLastEmail()).isEqualTo("RECEIVED");
|
||||
verify(mailer).send(o.getValue(), "RECEIVED");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -184,6 +188,39 @@ class TicketOrderRequestTest {
|
||||
verify(orders).saveAndFlush(o.capture());
|
||||
assertThat(o.getValue().getPaidBy()).isEqualTo("system");
|
||||
assertThat(o.getValue().getPaidAt()).isNotNull();
|
||||
assertThat(o.getValue().getLastEmail()).isEqualTo("PAID");
|
||||
verify(mailer).send(o.getValue(), "PAID");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOrderPageShowsTheOrderByItsToken() {
|
||||
ShopOrder o = new ShopOrder();
|
||||
o.setId(300L);
|
||||
o.setCompanyId(COMPANY);
|
||||
o.setEventUuid(EVENT);
|
||||
o.setReference("T-7K3M9Q");
|
||||
o.setStatus(ShopOrder.AWAITING);
|
||||
o.setBuyerName("Aisyah");
|
||||
o.setBuyerEmail("a@example.test");
|
||||
o.setTotalSen(50000);
|
||||
when(orders.findByToken("abcdefghijklmnopqrstuv")).thenReturn(Optional.of(o));
|
||||
ShopOrderLine l = new ShopOrderLine();
|
||||
l.setName("General");
|
||||
l.setUnitPriceSen(25000);
|
||||
l.setQuantity(2);
|
||||
when(lines.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(l));
|
||||
TicketOrderService.OrderView v = service.byToken("abcdefghijklmnopqrstuv");
|
||||
assertThat(v.reference()).isEqualTo("T-7K3M9Q");
|
||||
assertThat(v.buyerName()).isEqualTo("Aisyah");
|
||||
assertThat(v.eventUuid()).isEqualTo(EVENT);
|
||||
assertThat(v.lines()).extracting(TicketOrderService.LineView::quantity).containsExactly(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownTokenIsNotFound() {
|
||||
when(orders.findByToken("zzzzzzzzzzzzzzzzzzzzzz")).thenReturn(Optional.empty());
|
||||
assertThatThrownBy(() -> service.byToken("zzzzzzzzzzzzzzzzzzzzzz")).isInstanceOfSatisfying(ResponseStatusException.class,
|
||||
ex -> assertThat(ex.getStatusCode().value()).isEqualTo(404));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
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.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.TicketHeld;
|
||||
import com.solvway.services.counter.repo.TicketRepository;
|
||||
import com.solvway.services.counter.repo.TicketTypeRepository;
|
||||
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.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
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.anyCollection;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** add-event-ticket-orders: staff order screens and actions (spec: Staff Order Screens, Staff Order Actions). */
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class TicketOrderStaffServiceTest {
|
||||
private static final long COMPANY = 7L;
|
||||
private static final long EVENT = 900L;
|
||||
|
||||
@Mock private EventRepository events;
|
||||
@Mock private TicketTypeRepository types;
|
||||
@Mock private TicketRepository tickets;
|
||||
@Mock private ShopOrderRepository orders;
|
||||
@Mock private ShopOrderLineRepository lines;
|
||||
@Mock private TicketOrderMailer mailer;
|
||||
|
||||
private TicketOrderStaffService service;
|
||||
private ShopOrder order;
|
||||
private Ticket t1, t2, t3;
|
||||
private ShopOrderLine line;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new TicketOrderStaffService(events, new TicketTypeService(events, types, tickets, lines), types, tickets, orders, lines, mailer);
|
||||
Event event = new Event();
|
||||
event.setUuid(EVENT);
|
||||
event.setCompanyId(COMPANY);
|
||||
lenient().when(events.lockByUuid(EVENT)).thenReturn(Optional.of(event));
|
||||
order = new ShopOrder();
|
||||
order.setId(300L);
|
||||
order.setCompanyId(COMPANY);
|
||||
order.setEventUuid(EVENT);
|
||||
order.setReference("T-7K3M9Q");
|
||||
order.setStatus(ShopOrder.AWAITING);
|
||||
order.setTotalSen(75000);
|
||||
lenient().when(orders.findById(300L)).thenReturn(Optional.of(order));
|
||||
lenient().when(orders.save(any(ShopOrder.class))).thenAnswer(i -> i.getArgument(0));
|
||||
line = new ShopOrderLine();
|
||||
line.setId(400L);
|
||||
line.setOrderId(300L);
|
||||
line.setItemId(2L);
|
||||
line.setName("General");
|
||||
line.setUnitPriceSen(25000);
|
||||
line.setQuantity(3);
|
||||
lenient().when(lines.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(line));
|
||||
t1 = ticket(1L);
|
||||
t2 = ticket(2L);
|
||||
t3 = ticket(3L);
|
||||
lenient().when(tickets.findByOrderIdOrderByIdAsc(300L)).thenReturn(List.of(t1, t2, t3));
|
||||
TicketType general = new TicketType();
|
||||
general.setId(2L);
|
||||
general.setEventUuid(EVENT);
|
||||
general.setName("General");
|
||||
general.setQuantity(10);
|
||||
general.setEnabled(true);
|
||||
lenient().when(types.findByEventUuidOrderBySortAscIdAsc(EVENT)).thenReturn(List.of(general));
|
||||
}
|
||||
|
||||
private static Ticket ticket(long id) {
|
||||
Ticket t = new Ticket();
|
||||
t.setId(id);
|
||||
t.setOrderId(300L);
|
||||
t.setOrderLineId(400L);
|
||||
t.setTicketTypeId(2L);
|
||||
t.setEventUuid(EVENT);
|
||||
t.setCompanyId(COMPANY);
|
||||
return t;
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void listsOrdersNewestFirstWithTicketCountsAndFilters() {
|
||||
when(orders.search(eq(COMPANY), eq(EVENT), eq("AWAITING"), eq("%aisyah%"), any(Pageable.class)))
|
||||
.thenReturn(new PageImpl<>(List.of(order), PageRequest.of(0, 50), 1));
|
||||
when(tickets.activeByOrder(anyCollection())).thenReturn(List.of(new TicketCount(300L, 3L)));
|
||||
TicketOrderStaffService.Page page = service.list(new TicketOrderStaffService.ListRequest(COMPANY, EVENT, "AWAITING", " Aisyah ", 0, 200));
|
||||
assertThat(page.totalElements()).isEqualTo(1);
|
||||
assertThat(page.size()).isEqualTo(50);
|
||||
assertThat(page.content().get(0).tickets()).isEqualTo(3);
|
||||
assertThat(page.content().get(0).reference()).isEqualTo("T-7K3M9Q");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptySearchIsNoFilter() {
|
||||
when(orders.search(eq(COMPANY), eq(EVENT), isNull(), isNull(), any(Pageable.class))).thenReturn(new PageImpl<>(List.of()));
|
||||
assertThat(service.list(new TicketOrderStaffService.ListRequest(COMPANY, EVENT, "", " ", 0, 50)).content()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherCompanysOrderIsNotFound() {
|
||||
assertStatus(() -> service.get(new TicketOrderStaffService.OrderRef(8L, EVENT, 300L)), 404, "ORDER_NOT_FOUND");
|
||||
assertStatus(() -> service.get(new TicketOrderStaffService.OrderRef(COMPANY, 901L, 300L)), 404, "ORDER_NOT_FOUND");
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailHasLinesAndTickets() {
|
||||
TicketOrderStaffService.Detail d = service.get(new TicketOrderStaffService.OrderRef(COMPANY, EVENT, 300L));
|
||||
assertThat(d.lines()).hasSize(1);
|
||||
assertThat(d.tickets()).extracting(TicketOrderStaffService.TicketView::typeName).containsOnly("General");
|
||||
}
|
||||
|
||||
@Test
|
||||
void marksAnAwaitingOrderPaidWithItsReference() {
|
||||
service.markPaid(new TicketOrderStaffService.PayRequest(COMPANY, EVENT, 300L, " MBB 0412 883 ", "finance1"));
|
||||
assertThat(order.getStatus()).isEqualTo("PAID");
|
||||
assertThat(order.getPaymentRef()).isEqualTo("MBB 0412 883");
|
||||
assertThat(order.getPaidBy()).isEqualTo("finance1");
|
||||
assertThat(order.getPaidAt()).isNotNull();
|
||||
assertThat(order.getLastEmail()).isEqualTo("PAID");
|
||||
verify(events).lockByUuid(EVENT);
|
||||
verify(mailer).send(order, "PAID");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredOrderIsPaidOnlyWhileItsSeatsAreFree() {
|
||||
order.setStatus(ShopOrder.EXPIRED);
|
||||
when(tickets.heldByType(EVENT)).thenReturn(List.of(new TicketHeld(2L, 8L)));
|
||||
assertStatus(() -> service.markPaid(new TicketOrderStaffService.PayRequest(COMPANY, EVENT, 300L, null, "x")), 409, "SEATS_GONE");
|
||||
assertThat(order.getStatus()).isEqualTo("EXPIRED");
|
||||
when(tickets.heldByType(EVENT)).thenReturn(List.of(new TicketHeld(2L, 7L)));
|
||||
service.markPaid(new TicketOrderStaffService.PayRequest(COMPANY, EVENT, 300L, null, "x"));
|
||||
assertThat(order.getStatus()).isEqualTo("PAID");
|
||||
}
|
||||
|
||||
@Test
|
||||
void paidOrCancelledOrdersCannotBePaid() {
|
||||
order.setStatus(ShopOrder.PAID);
|
||||
assertStatus(() -> service.markPaid(new TicketOrderStaffService.PayRequest(COMPANY, EVENT, 300L, null, "x")), 409, "NOT_PAYABLE");
|
||||
order.setStatus(ShopOrder.CANCELLED);
|
||||
assertStatus(() -> service.markPaid(new TicketOrderStaffService.PayRequest(COMPANY, EVENT, 300L, null, "x")), 409, "NOT_PAYABLE");
|
||||
verify(mailer, never()).send(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPaymentReferenceIsAtMostOneHundredCharacters() {
|
||||
assertStatus(() -> service.markPaid(new TicketOrderStaffService.PayRequest(COMPANY, EVENT, 300L, "x".repeat(101), "x")), 400,
|
||||
"PAYMENT_REF_TOO_LONG");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancelsAnOrderAndEmailsTheBuyer() {
|
||||
service.cancel(new TicketOrderStaffService.ActionRequest(COMPANY, EVENT, 300L, null, "admin"));
|
||||
assertThat(order.getStatus()).isEqualTo("CANCELLED");
|
||||
assertThat(order.getCancelledBy()).isEqualTo("admin");
|
||||
verify(mailer).send(order, "CANCELLED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredOrderCannotBeCancelled() {
|
||||
order.setStatus(ShopOrder.EXPIRED);
|
||||
assertStatus(() -> service.cancel(new TicketOrderStaffService.ActionRequest(COMPANY, EVENT, 300L, null, "admin")), 409, "NOT_CANCELLABLE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancellingOneTicketLowersTheTotal() {
|
||||
service.cancelTicket(new TicketOrderStaffService.ActionRequest(COMPANY, EVENT, 300L, 2L, "admin"));
|
||||
assertThat(t2.getStatus()).isEqualTo("CANCELLED");
|
||||
assertThat(t2.getCancelledBy()).isEqualTo("admin");
|
||||
assertThat(order.getTotalSen()).isEqualTo(50000);
|
||||
ArgumentCaptor<ShopOrderLine> l = ArgumentCaptor.forClass(ShopOrderLine.class);
|
||||
verify(lines).save(l.capture());
|
||||
assertThat(l.getValue().getQuantity()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLastTicketCannotBeCancelledAlone() {
|
||||
t1.setStatus(Ticket.CANCELLED);
|
||||
t2.setStatus(Ticket.CANCELLED);
|
||||
assertStatus(() -> service.cancelTicket(new TicketOrderStaffService.ActionRequest(COMPANY, EVENT, 300L, 3L, "admin")), 409, "LAST_TICKET");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownTicketIsNotFound() {
|
||||
assertStatus(() -> service.cancelTicket(new TicketOrderStaffService.ActionRequest(COMPANY, EVENT, 300L, 99L, "admin")), 404, "TICKET_NOT_FOUND");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resendSendsTheLatestEmailKind() {
|
||||
order.setLastEmail("PAID");
|
||||
service.resend(new TicketOrderStaffService.OrderRef(COMPANY, EVENT, 300L));
|
||||
verify(mailer).send(order, "PAID");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resendWithoutAnEarlierEmailSendsTheReceivedOne() {
|
||||
service.resend(new TicketOrderStaffService.OrderRef(COMPANY, EVENT, 300L));
|
||||
verify(mailer).send(order, "RECEIVED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void paidAtIsNow() {
|
||||
service.markPaid(new TicketOrderStaffService.PayRequest(COMPANY, EVENT, 300L, null, "x"));
|
||||
assertThat(order.getPaidAt()).isAfter(LocalDateTime.now().minusMinutes(1));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user