feat(tickets): public ticket request, order page and gateway paths

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:53:54 +08:00
1 parent a18ca0db71
commit d25641e139
8 files changed
+569 -2

No files matched your search

@@ -108,7 +108,7 @@ Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-04
- **Event GET:** it returns `ticketsEnabled`.
- Scope: `solvway-mobile-api/src/**`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
- [ ] 3.2 Public TICKETS page data, request and order page, and the gateway paths.
- [x] 3.2 Public TICKETS page data, request and order page, and the gateway paths.
- Depends on: 2.4, 3.1
- Tests first:
- **Page data:** the page GET adds `tickets` or `closed` to a TICKETS block.
@@ -60,6 +60,10 @@ public class JWTAuthFilter implements GlobalFilter, Ordered {
publicPath(HttpMethod.GET, "/counter/cmsPage/findPublished/\\d+/[A-Za-z0-9-]{1,80}"),
publicPath(HttpMethod.GET, "/counter/pageImage/\\d+"),
publicPath(HttpMethod.GET, "/company/branding/[A-Za-z0-9-]{2,20}"),
// Ticket orders (add-event-ticket-orders): a request, an order by its link token, and the on-sale types. Staff calls need a token.
publicPath(HttpMethod.POST, "/counter/ticketOrder/request"),
publicPath(HttpMethod.GET, "/counter/ticketOrder/byToken/[A-Za-z0-9_-]{22}"),
publicPath(HttpMethod.GET, "/counter/ticketType/onSale/\\d{1,19}"),
// Password hint on public password screens: switched-on rule names and numbers only, no user data
publicPath(HttpMethod.GET, "/passwordRule/adminActive"),
// WhatsApp webhook forward from mobile-api: no user token; the service re-verifies Meta's signature itself
@@ -0,0 +1,84 @@
package com.solvway.gateway.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.gateway.model.AuthAppKey;
import com.solvway.gateway.model.AuthAppKeyMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.test.util.ReflectionTestUtils;
import reactor.core.publisher.Mono;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
/** add-event-ticket-orders: a ticket request, an order by its link token and the on-sale ticket types are open; staff ticket calls stay closed. */
class JWTAuthFilterTicketsPathTest {
private static final String KEY = "gateway-test-key";
private JWTAuthFilter filter;
@BeforeEach
void setUp() throws Exception {
AuthAppKey key = new ObjectMapper().readValue(
"{\"key\":\"" + KEY + "\",\"type\":\"BO\",\"ipList\":[\"0.0.0.0/0\"],\"allowList\":[\"/\"]}",
AuthAppKey.class);
AuthAppKeyMap map = new AuthAppKeyMap();
map.add(KEY, key);
filter = new JWTAuthFilter();
ReflectionTestUtils.setField(filter, "authAppKeyMap", map);
}
private MockServerWebExchange call(HttpMethod method, String path) {
return MockServerWebExchange.from(MockServerHttpRequest.method(method, path)
.header("api-key", KEY)
.remoteAddress(new InetSocketAddress("127.0.0.1", 40000)));
}
private boolean passes(MockServerWebExchange exchange) {
AtomicBoolean called = new AtomicBoolean(false);
GatewayFilterChain chain = ex -> {
called.set(true);
return Mono.empty();
};
filter.filter(exchange, chain).block();
return called.get();
}
@Test
void publicTicketCallsNeedNoUserToken() {
for (String[] c : new String[][] {
{"POST", "/counter/ticketOrder/request"},
{"GET", "/counter/ticketOrder/byToken/abcdefghijklmnopqrstu_"},
{"GET", "/counter/ticketType/onSale/3312726793093644288"} }) {
assertThat(passes(call(HttpMethod.valueOf(c[0]), c[1]))).as(c[0] + " " + c[1]).isTrue();
}
}
@Test
void everythingElseAboutTicketsNeedsAUserToken() {
for (String[] c : new String[][] {
{"GET", "/counter/ticketOrder/request"},
{"POST", "/counter/ticketOrder/request/x"},
{"GET", "/counter/ticketOrder/byToken/short"},
{"GET", "/counter/ticketOrder/byToken/abcdefghijklmnopqrstuvw"},
{"POST", "/counter/ticketOrder/byToken/abcdefghijklmnopqrstu_"},
{"GET", "/counter/ticketType/onSale/x"},
{"GET", "/counter/ticketType/onSale/12345678901234567890"},
{"POST", "/counter/ticketType/list"},
{"POST", "/counter/ticketType/settings"},
{"POST", "/counter/ticketOrder/list"},
{"POST", "/counter/ticketOrder/markPaid"} }) {
MockServerWebExchange exchange = call(HttpMethod.valueOf(c[0]), c[1]);
assertThat(passes(exchange)).as(c[0] + " " + c[1]).isFalse();
assertThat(exchange.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED);
}
}
}
@@ -57,6 +57,9 @@ public class RestApiCounterServiceConstants {
public static final String API_REST_COUNTER_TICKET_ORDER_CANCEL = "/counter/ticketOrder/cancel";
public static final String API_REST_COUNTER_TICKET_ORDER_CANCEL_TICKET = "/counter/ticketOrder/cancelTicket";
public static final String API_REST_COUNTER_TICKET_ORDER_RESEND = "/counter/ticketOrder/resend";
public static final String API_REST_COUNTER_TICKET_TYPE_ON_SALE = "/counter/ticketType/onSale/{eventUuid}";
public static final String API_REST_COUNTER_TICKET_ORDER_REQUEST = "/counter/ticketOrder/request";
public static final String API_REST_COUNTER_TICKET_ORDER_BY_TOKEN = "/counter/ticketOrder/byToken/{token}";
public static final String API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID="/counter/eventSalesperson/findByEventUuid/{eventUuid}";
public static final String API_REST_COUNTER_EVENT_SALESPERSON_REPLACE="/counter/eventSalesperson/replace";
public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}";
@@ -2,6 +2,7 @@ package com.solvway.mobile.api.controller.publicapi;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.PublicPageFormRequest;
import com.solvway.mobile.api.dto.PublicTicketRequest;
import com.solvway.mobile.api.service.PublicPageService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
@@ -32,6 +33,19 @@ public class PublicPageController {
return ResponseEntity.ok(pages.submit(company, slug, block, request));
}
@AppAuth(skipValidate = true)
@PostMapping("/api/public/pages/{company}/{slug}/tickets/{block}")
public ResponseEntity<Map<String, Object>> tickets(@PathVariable String company, @PathVariable String slug,
@PathVariable int block, @RequestBody PublicTicketRequest request) {
return ResponseEntity.ok(pages.tickets(company, slug, block, request));
}
@AppAuth(skipValidate = true)
@GetMapping("/api/public/orders/{token}")
public ResponseEntity<Map<String, Object>> order(@PathVariable String token) {
return ResponseEntity.ok(pages.order(token));
}
@AppAuth(skipValidate = true)
@GetMapping("/api/public/page-images/{id}")
public ResponseEntity<byte[]> image(@PathVariable long id) {
@@ -0,0 +1,10 @@
package com.solvway.mobile.api.dto;
import java.util.List;
/** A visitor's ticket request from a TICKETS block (add-event-ticket-orders). {@code website} is the honeypot. */
public record PublicTicketRequest(List<Line> lines, String name, String mobile, String email, String companyName, Boolean consent,
String website, String utmSource, String utmMedium, String utmCampaign) {
public record Line(Long ticketTypeId, Integer quantity) {}
}
@@ -4,6 +4,8 @@ import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.dto.PublicPageFormRequest;
import com.solvway.mobile.api.dto.PublicRegistrationRequest;
import com.solvway.mobile.api.dto.PublicTicketRequest;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
@@ -13,8 +15,13 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -26,6 +33,7 @@ import java.util.regex.Pattern;
* Public landing pages: a published page with its company's branding, and its form blocks' sign-ups.
* A form block registers under the QR rules (PublicRegistrationService): same event checks, form validation,
* honeypot and abuse limits, with source WEB, no salesperson, the page address and the UTM tags.
* add-event-ticket-orders: a TICKETS block's types and ticket requests follow the same rules, and an order's link shows the order.
*/
@Service
@RequiredArgsConstructor
@@ -35,7 +43,11 @@ public class PublicPageService {
private static final Pattern SLUG = Pattern.compile("[A-Za-z0-9-]{1,80}");
private static final int LOAD_LIMIT = 300;
private static final int SUBMIT_LIMIT = 60;
private static final int ORDER_LOAD_LIMIT = 120;
private static final String TOO_MANY_SUBMITS = "Too many registrations from this device. Try again later.";
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<CompanyEvent> EVENT = new ParameterizedTypeReference<>() {};
private static final ObjectMapper JSON = new ObjectMapper();
private final RestTemplateCustomUtil rest;
private final PublicRegistrationService registration;
@@ -52,6 +64,10 @@ public class PublicPageService {
PublicRegistrationService.Open o = open(f.companyId(), block);
if (o == null) block.put("closed", true);
else block.put("form", registration.eventView(o));
} else if ("TICKETS".equals(block.get("type"))) {
Map<String, Object> t = ticketsView(f.companyId(), block);
if (t == null) block.put("closed", true);
else block.put("tickets", t);
}
blocks.add(block);
}
@@ -84,7 +100,7 @@ public class PublicPageService {
PublicRegistrationRequest form = r.registration();
if (PublicRegistrationService.honeypot(form)) return done; // look like success, store nothing
registration.limit("reg:submit:" + o.event().getUuid() + ":" + PublicRegistrationService.ip(), SUBMIT_LIMIT,
"Too many registrations from this device. Try again later.");
TOO_MANY_SUBMITS);
Map<String, Object> body = registration.form(o, form);
body.put("eventUuid", o.event().getUuid());
body.put("salespersonUserId", null);
@@ -97,6 +113,160 @@ public class PublicPageService {
return done;
}
/** A TICKETS block's event and on-sale types, or null when the event no longer takes ticket requests. */
private Map<String, Object> ticketsView(long companyId, Map<String, Object> block) {
PublicRegistrationService.Open o = open(companyId, block);
if (o == null) return null;
Map<String, Object> sale = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_TYPE_ON_SALE), MAP, o.event().getUuid()).getBody());
if (sale == null || !Boolean.TRUE.equals(sale.get("ticketsOpen"))) return null;
CompanyEvent e = o.event();
Map<String, Object> out = new LinkedHashMap<>();
out.put("eventName", e.getName());
out.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
out.put("endDate", e.getDateEnd().toLocalDate().toString());
out.put("location", e.getLocation());
out.put("notice", Map.of("id", o.notice().get("id"), "textEn", String.valueOf(o.notice().get("textEn")),
"textMs", String.valueOf(o.notice().get("textMs"))));
out.put("types", sale.get("types") instanceof List<?> l ? l : List.of());
return out;
}
/** A ticket request from a TICKETS block: QR limits and honeypot, inputs normalised here, seats and prices checked by the counter. */
public Map<String, Object> tickets(String companyCode, String slug, int blockIndex, PublicTicketRequest r) {
registration.limit("page:load:" + PublicRegistrationService.ip(), LOAD_LIMIT, "Too many requests from this device. Try again later.");
Found f = find(companyCode, slug);
List<?> blocks = blocks(f.page());
if (blockIndex < 0 || blockIndex >= blocks.size() || !"TICKETS".equals(((Map<?, ?>) blocks.get(blockIndex)).get("type"))) {
throw notFound();
}
PublicRegistrationService.Open o = open(f.companyId(), (Map<String, Object>) blocks.get(blockIndex));
if (o == null) throw new CodedResponseStatusException(HttpStatus.CONFLICT, "Ticket sales are closed.", "TICKETS_CLOSED");
Map<String, Object> done = PublicRegistrationService.done(o.event());
if (r == null || r.website() != null && !r.website().isBlank()) return done; // look like success, store nothing
registration.limit("reg:submit:" + o.event().getUuid() + ":" + PublicRegistrationService.ip(), SUBMIT_LIMIT, TOO_MANY_SUBMITS);
String name = AdminEventLeadService.trimmed(r.name());
String email = AdminEventLeadService.email(r.email());
List<String> missing = new ArrayList<>();
if (name == null) missing.add("name");
if (email == null) missing.add("email");
if (!missing.isEmpty()) throw AdminEventLeadService.required(missing);
AdminEventLeadService.maxLength("name", name, 100);
AdminEventLeadService.maxLength("email", email, 254);
String mobile = AdminEventLeadService.mobile(r.mobile());
String companyName = AdminEventLeadService.maxLength("companyName", AdminEventLeadService.trimmed(r.companyName()), 150);
if (!Boolean.TRUE.equals(r.consent())) {
throw AdminEventLeadService.error(HttpStatus.BAD_REQUEST, "Please agree to the privacy notice", "CONSENT_REQUIRED", "consent");
}
List<Map<String, Object>> lines = new ArrayList<>();
for (PublicTicketRequest.Line l : r.lines() == null ? List.<PublicTicketRequest.Line>of() : r.lines()) {
Map<String, Object> line = new LinkedHashMap<>();
line.put("ticketTypeId", l == null ? null : l.ticketTypeId());
line.put("quantity", l == null ? null : l.quantity());
lines.add(line);
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", o.event().getCompanyId());
body.put("eventUuid", o.event().getUuid());
body.put("lines", lines);
body.put("buyerName", name);
body.put("buyerEmail", email);
body.put("buyerMobileE164", mobile);
body.put("buyerCompany", companyName);
body.put("consentNoticeId", o.notice().get("id"));
body.put("consentAt", LocalDateTime.now(PublicRegistrationService.MALAYSIA).toString());
body.put("pagePath", "/p/" + f.company().get("code") + "/" + f.page().get("slug"));
body.put("utmSource", r.utmSource());
body.put("utmMedium", r.utmMedium());
body.put("utmCampaign", r.utmCampaign());
Map<String, Object> result;
try {
result = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_ORDER_REQUEST), MAP, body).getBody();
} catch (HttpClientErrorException e) {
throw ticketRefusal(e, o);
}
Map<String, Object> out = new LinkedHashMap<>(result == null ? Map.of() : result);
if (!"AWAITING".equals(out.get("status"))) out.remove("paymentInstructions"); // a free order is confirmed at once
out.put("eventName", o.event().getName());
return out;
}
/** The counter's refusal ("CODE" or "CODE|typeId|left" or "CODE|left") as the message a visitor reads. */
private CodedResponseStatusException ticketRefusal(HttpClientErrorException e, PublicRegistrationService.Open o) {
String detail = "";
try {
JsonNode n = JSON.readTree(e.getResponseBodyAsString());
detail = n.path("detail").asText("");
} catch (Exception ignored) {
// not a ProblemDetail
}
String[] p = detail.split("\\|");
HttpStatus status = HttpStatus.valueOf(e.getStatusCode().value());
CodedResponseStatusException out = switch (p[0]) {
case "TYPE_UNAVAILABLE" -> {
long id = p.length > 1 ? Long.parseLong(p[1]) : 0;
long left = p.length > 2 ? Long.parseLong(p[2]) : 0;
String name = typeName(o.event().getUuid(), id);
CodedResponseStatusException x = new CodedResponseStatusException(status, left == 0 ? name + " is no longer available."
: name + " has only " + left + (left == 1 ? " ticket left." : " tickets left."), "TYPE_UNAVAILABLE");
x.getBody().setProperty("details", Map.of("ticketTypeId", id, "left", left));
yield x;
}
case "EVENT_FULL" -> {
long left = p.length > 1 ? Long.parseLong(p[1]) : 0;
CodedResponseStatusException x = new CodedResponseStatusException(status, left == 0 ? "This event is full."
: "Only " + left + (left == 1 ? " seat is" : " seats are") + " left for this event.", "EVENT_FULL");
x.getBody().setProperty("details", Map.of("left", left));
yield x;
}
case "TOO_MANY_AWAITING" -> new CodedResponseStatusException(status, "You already have orders awaiting payment for this event.", p[0]);
case "BAD_QUANTITY" -> new CodedResponseStatusException(status, "Choose from 1 to 10 tickets.", p[0]);
case "TICKETS_CLOSED", "EVENT_NOT_FOUND" -> new CodedResponseStatusException(HttpStatus.CONFLICT, "Ticket sales are closed.", "TICKETS_CLOSED");
default -> new CodedResponseStatusException(status, "Your request could not be completed.", p[0].isEmpty() ? "REFUSED" : p[0]);
};
return out;
}
private String typeName(long eventUuid, long typeId) {
Map<String, Object> sale = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_TYPE_ON_SALE), MAP, eventUuid).getBody());
if (sale != null && sale.get("types") instanceof List<?> types) {
for (Object t : types) {
if (t instanceof Map<?, ?> m && m.get("id") instanceof Number n && n.longValue() == typeId) return String.valueOf(m.get("name"));
}
}
return "This ticket type";
}
/** An order by its link token: the buyer's name but no other personal details; instructions and hold only while awaiting payment. */
public Map<String, Object> order(String token) {
if (token == null || !PublicRegistrationService.TOKEN_SHAPE.matcher(token).matches()) throw orderInvalid();
registration.limit("ord:load:" + PublicRegistrationService.ip(), ORDER_LOAD_LIMIT, "Too many requests from this device. Try again later.");
Map<String, Object> o = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_ORDER_BY_TOKEN), MAP, token).getBody());
if (o == null || !(o.get("eventUuid") instanceof Number uuid)) throw orderInvalid();
CompanyEvent e = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, uuid.longValue()).getBody());
if (e == null) throw orderInvalid();
Map<String, Object> out = new LinkedHashMap<>();
for (String k : List.of("reference", "status", "buyerName", "totalSen", "createdAt", "lines")) out.put(k, o.get(k));
out.put("eventName", e.getName());
out.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
out.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
out.put("location", e.getLocation());
if ("AWAITING".equals(o.get("status"))) {
out.put("holdUntil", o.get("holdUntil"));
out.put("paymentInstructions", e.getPaymentInstructions());
}
return out;
}
private static CodedResponseStatusException orderInvalid() {
return new CodedResponseStatusException(HttpStatus.NOT_FOUND, "This order link is not valid.", "ORDER_INVALID");
}
/** An image's bytes with the counter's type and long cache; a missing one is 404. Image ids are not secret. */
public ResponseEntity<byte[]> image(long id) {
ResponseEntity<byte[]> r = PublicRegistrationService.found(() -> rest.getForEntity(
@@ -0,0 +1,282 @@
package com.solvway.mobile.api.service;
import com.solvway.core.enums.GeneralEnum;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.dto.PublicTicketRequest;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** add-event-ticket-orders: the TICKETS block's page data, a visitor's ticket request and the public order page. */
@SuppressWarnings({"unchecked", "rawtypes"})
class PublicTicketTest {
private static final String BRANDING = "/company/branding/{code}";
private static final String PUBLISHED = "/counter/cmsPage/findPublished/{companyId}/{slug}";
private static final String EVENT = "/counter/event/findByUuid/{uuid}";
private static final String COMPANY_URL = "/company/findById/{id}";
private static final String NOTICE = "/company/{id}/privacyNotice";
private static final String ON_SALE = "/counter/ticketType/onSale/{eventUuid}";
private static final String REQUEST = "/counter/ticketOrder/request";
private static final String BY_TOKEN = "/counter/ticketOrder/byToken/{token}";
private static final long EV = 3312726793093644288L;
private static final long COMPANY = 1L;
private static final String TOKEN = "abcdefghijklmnopqrstuv";
private RestTemplateCustomUtil rest;
private ValueOperations<String, Object> ops;
private MockedStatic<HttpReqRespUtils> http;
private PublicPageService service;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
RedisTemplate<String, Object> redis = mock(RedisTemplate.class);
ops = mock(ValueOperations.class);
when(redis.opsForValue()).thenReturn(ops);
when(ops.increment(any())).thenReturn(1L);
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getClientIpAddressIfServletRequestExist).thenReturn("1.2.3.4");
AdminEventLeadService leads = new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope());
PublicRegistrationService registration = new PublicRegistrationService(rest, leads, redis,
Clock.fixed(Instant.parse("2027-01-10T04:00:00Z"), ZoneOffset.UTC));
service = new PublicPageService(rest, registration);
Map<String, Object> brand = new HashMap<>(Map.of("id", COMPANY, "code", "INS", "name", "INS", "accentColor", "#0B5FFF"));
stub(BRANDING, "INS", brand);
Map<String, Object> tickets = new HashMap<>(Map.of("type", "TICKETS", "heading", "Get tickets", "eventUuid", String.valueOf(EV)));
Map<String, Object> page = new HashMap<>(Map.of("id", 12L, "companyId", COMPANY, "slug", "tech-day", "title", "Tech day",
"status", "PUBLISHED", "blocks", List.of(Map.of("type", "RICH_TEXT", "html", "<p>Hi</p>"), tickets)));
when(rest.getForEntity(eq(PUBLISHED), any(ParameterizedTypeReference.class), eq(COMPANY), eq("tech-day"))).thenReturn(ResponseEntity.ok(page));
stubEvent(LocalDateTime.of(2027, 1, 16, 18, 0));
stub(COMPANY_URL, COMPANY, Map.of("id", COMPANY, "name", "INS", "status", "A"));
stub(NOTICE, COMPANY, Map.of("id", 9L, "textEn", "English notice", "textMs", "Notis"));
stubOnSale(true);
when(rest.postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(new HashMap<>(Map.of(
"reference", "T-7K3M9Q", "token", TOKEN, "status", "AWAITING", "totalSen", 100000, "paymentInstructions", "Maybank 5140"))));
}
@AfterEach
void close() {
http.close();
}
private void stub(String url, Object var, Object body) {
when(rest.getForEntity(eq(url), any(ParameterizedTypeReference.class), eq(var))).thenReturn(ResponseEntity.ok(body));
}
private void stubEvent(LocalDateTime end) {
CompanyEvent e = new CompanyEvent();
e.setCompanyId(COMPANY);
e.setUuid(EV);
e.setName("KL Hotel Tech Day");
e.setLocation("KLCC");
e.setDateStart(LocalDateTime.of(2027, 1, 15, 9, 0));
e.setDateEnd(end);
e.setEnabled(GeneralEnum.FlagYesNo.Y);
e.setTicketsEnabled(true);
e.setPaymentInstructions("Maybank 5140");
stub(EVENT, EV, e);
}
private void stubOnSale(boolean open) {
stub(ON_SALE, EV, Map.of("ticketsOpen", open, "paymentInstructions", "Maybank 5140", "types",
List.of(Map.of("id", 2, "name", "General", "priceSen", 25000, "left", 80, "state", "ON_SALE"),
Map.of("id", 3, "name", "VIP", "priceSen", 50000, "left", 0, "state", "SOLD_OUT"))));
}
private static PublicTicketRequest visitor(String website) {
return new PublicTicketRequest(List.of(new PublicTicketRequest.Line(2L, 2), new PublicTicketRequest.Line(3L, 0)),
" Aisyah ", "012-555 0101", " Aisyah@Example.TEST ", " Hotel Seri ", true, website, "fb", "social", "launch");
}
private Map<String, Object> posted() {
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), c.capture());
return (Map<String, Object>) c.getValue();
}
private static void assertCoded(Runnable r, HttpStatus status, String code) {
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(status);
assertThat(e.getCode()).isEqualTo(code);
});
}
private static HttpClientErrorException counter(HttpStatus status, String detail) {
String body = "{\"status\":" + status.value() + ",\"detail\":\"" + detail + "\"}";
return HttpClientErrorException.create(status, status.getReasonPhrase(), null, body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
}
private List<Map<String, Object>> blocks() {
return (List<Map<String, Object>>) ((Map<String, Object>) service.page("INS", "tech-day").get("page")).get("blocks");
}
// --- page data ---
@Test
void aTicketsBlockCarriesItsEventAndTypes() {
Map<String, Object> t = (Map<String, Object>) blocks().get(1).get("tickets");
assertThat(t).containsEntry("eventName", "KL Hotel Tech Day").containsEntry("location", "KLCC").containsEntry("startDate", "2027-01-15")
.containsKey("notice");
assertThat((List<Map<String, Object>>) t.get("types")).extracting(m -> m.get("state")).containsExactly("ON_SALE", "SOLD_OUT");
assertThat(blocks().get(1)).doesNotContainKey("closed");
}
@Test
void aTicketsBlockIsClosedWhenSalesAreClosedAndThePageStillShows() {
stubOnSale(false);
List<Map<String, Object>> b = blocks();
assertThat(b.get(1)).containsEntry("closed", true).doesNotContainKey("tickets");
assertThat(b.get(0)).containsEntry("type", "RICH_TEXT");
stubOnSale(true);
stubEvent(LocalDateTime.of(2027, 1, 9, 18, 0)); // ended yesterday
assertThat(blocks().get(1)).containsEntry("closed", true);
}
// --- request ---
@Test
void aRequestIsNormalisedAndPostedWithThePageAndConsent() {
Map<String, Object> out = service.tickets("INS", "tech-day", 1, visitor(null));
Map<String, Object> body = posted();
assertThat(body).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("buyerName", "Aisyah")
.containsEntry("buyerEmail", "aisyah@example.test").containsEntry("buyerMobileE164", "+60125550101")
.containsEntry("buyerCompany", "Hotel Seri").containsEntry("consentNoticeId", 9L).containsEntry("pagePath", "/p/INS/tech-day")
.containsEntry("utmSource", "fb").containsEntry("utmCampaign", "launch").containsKey("consentAt");
assertThat((List<Map<String, Object>>) body.get("lines")).containsExactly(Map.of("ticketTypeId", 2L, "quantity", 2),
Map.of("ticketTypeId", 3L, "quantity", 0));
assertThat(out).containsEntry("reference", "T-7K3M9Q").containsEntry("token", TOKEN).containsEntry("paymentInstructions", "Maybank 5140")
.containsEntry("eventName", "KL Hotel Tech Day");
}
@Test
void aFreeOrderShowsNoPaymentInstructions() {
when(rest.postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(new HashMap<>(Map.of(
"reference", "T-7K3M9Q", "token", TOKEN, "status", "PAID", "totalSen", 0, "paymentInstructions", "Maybank 5140"))));
assertThat(service.tickets("INS", "tech-day", 1, visitor(null))).doesNotContainKey("paymentInstructions");
}
@Test
void theHoneypotGetsAThankYouWithoutAnOrder() {
Map<String, Object> out = service.tickets("INS", "tech-day", 1, visitor("http://spam"));
assertThat(out).containsEntry("eventName", "KL Hotel Tech Day").doesNotContainKey("token");
verify(rest, never()).postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), any());
}
@Test
void theSubmitLimitApplies() {
when(ops.increment("reg:submit:" + EV + ":1.2.3.4")).thenReturn(61L);
assertThatThrownBy(() -> service.tickets("INS", "tech-day", 1, visitor(null))).isInstanceOfSatisfying(CodedResponseStatusException.class,
e -> assertThat(e.getReason()).isEqualTo("Too many registrations from this device. Try again later."));
verify(rest, never()).postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), any());
}
@Test
void nameEmailAndConsentAreRequiredHere() {
assertCoded(() -> service.tickets("INS", "tech-day", 1, new PublicTicketRequest(List.of(new PublicTicketRequest.Line(2L, 1)),
"Aisyah", "0125550101", null, null, true, null, null, null, null)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
assertCoded(() -> service.tickets("INS", "tech-day", 1, new PublicTicketRequest(List.of(new PublicTicketRequest.Line(2L, 1)),
"Aisyah", null, "a@example.test", null, false, null, null, null, null)), HttpStatus.BAD_REQUEST, "CONSENT_REQUIRED");
verify(rest, never()).postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), any());
}
@Test
void aBlockThatIsNotTicketsIsNotFound() {
assertCoded(() -> service.tickets("INS", "tech-day", 0, visitor(null)), HttpStatus.NOT_FOUND, "PAGE_NOT_FOUND");
}
@Test
void counterRefusalsBecomePublicMessages() {
when(rest.postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), any())).thenThrow(counter(HttpStatus.CONFLICT, "TYPE_UNAVAILABLE|2|1"));
assertThatThrownBy(() -> service.tickets("INS", "tech-day", 1, visitor(null))).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getCode()).isEqualTo("TYPE_UNAVAILABLE");
assertThat(e.getReason()).isEqualTo("General has only 1 ticket left.");
assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("ticketTypeId", 2L).containsEntry("left", 1L);
});
when(rest.postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), any())).thenThrow(counter(HttpStatus.CONFLICT, "TOO_MANY_AWAITING"));
assertThatThrownBy(() -> service.tickets("INS", "tech-day", 1, visitor(null))).isInstanceOfSatisfying(CodedResponseStatusException.class,
e -> assertThat(e.getReason()).isEqualTo("You already have orders awaiting payment for this event."));
when(rest.postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), any())).thenThrow(counter(HttpStatus.CONFLICT, "EVENT_FULL|0"));
assertCoded(() -> service.tickets("INS", "tech-day", 1, visitor(null)), HttpStatus.CONFLICT, "EVENT_FULL");
when(rest.postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), any())).thenThrow(counter(HttpStatus.CONFLICT, "TICKETS_CLOSED"));
assertCoded(() -> service.tickets("INS", "tech-day", 1, visitor(null)), HttpStatus.CONFLICT, "TICKETS_CLOSED");
when(rest.postForEntity(eq(REQUEST), any(ParameterizedTypeReference.class), any())).thenThrow(counter(HttpStatus.BAD_REQUEST, "BAD_QUANTITY"));
assertCoded(() -> service.tickets("INS", "tech-day", 1, visitor(null)), HttpStatus.BAD_REQUEST, "BAD_QUANTITY");
}
// --- order page ---
private void stubOrder(String status) {
Map<String, Object> o = new HashMap<>(Map.of("companyId", COMPANY, "eventUuid", EV, "reference", "T-7K3M9Q", "status", status,
"buyerName", "Aisyah", "totalSen", 50000, "lines", List.of(Map.of("name", "General", "unitPriceSen", 25000, "quantity", 2))));
o.put("holdUntil", "2027-01-13T12:00:00");
stub(BY_TOKEN, TOKEN, o);
}
@Test
void anAwaitingOrderShowsItsEventInstructionsAndHold() {
stubOrder("AWAITING");
Map<String, Object> out = service.order(TOKEN);
assertThat(out).containsEntry("reference", "T-7K3M9Q").containsEntry("buyerName", "Aisyah").containsEntry("eventName", "KL Hotel Tech Day")
.containsEntry("location", "KLCC").containsEntry("paymentInstructions", "Maybank 5140").containsEntry("holdUntil", "2027-01-13T12:00:00")
.doesNotContainKey("companyId");
}
@Test
void aPaidOrderHasNoInstructionsOrHold() {
stubOrder("PAID");
assertThat(service.order(TOKEN)).doesNotContainKeys("paymentInstructions", "holdUntil").containsEntry("status", "PAID");
}
@Test
void aBadTokenShapeIsNotFoundWithoutABackendCall() {
assertCoded(() -> service.order("short"), HttpStatus.NOT_FOUND, "ORDER_INVALID");
verify(rest, never()).getForEntity(anyString(), any(ParameterizedTypeReference.class), any(Object[].class));
verify(ops, never()).increment(any());
}
@Test
void anUnknownTokenIsNotFound() {
when(rest.getForEntity(eq(BY_TOKEN), any(ParameterizedTypeReference.class), eq(TOKEN))).thenThrow(HttpClientErrorException.NotFound.class);
assertCoded(() -> service.order(TOKEN), HttpStatus.NOT_FOUND, "ORDER_INVALID");
}
@Test
void theOrderPageLoadLimitApplies() {
when(ops.increment("ord:load:1.2.3.4")).thenReturn(121L);
assertCoded(() -> service.order(TOKEN), HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY");
}
}