feat(tickets): public ticket page API, QR PNG, attendee naming and consent

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 17:19:56 +08:00
1 parent 6215eb5d8c
commit 8f3818414d
12 files changed
+629 -4

No files matched your search

@@ -60,6 +60,9 @@ public class RestApiCounterServiceConstants {
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_TICKET_BY_CODE = "/counter/ticket/byCode/{code}";
public static final String API_REST_COUNTER_TICKET_ATTENDEE = "/counter/ticket/attendee";
public static final String API_REST_COUNTER_TICKET_CONSENT = "/counter/ticket/consent";
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}";
@@ -4,6 +4,7 @@ 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 com.solvway.mobile.api.service.PublicTicketService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@@ -19,6 +20,7 @@ import java.util.Map;
@RequiredArgsConstructor
public class PublicPageController {
private final PublicPageService pages;
private final PublicTicketService tickets;
@AppAuth(skipValidate = true)
@GetMapping("/api/public/pages/{company}/{slug}")
@@ -51,4 +53,29 @@ public class PublicPageController {
public ResponseEntity<byte[]> image(@PathVariable long id) {
return pages.image(id);
}
@AppAuth(skipValidate = true)
@GetMapping("/api/public/tickets/{code}")
public ResponseEntity<Map<String, Object>> ticket(@PathVariable String code) {
return ResponseEntity.ok(tickets.ticket(code));
}
@AppAuth(skipValidate = true)
@GetMapping("/api/public/tickets/{code}/qr.png")
public ResponseEntity<byte[]> ticketQr(@PathVariable String code) {
return tickets.qr(code);
}
@AppAuth(skipValidate = true)
@PostMapping("/api/public/tickets/{code}/consent")
public ResponseEntity<Map<String, Object>> ticketConsent(@PathVariable String code, @RequestBody PublicTicketService.ConsentRequest request) {
return ResponseEntity.ok(tickets.consent(code, request));
}
@AppAuth(skipValidate = true)
@PostMapping("/api/public/orders/{token}/tickets/{ticketId}/attendee")
public ResponseEntity<Map<String, Object>> attendee(@PathVariable String token, @PathVariable long ticketId,
@RequestBody PublicTicketService.AttendeeRequest request) {
return ResponseEntity.ok(tickets.attendee(token, ticketId, request));
}
}
@@ -182,7 +182,7 @@ public class PublicInviteService {
}
}
private static String counterCode(HttpClientErrorException e) {
static String counterCode(HttpClientErrorException e) {
try {
// The counter's core error handler sends a ProblemDetail whose "detail" is the reason code.
com.fasterxml.jackson.databind.JsonNode body = new ObjectMapper().readTree(e.getResponseBodyAsString());
@@ -257,6 +257,7 @@ public class PublicPageService {
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 ("PAID".equals(o.get("status"))) out.put("tickets", o.get("tickets") instanceof List<?> l ? l : List.of());
if ("AWAITING".equals(o.get("status"))) {
out.put("holdUntil", o.get("holdUntil"));
out.put("paymentInstructions", e.getPaymentInstructions());
@@ -0,0 +1,209 @@
package com.solvway.mobile.api.service;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.CacheControl;
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 javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* add-event-tickets, public side: the ticket page by its code, the ticket's QR as a PNG for emails, attendee consent, and the buyer
* naming a ticket's attendee by the order's link token. Inputs are normalised as in QR registration; no attendee contact goes out.
*/
@Service
@SuppressWarnings("unchecked")
public class PublicTicketService {
private static final int LOAD_LIMIT = 120;
private static final int SUBMIT_LIMIT = 60;
private static final int QR_PX = 300;
private static final String TOO_MANY = "Too many requests from this device. Try again later.";
private static final Set<String> CONSENT_STATES = Set.of("VALID", "CHECKED_IN");
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
public record AttendeeRequest(String name, String mobile, String email, Boolean permission) {}
public record ConsentRequest(Boolean consent) {}
private record Loaded(Map<String, Object> ticket, PublicRegistrationService.Open open) {}
private final RestTemplateCustomUtil rest;
private final PublicRegistrationService registration;
private final String portalBase;
public PublicTicketService(RestTemplateCustomUtil rest, PublicRegistrationService registration,
@Value("${app.admin-portal-base-url}") String portalBase) {
this.rest = rest;
this.registration = registration;
this.portalBase = portalBase.replaceAll("/+$", "");
}
/** The public ticket page: event, ticket type, attendee first name and state; the consent offer only for a named valid ticket. */
public Map<String, Object> ticket(String code) {
Loaded l = load(code);
Map<String, Object> out = new LinkedHashMap<>();
for (String k : List.of("typeName", "attendeeFirstName", "named", "state", "checkedInAt", "consented")) out.put(k, l.ticket().get(k));
CompanyEvent e = l.open().event();
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());
out.put("companyName", l.open().companyName());
if (offersConsent(l.ticket())) {
Map<String, Object> n = l.open().notice();
out.put("notice", Map.of("id", n.get("id"), "textEn", String.valueOf(n.get("textEn")), "textMs", String.valueOf(n.get("textMs"))));
}
return out;
}
/** The ticket's QR for emails: encodes the ticket page link; only while the ticket is valid. */
public ResponseEntity<byte[]> qr(String code) {
Loaded l = load(code);
if (!"VALID".equals(l.ticket().get("state"))) throw invalid();
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)).cachePrivate())
.body(png(portalBase + "/t/" + code));
}
/** The attendee opts in on their ticket page, under the company's current notice. */
public Map<String, Object> consent(String code, ConsentRequest r) {
Loaded l = load(code);
registration.limit("tkt:submit:" + PublicRegistrationService.ip() + ":" + l.open().event().getUuid(), SUBMIT_LIMIT, TOO_MANY);
if (r == null || !Boolean.TRUE.equals(r.consent())) {
throw AdminEventLeadService.error(HttpStatus.BAD_REQUEST, "Please tick the box to be kept updated.", "CONSENT_REQUIRED", "consent");
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("code", code);
body.put("noticeId", l.open().notice().get("id"));
try {
rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_CONSENT), Void.class, body);
} catch (HttpClientErrorException e) {
throw refusal(e);
}
return Map.of("consented", true);
}
/** The buyer names or renames a ticket of their Paid order; the counter issues a new code and emails the attendee. */
public Map<String, Object> attendee(String token, long ticketId, AttendeeRequest r) {
if (token == null || !PublicRegistrationService.TOKEN_SHAPE.matcher(token).matches()) throw orderInvalid();
Map<String, Object> order = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_ORDER_BY_TOKEN), MAP, token).getBody());
if (order == null || !(order.get("eventUuid") instanceof Number uuid)) throw orderInvalid();
registration.limit("tkt:submit:" + PublicRegistrationService.ip() + ":" + uuid.longValue(), SUBMIT_LIMIT, TOO_MANY);
if (r == null) throw AdminEventLeadService.required(List.of("name"));
String name = AdminEventLeadService.trimmed(r.name());
String mobile = AdminEventLeadService.mobile(r.mobile());
String email = AdminEventLeadService.email(r.email());
List<String> missing = new ArrayList<>();
if (name == null) missing.add("name");
if (mobile == null && email == null) {
missing.add("mobile");
missing.add("email");
}
if (!missing.isEmpty()) throw AdminEventLeadService.required(missing);
AdminEventLeadService.maxLength("name", name, 100);
AdminEventLeadService.maxLength("email", email, 254);
if (!Boolean.TRUE.equals(r.permission())) {
throw AdminEventLeadService.error(HttpStatus.BAD_REQUEST, "Please confirm you have permission to share these details.",
"PERMISSION_REQUIRED", "permission");
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("orderToken", token);
body.put("ticketId", ticketId);
body.put("name", name);
body.put("mobileE164", mobile);
body.put("email", email);
body.put("permission", true);
try {
Map<String, Object> out = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_ATTENDEE), MAP, body).getBody();
return out == null ? Map.of() : out;
} catch (HttpClientErrorException e) {
throw refusal(e);
}
}
/** Shape check, load limit, the ticket and its event with company and notice; anything missing is one "not valid". */
private Loaded load(String code) {
if (code == null || !PublicRegistrationService.TOKEN_SHAPE.matcher(code).matches()) throw invalid();
registration.limit("tkt:load:" + PublicRegistrationService.ip(), LOAD_LIMIT, TOO_MANY);
Map<String, Object> t = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_BY_CODE), MAP, code).getBody());
if (t == null || !(t.get("eventUuid") instanceof Number uuid) || !(t.get("companyId") instanceof Number company)) throw invalid();
Map<String, Object> link = new LinkedHashMap<>();
link.put("eventUuid", uuid.longValue());
link.put("companyId", company.longValue());
PublicRegistrationService.Open o = registration.load(link, false);
if (o == null) throw invalid();
return new Loaded(t, o);
}
private static boolean offersConsent(Map<String, Object> t) {
return Boolean.TRUE.equals(t.get("named")) && !Boolean.TRUE.equals(t.get("consented")) && CONSENT_STATES.contains(t.get("state"));
}
/** The counter's refusal as the message a visitor reads. */
private static CodedResponseStatusException refusal(HttpClientErrorException e) {
String code = PublicInviteService.counterCode(e);
return switch (code) {
case "NOT_PAID" -> new CodedResponseStatusException(HttpStatus.CONFLICT, "Tickets can be named once the order is paid.", code);
case "TICKET_CANCELLED" -> new CodedResponseStatusException(HttpStatus.CONFLICT, "This ticket was cancelled.", code);
case "ALREADY_CHECKED_IN" -> new CodedResponseStatusException(HttpStatus.CONFLICT,
"This ticket is already checked in and can no longer be changed.", code);
case "ATTENDEE_REQUIRED" -> new CodedResponseStatusException(HttpStatus.CONFLICT, "This ticket has no attendee yet.", code);
case "ORDER_NOT_FOUND" -> orderInvalid();
case "TICKET_NOT_FOUND", "TICKET_NOT_VALID" -> new CodedResponseStatusException(HttpStatus.CONFLICT, "This ticket is not valid.",
"TICKET_INVALID");
default -> new CodedResponseStatusException(HttpStatus.valueOf(e.getStatusCode().value()), "This could not be completed.", code);
};
}
static byte[] png(String text) {
try {
BitMatrix m = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, QR_PX, QR_PX);
BufferedImage img = new BufferedImage(m.getWidth(), m.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
for (int y = 0; y < m.getHeight(); y++) {
for (int x = 0; x < m.getWidth(); x++) img.setRGB(x, y, m.get(x, y) ? 0x000000 : 0xFFFFFF);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(img, "png", out);
return out.toByteArray();
} catch (WriterException e) {
throw new IllegalStateException(e);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static CodedResponseStatusException invalid() {
return new CodedResponseStatusException(HttpStatus.NOT_FOUND, "This ticket link is not valid.", "TICKET_INVALID");
}
private static CodedResponseStatusException orderInvalid() {
return new CodedResponseStatusException(HttpStatus.NOT_FOUND, "This order link is not valid.", "ORDER_INVALID");
}
private String url(String api) {
return rest.getURLforApiService(api);
}
}
@@ -0,0 +1,286 @@
package com.solvway.mobile.api.service;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.solvway.core.enums.GeneralEnum;
import com.solvway.core.utils.HttpReqRespUtils;
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.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** add-event-tickets: the public ticket page, its QR PNG, attendee consent, naming attendees and the order page's tickets. */
@SuppressWarnings({"unchecked", "rawtypes"})
class PublicTicketPageTest {
private static final String BY_CODE = "/counter/ticket/byCode/{code}";
private static final String ATTENDEE = "/counter/ticket/attendee";
private static final String CONSENT = "/counter/ticket/consent";
private static final String BY_TOKEN = "/counter/ticketOrder/byToken/{token}";
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 long EV = 3312726793093644288L;
private static final long COMPANY = 1L;
private static final String CODE = "abcdefghijklmnopqrstu_";
private static final String TOKEN = "tokentokentokentokento";
private RestTemplateCustomUtil rest;
private ValueOperations<String, Object> ops;
private MockedStatic<HttpReqRespUtils> http;
private PublicTicketService service;
private PublicPageService pages;
private Map<String, Object> ticket;
@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();
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 PublicTicketService(rest, registration, "https://portal.example.test/");
pages = new PublicPageService(rest, registration);
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(LocalDateTime.of(2027, 1, 16, 18, 0));
e.setEnabled(GeneralEnum.FlagYesNo.Y);
e.setTicketsEnabled(true);
stub(EVENT, EV, e);
stub(COMPANY_URL, COMPANY, Map.of("id", COMPANY, "name", "INS", "status", "A"));
stub(NOTICE, COMPANY, Map.of("id", 9L, "textEn", "English notice", "textMs", "Notis"));
ticket = new HashMap<>(Map.of("companyId", COMPANY, "eventUuid", EV, "typeName", "General", "attendeeFirstName", "Tan",
"named", true, "state", "VALID", "consented", false));
stub(BY_CODE, CODE, ticket);
}
private MockedStatic<HttpReqRespUtils> mockStatic() {
MockedStatic<HttpReqRespUtils> m = org.mockito.Mockito.mockStatic(HttpReqRespUtils.class);
m.when(HttpReqRespUtils::getClientIpAddressIfServletRequestExist).thenReturn("1.2.3.4");
return m;
}
@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 static HttpClientErrorException counter(HttpStatus status, String code) {
return HttpClientErrorException.create(status, status.getReasonPhrase(), HttpHeaders.EMPTY,
("{\"detail\":\"" + code + "\"}").getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
}
private static void assertCoded(Runnable r, HttpStatus status, String code) {
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, ex -> {
assertThat(ex.getStatusCode()).isEqualTo(status);
assertThat(ex.getCode()).isEqualTo(code);
});
}
// ---- ticket page
@Test
void theTicketPageShowsTheEventTicketAndTheConsentOfferWithoutPersonalDetails() {
Map<String, Object> out = service.ticket(CODE);
assertThat(out).containsEntry("eventName", "KL Hotel Tech Day").containsEntry("typeName", "General")
.containsEntry("attendeeFirstName", "Tan").containsEntry("state", "VALID").containsEntry("companyName", "INS")
.containsEntry("startDate", "2027-01-15").containsEntry("location", "KLCC");
assertThat((Map<String, Object>) out.get("notice")).containsEntry("id", 9L);
assertThat(out).doesNotContainKeys("companyId", "eventUuid");
verify(ops).increment("tkt:load:1.2.3.4");
}
@Test
void noConsentOfferOnAnUnnamedAConsentedOrAnInvalidTicket() {
ticket.put("named", false);
assertThat(service.ticket(CODE)).doesNotContainKey("notice");
ticket.put("named", true);
ticket.put("consented", true);
assertThat(service.ticket(CODE)).doesNotContainKey("notice");
ticket.put("consented", false);
ticket.put("state", "ORDER_CANCELLED");
assertThat(service.ticket(CODE)).doesNotContainKey("notice").containsEntry("state", "ORDER_CANCELLED");
}
@Test
void aBadShapeOrUnknownCodeIsNotValid() {
assertCoded(() -> service.ticket("short"), HttpStatus.NOT_FOUND, "TICKET_INVALID");
assertCoded(() -> service.ticket("abcdefghijklmnopqrstu/"), HttpStatus.NOT_FOUND, "TICKET_INVALID");
verify(rest, never()).getForEntity(eq(BY_CODE), any(ParameterizedTypeReference.class), anyString());
when(rest.getForEntity(eq(BY_CODE), any(ParameterizedTypeReference.class), eq("zzzzzzzzzzzzzzzzzzzzzz")))
.thenThrow(counter(HttpStatus.NOT_FOUND, "TICKET_NOT_FOUND"));
assertCoded(() -> service.ticket("zzzzzzzzzzzzzzzzzzzzzz"), HttpStatus.NOT_FOUND, "TICKET_INVALID");
}
@Test
void theLoadLimitApplies() {
when(ops.increment("tkt:load:1.2.3.4")).thenReturn(121L);
assertCoded(() -> service.ticket(CODE), HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY");
verify(rest, never()).getForEntity(eq(BY_CODE), any(ParameterizedTypeReference.class), anyString());
}
// ---- QR PNG
@Test
void theQrPngDecodesToTheTicketLinkAndIsPrivate() throws Exception {
ResponseEntity<byte[]> r = service.qr(CODE);
assertThat(r.getHeaders().getContentType()).isEqualTo(MediaType.IMAGE_PNG);
assertThat(r.getHeaders().getCacheControl()).contains("private").contains("max-age=300");
BufferedImage img = ImageIO.read(new ByteArrayInputStream(r.getBody()));
int[] px = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth());
String text = new QRCodeReader().decode(new BinaryBitmap(new HybridBinarizer(
new RGBLuminanceSource(img.getWidth(), img.getHeight(), px)))).getText();
assertThat(text).isEqualTo("https://portal.example.test/t/" + CODE);
verify(ops).increment("tkt:load:1.2.3.4");
}
@Test
void anInvalidTicketHasNoQr() {
ticket.put("state", "AWAITING");
assertCoded(() -> service.qr(CODE), HttpStatus.NOT_FOUND, "TICKET_INVALID");
}
// ---- consent
@Test
void consentSendsTheCompanysCurrentNotice() {
assertThat(service.consent(CODE, new PublicTicketService.ConsentRequest(true))).containsEntry("consented", true);
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(CONSENT), any(Class.class), body.capture());
assertThat((Map<String, Object>) body.getValue()).containsEntry("code", CODE).containsEntry("noticeId", 9L);
verify(ops).increment("tkt:submit:1.2.3.4:" + EV);
}
@Test
void consentNeedsTheTickAndMapsCounterRefusals() {
assertCoded(() -> service.consent(CODE, new PublicTicketService.ConsentRequest(false)), HttpStatus.BAD_REQUEST, "CONSENT_REQUIRED");
when(rest.postForEntity(eq(CONSENT), any(Class.class), any())).thenThrow(counter(HttpStatus.CONFLICT, "TICKET_NOT_VALID"));
assertCoded(() -> service.consent(CODE, new PublicTicketService.ConsentRequest(true)), HttpStatus.CONFLICT, "TICKET_INVALID");
}
// ---- naming attendees
private void stubOrder() {
stub(BY_TOKEN, TOKEN, new HashMap<>(Map.of("eventUuid", EV, "status", "PAID", "reference", "T-7K3M9Q")));
}
@Test
void namingNormalisesTheAttendeeAndSendsThePermission() {
stubOrder();
when(rest.postForEntity(eq(ATTENDEE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(
new HashMap<>(Map.of("id", 1, "attendeeName", "Tan Mei Ling", "code", "newcodenewcodenewcode_", "state", "VALID"))));
Map<String, Object> out = service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest(" Tan Mei Ling ", "012-555 0101",
" Tan@Example.COM ", true));
assertThat(out).containsEntry("code", "newcodenewcodenewcode_");
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(ATTENDEE), any(ParameterizedTypeReference.class), body.capture());
assertThat((Map<String, Object>) body.getValue()).containsEntry("orderToken", TOKEN).containsEntry("ticketId", 1L)
.containsEntry("name", "Tan Mei Ling").containsEntry("mobileE164", "+60125550101")
.containsEntry("email", "tan@example.com").containsEntry("permission", true);
verify(ops).increment("tkt:submit:1.2.3.4:" + EV);
}
@Test
void namingNeedsThePermissionANameAndAContact() {
stubOrder();
assertCoded(() -> service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", false)),
HttpStatus.BAD_REQUEST, "PERMISSION_REQUIRED");
assertCoded(() -> service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest("Tan", " ", null, true)),
HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
assertCoded(() -> service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest(" ", null, "t@x.test", true)),
HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
verify(rest, never()).postForEntity(eq(ATTENDEE), any(ParameterizedTypeReference.class), any());
}
@Test
void namingRefusalsBecomePublicMessages() {
stubOrder();
PublicTicketService.AttendeeRequest r = new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", true);
when(rest.postForEntity(eq(ATTENDEE), any(ParameterizedTypeReference.class), any()))
.thenThrow(counter(HttpStatus.CONFLICT, "ALREADY_CHECKED_IN"))
.thenThrow(counter(HttpStatus.CONFLICT, "NOT_PAID"))
.thenThrow(counter(HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND"));
assertCoded(() -> service.attendee(TOKEN, 1L, r), HttpStatus.CONFLICT, "ALREADY_CHECKED_IN");
assertCoded(() -> service.attendee(TOKEN, 1L, r), HttpStatus.CONFLICT, "NOT_PAID");
assertCoded(() -> service.attendee(TOKEN, 1L, r), HttpStatus.NOT_FOUND, "ORDER_INVALID");
}
@Test
void theSubmitLimitAppliesToNaming() {
stubOrder();
when(ops.increment("tkt:submit:1.2.3.4:" + EV)).thenReturn(61L);
assertCoded(() -> service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", true)),
HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY");
}
@Test
void aBadOrderTokenIsNotValid() {
assertCoded(() -> service.attendee("bad", 1L, new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", true)),
HttpStatus.NOT_FOUND, "ORDER_INVALID");
}
// ---- order page
@Test
void aPaidOrderPageCarriesItsTickets() {
List<Map<String, Object>> tickets = List.of(Map.of("id", 1, "typeName", "General", "code", CODE, "state", "VALID"));
stub(BY_TOKEN, TOKEN, new HashMap<>(Map.of("eventUuid", EV, "status", "PAID", "reference", "T-7K3M9Q", "tickets", tickets)));
assertThat(pages.order(TOKEN)).containsEntry("tickets", tickets);
}
@Test
void anUnpaidOrderPageHasNoTickets() {
stub(BY_TOKEN, TOKEN, new HashMap<>(Map.of("eventUuid", EV, "status", "AWAITING", "reference", "T-7K3M9Q", "tickets", List.of())));
assertThat(pages.order(TOKEN)).doesNotContainKey("tickets");
}
}