diff --git a/openspec/changes/add-event-tickets/tasks.md b/openspec/changes/add-event-tickets/tasks.md index eae0244..84e817e 100644 --- a/openspec/changes/add-event-tickets/tasks.md +++ b/openspec/changes/add-event-tickets/tasks.md @@ -73,7 +73,7 @@ Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-04 ## 3. mobile-api and gateway -- [ ] 3.1 Public ticket endpoints, the QR PNG and gateway paths. +- [x] 3.1 Public ticket endpoints, the QR PNG and gateway paths. - Depends on: 2.3 - Tests first: - **`GET /api/public/tickets/{code}`:** diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java index 45f8f9c..071d108 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java @@ -64,6 +64,10 @@ public class JWTAuthFilter implements GlobalFilter, Ordered { 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}"), + // Tickets (add-event-tickets): a ticket by its code, naming an attendee by the order token, attendee consent. Check-in needs a token. + publicPath(HttpMethod.GET, "/counter/ticket/byCode/[A-Za-z0-9_-]{22}"), + publicPath(HttpMethod.POST, "/counter/ticket/attendee"), + publicPath(HttpMethod.POST, "/counter/ticket/consent"), // 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 diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterTicketCodesPathTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterTicketCodesPathTest.java new file mode 100644 index 0000000..0e54250 --- /dev/null +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterTicketCodesPathTest.java @@ -0,0 +1,81 @@ +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-tickets: a ticket by its code, naming an attendee and attendee consent are open; staff check-in stays closed. */ +class JWTAuthFilterTicketCodesPathTest { + + 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 publicTicketCodeCallsNeedNoUserToken() { + for (String[] c : new String[][] { + {"GET", "/counter/ticket/byCode/abcdefghijklmnopqrstu_"}, + {"POST", "/counter/ticket/attendee"}, + {"POST", "/counter/ticket/consent"} }) { + assertThat(passes(call(HttpMethod.valueOf(c[0]), c[1]))).as(c[0] + " " + c[1]).isTrue(); + } + } + + @Test + void otherTicketShapesAndStaffCallsNeedAUserToken() { + for (String[] c : new String[][] { + {"GET", "/counter/ticket/byCode/short"}, + {"GET", "/counter/ticket/byCode/abcdefghijklmnopqrstuvw"}, + {"GET", "/counter/ticket/byCode/abcdefghijklmnopqrstu_/x"}, + {"POST", "/counter/ticket/byCode/abcdefghijklmnopqrstu_"}, + {"GET", "/counter/ticket/attendee"}, + {"GET", "/counter/ticket/consent"}, + {"POST", "/counter/ticket/staff"}, + {"POST", "/counter/ticket/checkin"} }) { + 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); + } + } +} diff --git a/solvway-mobile-api/pom.xml b/solvway-mobile-api/pom.xml index 7cf811f..5804ec3 100644 --- a/solvway-mobile-api/pom.xml +++ b/solvway-mobile-api/pom.xml @@ -67,6 +67,12 @@ libphonenumber 8.13.55 + + + com.google.zxing + core + 3.5.3 + org.springframework.boot diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index 842929a..e419b45 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -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}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicPageController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicPageController.java index 6270605..7af213c 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicPageController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicPageController.java @@ -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 image(@PathVariable long id) { return pages.image(id); } + + @AppAuth(skipValidate = true) + @GetMapping("/api/public/tickets/{code}") + public ResponseEntity> ticket(@PathVariable String code) { + return ResponseEntity.ok(tickets.ticket(code)); + } + + @AppAuth(skipValidate = true) + @GetMapping("/api/public/tickets/{code}/qr.png") + public ResponseEntity ticketQr(@PathVariable String code) { + return tickets.qr(code); + } + + @AppAuth(skipValidate = true) + @PostMapping("/api/public/tickets/{code}/consent") + public ResponseEntity> 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> attendee(@PathVariable String token, @PathVariable long ticketId, + @RequestBody PublicTicketService.AttendeeRequest request) { + return ResponseEntity.ok(tickets.attendee(token, ticketId, request)); + } } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicInviteService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicInviteService.java index 7c6b17c..a912857 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicInviteService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicInviteService.java @@ -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()); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicPageService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicPageService.java index 8dc85bd..58c5ec9 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicPageService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicPageService.java @@ -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()); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicTicketService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicTicketService.java new file mode 100644 index 0000000..bf0089e --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicTicketService.java @@ -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 CONSENT_STATES = Set.of("VALID", "CHECKED_IN"); + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + + public record AttendeeRequest(String name, String mobile, String email, Boolean permission) {} + + public record ConsentRequest(Boolean consent) {} + + private record Loaded(Map 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 ticket(String code) { + Loaded l = load(code); + Map 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 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 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 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 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 attendee(String token, long ticketId, AttendeeRequest r) { + if (token == null || !PublicRegistrationService.TOKEN_SHAPE.matcher(token).matches()) throw orderInvalid(); + Map 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 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 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 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 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 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 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); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicTicketPageTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicTicketPageTest.java new file mode 100644 index 0000000..25d4dc1 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicTicketPageTest.java @@ -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 ops; + private MockedStatic http; + private PublicTicketService service; + private PublicPageService pages; + private Map ticket; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + RedisTemplate 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 mockStatic() { + MockedStatic 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 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) 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 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 body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(CONSENT), any(Class.class), body.capture()); + assertThat((Map) 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 out = service.attendee(TOKEN, 1L, new PublicTicketService.AttendeeRequest(" Tan Mei Ling ", "012-555 0101", + " Tan@Example.COM ", true)); + assertThat(out).containsEntry("code", "newcodenewcodenewcode_"); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(ATTENDEE), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) 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> 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"); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketService.java index 5594523..640c3ea 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketService.java @@ -170,14 +170,14 @@ public class TicketService { /** The public ticket page: no buyer details and no attendee contact. */ public record TicketView(long companyId, long eventUuid, String typeName, String attendeeFirstName, boolean named, String state, - LocalDateTime checkedInAt) {} + LocalDateTime checkedInAt, boolean consented) {} public TicketView byCode(String code) { Ticket t = ticket(code); ShopOrder o = orders.findById(t.getOrderId()).orElseThrow(TicketService::notFound); String typeName = lines.findById(t.getOrderLineId()).map(ShopOrderLine::getName).orElse(null); return new TicketView(t.getCompanyId(), t.getEventUuid(), typeName, firstName(t.getAttendeeName()), t.getAttendeeName() != null, - TicketState.of(o, t), t.getCheckedInAt()); + TicketState.of(o, t), t.getCheckedInAt(), t.getAttendeeConsentAt() != null); } Ticket ticket(String code) { diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCheckInTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCheckInTest.java index e2aa195..77af6a0 100644 --- a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCheckInTest.java +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketCheckInTest.java @@ -128,6 +128,14 @@ class TicketCheckInTest { assertStatus(() -> service.staffView(new TicketService.StaffRequest(null, CODE)), 404, "TICKET_NOT_FOUND"); } + @Test + void thePublicViewTellsWhetherTheAttendeeHasConsented() { + named(); + assertThat(service.byCode(CODE).consented()).isFalse(); + ticket.setAttendeeConsentAt(LocalDateTime.now()); + assertThat(service.byCode(CODE).consented()).isTrue(); + } + @Test void checkInRecordsTheTimeAndTheStaffUserWithAConditionalUpdate() { named();