feat(tickets): admin ticket settings, types and order endpoints

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:48:29 +08:00
1 parent 763a295234
commit a18ca0db71
10 files changed
+626 -2

No files matched your search

@@ -46,6 +46,17 @@ public class RestApiCounterServiceConstants {
public static final String API_REST_COUNTER_CHECKIN_LOOKUP = "/counter/checkin/lookup";
public static final String API_REST_COUNTER_CHECKIN_BY_GUEST = "/counter/checkin/byGuest";
public static final String API_REST_COUNTER_EVENT_ATTENDANCE = "/counter/event/attendance";
// add-event-ticket-orders
public static final String API_REST_COUNTER_TICKET_SETTINGS = "/counter/ticketType/settings";
public static final String API_REST_COUNTER_TICKET_TYPE_LIST = "/counter/ticketType/list";
public static final String API_REST_COUNTER_TICKET_TYPE_SAVE = "/counter/ticketType/save";
public static final String API_REST_COUNTER_TICKET_TYPE_DELETE = "/counter/ticketType/delete";
public static final String API_REST_COUNTER_TICKET_ORDER_LIST = "/counter/ticketOrder/list";
public static final String API_REST_COUNTER_TICKET_ORDER_GET = "/counter/ticketOrder/get";
public static final String API_REST_COUNTER_TICKET_ORDER_MARK_PAID = "/counter/ticketOrder/markPaid";
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_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}";
@@ -0,0 +1,130 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminTicketService;
import com.solvway.mobile.api.useraccess.AdminModule;
import com.solvway.mobile.api.useraccess.Audited;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/** add-event-ticket-orders: ticket settings, types and orders of an event. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin/events/{uuid}")
@RequiredArgsConstructor
public class AdminTicketController {
private final AdminTicketService tickets;
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@GetMapping("/tickets/settings")
public ResponseEntity<Map<String, Object>> settings(@PathVariable String uuid) {
return ResponseEntity.ok(tickets.settings(uuid));
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited(targetVariable = "uuid")
@PutMapping("/tickets/settings")
public ResponseEntity<Void> saveSettings(@PathVariable String uuid, @RequestBody AdminTicketService.SettingsBody body) {
tickets.saveSettings(uuid, body);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@GetMapping("/ticket-types")
public ResponseEntity<List<Map<String, Object>>> types(@PathVariable String uuid) {
return ResponseEntity.ok(tickets.types(uuid));
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited(targetVariable = "uuid")
@PostMapping("/ticket-types")
public ResponseEntity<Void> addType(@PathVariable String uuid, @RequestBody AdminTicketService.TypeBody body) {
tickets.saveType(uuid, null, body);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited
@PutMapping("/ticket-types/{id}")
public ResponseEntity<Void> updateType(@PathVariable String uuid, @PathVariable String id, @RequestBody AdminTicketService.TypeBody body) {
tickets.saveType(uuid, id, body);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited
@DeleteMapping("/ticket-types/{id}")
public ResponseEntity<Void> deleteType(@PathVariable String uuid, @PathVariable String id) {
tickets.deleteType(uuid, id);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@GetMapping("/orders")
public ResponseEntity<Map<String, Object>> orders(@PathVariable String uuid, @RequestParam(required = false) String status,
@RequestParam(required = false) String q, @RequestParam(defaultValue = "0") int page) {
return ResponseEntity.ok(tickets.orders(uuid, status, q, page));
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@GetMapping("/orders/{orderId}")
public ResponseEntity<Map<String, Object>> order(@PathVariable String uuid, @PathVariable String orderId) {
return ResponseEntity.ok(tickets.order(uuid, orderId));
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited
@PostMapping("/orders/{orderId}/paid")
public ResponseEntity<Void> markPaid(@PathVariable String uuid, @PathVariable String orderId,
@RequestBody(required = false) AdminTicketService.PayBody body) {
tickets.markPaid(uuid, orderId, body);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited
@PostMapping("/orders/{orderId}/cancel")
public ResponseEntity<Void> cancel(@PathVariable String uuid, @PathVariable String orderId) {
tickets.cancel(uuid, orderId);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited(targetVariable = "orderId")
@PostMapping("/orders/{orderId}/tickets/{ticketId}/cancel")
public ResponseEntity<Void> cancelTicket(@PathVariable String uuid, @PathVariable String orderId, @PathVariable String ticketId) {
tickets.cancelTicket(uuid, orderId, ticketId);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(value = "BO_EVENT_TICKETS", also = "BO_EVENTS")
@Audited
@PostMapping("/orders/{orderId}/resend")
public ResponseEntity<Void> resend(@PathVariable String uuid, @PathVariable String orderId) {
tickets.resend(uuid, orderId);
return ResponseEntity.noContent().build();
}
}
@@ -11,4 +11,8 @@ public class CompanyEvent extends Event {
private Long companyId;
private Integer capacity;
private Integer invitationCap;
/** add-event-ticket-orders: read here; changed only through the ticket settings call (event/save keeps the stored values). */
private Boolean ticketsEnabled;
private String paymentInstructions;
private Integer holdDays;
}
@@ -273,6 +273,7 @@ public class AdminEventService {
m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
m.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
m.put("enabled", e.getEnabled() == GeneralEnum.FlagYesNo.Y);
m.put("ticketsEnabled", Boolean.TRUE.equals(e.getTicketsEnabled()));
return m;
}
@@ -0,0 +1,169 @@
package com.solvway.mobile.api.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.mobile.api.dto.admin.CompanyEvent;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants.*;
/**
* add-event-ticket-orders: ticket settings, ticket types and orders of one event. Every call resolves the event through
* AdminEventLeadService.loadEvent, so another company's event is a 404; the counter checks the order belongs to that event.
* The counter validates; its refusal codes pass through with their status. Never log a buyer's name, mobile or email.
*/
@Service
@RequiredArgsConstructor
public class AdminTicketService {
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
private static final ObjectMapper JSON = new ObjectMapper();
private static final int PAGE_SIZE = 50;
/** The form field a counter refusal belongs to, so the portal can show it beside that field. */
private static final Map<String, String> FIELDS = Map.of(
"PAYMENT_INSTRUCTIONS_REQUIRED", "paymentInstructions", "PAYMENT_INSTRUCTIONS_TOO_LONG", "paymentInstructions",
"HOLD_DAYS_INVALID", "holdDays", "NAME_INVALID", "name", "NAME_TAKEN", "name", "PRICE_INVALID", "priceSen",
"QUANTITY_INVALID", "quantity", "QUANTITY_BELOW_HELD", "quantity", "PAYMENT_REF_TOO_LONG", "paymentRef");
private final RestTemplateCustomUtil rest;
private final AdminEventLeadService leads;
public record SettingsBody(Boolean ticketsEnabled, String paymentInstructions, Integer holdDays) {}
public record TypeBody(String name, Integer priceSen, Integer quantity, String salesEndDate, Integer sort, Boolean enabled) {}
public record PayBody(String paymentRef) {}
public Map<String, Object> settings(String uuid) {
CompanyEvent e = leads.loadEvent(uuid, null);
Map<String, Object> out = new LinkedHashMap<>();
out.put("ticketsEnabled", Boolean.TRUE.equals(e.getTicketsEnabled()));
out.put("paymentInstructions", e.getPaymentInstructions());
out.put("holdDays", e.getHoldDays());
return out;
}
public void saveSettings(String uuid, SettingsBody b) {
Map<String, Object> body = write(uuid);
body.put("ticketsEnabled", b != null && Boolean.TRUE.equals(b.ticketsEnabled()));
body.put("paymentInstructions", b == null ? null : b.paymentInstructions());
body.put("holdDays", b == null ? null : b.holdDays());
post(API_REST_COUNTER_TICKET_SETTINGS, MAP, body);
}
public List<Map<String, Object>> types(String uuid) {
List<Map<String, Object>> types = post(API_REST_COUNTER_TICKET_TYPE_LIST, MAP_LIST, read(uuid));
return types == null ? List.of() : types;
}
public void saveType(String uuid, String id, TypeBody b) {
Map<String, Object> body = write(uuid);
if (b == null) throw AdminEventLeadService.required(List.of("name"));
if (b.salesEndDate() != null && !b.salesEndDate().isBlank()) {
try {
LocalDate.parse(b.salesEndDate());
} catch (DateTimeParseException e) {
throw AdminEventLeadService.error(HttpStatus.BAD_REQUEST, "Sales end date is not a date", "DATE_INVALID", "salesEndDate");
}
}
body.put("id", id == null ? null : AdminEventLeadService.parseOr(id, AdminTicketService::typeNotFound));
body.put("name", b.name());
body.put("priceSen", b.priceSen());
body.put("quantity", b.quantity());
body.put("salesEndDate", b.salesEndDate() == null || b.salesEndDate().isBlank() ? null : b.salesEndDate());
body.put("sort", b.sort() == null ? 0 : b.sort());
body.put("enabled", b.enabled() == null || b.enabled());
post(API_REST_COUNTER_TICKET_TYPE_SAVE, MAP, body);
}
public void deleteType(String uuid, String id) {
Map<String, Object> body = write(uuid);
body.put("id", AdminEventLeadService.parseOr(id, AdminTicketService::typeNotFound));
post(API_REST_COUNTER_TICKET_TYPE_DELETE, MAP, body);
}
public Map<String, Object> orders(String uuid, String status, String q, int page) {
Map<String, Object> body = read(uuid);
body.put("status", status);
body.put("q", q);
body.put("page", Math.max(page, 0));
body.put("size", PAGE_SIZE);
return post(API_REST_COUNTER_TICKET_ORDER_LIST, MAP, body);
}
public Map<String, Object> order(String uuid, String orderId) {
return post(API_REST_COUNTER_TICKET_ORDER_GET, MAP, orderBody(read(uuid), orderId));
}
public void markPaid(String uuid, String orderId, PayBody b) {
Map<String, Object> body = orderBody(write(uuid), orderId);
body.put("paymentRef", b == null ? null : b.paymentRef());
post(API_REST_COUNTER_TICKET_ORDER_MARK_PAID, MAP, body);
}
public void cancel(String uuid, String orderId) {
post(API_REST_COUNTER_TICKET_ORDER_CANCEL, MAP, orderBody(write(uuid), orderId));
}
public void cancelTicket(String uuid, String orderId, String ticketId) {
Map<String, Object> body = orderBody(write(uuid), orderId);
body.put("ticketId", AdminEventLeadService.parseOr(ticketId,
() -> AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Ticket not found", "TICKET_NOT_FOUND", null)));
post(API_REST_COUNTER_TICKET_ORDER_CANCEL_TICKET, MAP, body);
}
public void resend(String uuid, String orderId) {
post(API_REST_COUNTER_TICKET_ORDER_RESEND, MAP, orderBody(read(uuid), orderId));
}
private Map<String, Object> read(String uuid) {
CompanyEvent e = leads.loadEvent(uuid, null);
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", e.getCompanyId());
body.put("eventUuid", e.getUuid());
return body;
}
private Map<String, Object> write(String uuid) {
Map<String, Object> body = read(uuid);
body.put("doneBy", leads.caller().getUsername());
return body;
}
private static Map<String, Object> orderBody(Map<String, Object> body, String orderId) {
body.put("orderId", AdminEventLeadService.parseOr(orderId,
() -> AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Order not found", "ORDER_NOT_FOUND", null)));
return body;
}
private static com.solvway.mobile.api.errorhandler.CodedResponseStatusException typeNotFound() {
return AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Ticket type not found", "TYPE_NOT_FOUND", null);
}
/** A counter refusal keeps its status; the counter's ProblemDetail "detail" is the reason code. */
private <T> T post(String api, ParameterizedTypeReference<T> type, Map<String, Object> body) {
try {
return rest.postForEntity(rest.getURLforApiService(api), type, body).getBody();
} catch (HttpClientErrorException e) {
String code = "REFUSED";
try {
JsonNode n = JSON.readTree(e.getResponseBodyAsString());
code = n.path("detail").asText(code);
} catch (Exception ignored) {
// not a ProblemDetail: keep the generic code
}
throw AdminEventLeadService.error(HttpStatus.valueOf(e.getStatusCode().value()), code, code, FIELDS.get(code));
}
}
}
@@ -0,0 +1,100 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminTicketService;
import com.solvway.mobile.api.useraccess.AdminModule;
import com.solvway.mobile.api.useraccess.Audited;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/** add-event-ticket-orders: every ticket endpoint needs BO_EVENT_TICKETS (with BO_EVENTS); every write is audited. */
@ExtendWith(MockitoExtension.class)
class AdminTicketControllerTest {
@Mock private AdminTicketService tickets;
@InjectMocks private AdminTicketController controller;
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
private static List<Method> handlers() {
return Arrays.stream(AdminTicketController.class.getDeclaredMethods())
.filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList();
}
@Test
void everyEndpointNeedsTheTicketsModule() {
assertThat(handlers()).hasSize(12);
for (Method m : handlers()) {
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue();
AdminModule module = m.getAnnotation(AdminModule.class);
assertThat(module.value()).as(m.getName()).containsExactly("BO_EVENT_TICKETS");
assertThat(module.also()).as(m.getName() + " also").containsExactly("BO_EVENTS");
}
}
@Test
void everyWriteIsAuditedAndNoReadIs() {
for (Method m : handlers()) {
boolean read = m.isAnnotationPresent(GetMapping.class);
assertThat(m.isAnnotationPresent(Audited.class)).as(m.getName() + " @Audited").isEqualTo(!read);
}
}
@Test
void routesBindToTheService() throws Exception {
when(tickets.settings("77")).thenReturn(Map.of());
mvc.perform(get("/api/admin/events/77/tickets/settings")).andExpect(status().isOk());
mvc.perform(put("/api/admin/events/77/tickets/settings").contentType(MediaType.APPLICATION_JSON)
.content("{\"ticketsEnabled\":true,\"paymentInstructions\":\"Maybank\",\"holdDays\":3}")).andExpect(status().isNoContent());
verify(tickets).saveSettings("77", new AdminTicketService.SettingsBody(true, "Maybank", 3));
String type = "{\"name\":\"General\",\"priceSen\":25000,\"quantity\":100,\"salesEndDate\":null,\"sort\":1,\"enabled\":true}";
mvc.perform(post("/api/admin/events/77/ticket-types").contentType(MediaType.APPLICATION_JSON).content(type)).andExpect(status().isNoContent());
verify(tickets).saveType(eq("77"), eq(null), any());
mvc.perform(put("/api/admin/events/77/ticket-types/2").contentType(MediaType.APPLICATION_JSON).content(type)).andExpect(status().isNoContent());
verify(tickets).saveType(eq("77"), eq("2"), any());
mvc.perform(delete("/api/admin/events/77/ticket-types/2")).andExpect(status().isNoContent());
verify(tickets).deleteType("77", "2");
mvc.perform(get("/api/admin/events/77/orders").param("status", "PAID").param("q", "ais").param("page", "1")).andExpect(status().isOk());
verify(tickets).orders("77", "PAID", "ais", 1);
mvc.perform(get("/api/admin/events/77/orders/300")).andExpect(status().isOk());
verify(tickets).order("77", "300");
mvc.perform(post("/api/admin/events/77/orders/300/paid").contentType(MediaType.APPLICATION_JSON).content("{\"paymentRef\":\"MBB 1\"}"))
.andExpect(status().isNoContent());
verify(tickets).markPaid("77", "300", new AdminTicketService.PayBody("MBB 1"));
mvc.perform(post("/api/admin/events/77/orders/300/cancel")).andExpect(status().isNoContent());
verify(tickets).cancel("77", "300");
mvc.perform(post("/api/admin/events/77/orders/300/tickets/7/cancel")).andExpect(status().isNoContent());
verify(tickets).cancelTicket("77", "300", "7");
mvc.perform(post("/api/admin/events/77/orders/300/resend")).andExpect(status().isNoContent());
verify(tickets).resend("77", "300");
}
}
@@ -71,6 +71,7 @@ class AdminEventServiceCapacityTest {
e.setDateEnd(LocalDateTime.of(2026, 5, 2, 23, 59, 59));
e.setCapacity(500);
e.setInvitationCap(40);
e.setTicketsEnabled(true);
when(rest.getForEntity(eq(BY_UUID), any(ParameterizedTypeReference.class), eq(UUID))).thenReturn(ResponseEntity.ok(e));
}
@@ -92,6 +93,11 @@ class AdminEventServiceCapacityTest {
return (CompanyEvent) c.getValue();
}
@Test
void get_showsWhetherTheEventSellsTickets() {
assertThat(service.get(String.valueOf(UUID))).containsEntry("ticketsEnabled", true);
}
@Test
void get_showsCapacityAndInvitationCap() {
assertThat(service.get(String.valueOf(UUID))).containsEntry("capacity", 500).containsEntry("invitationCap", 40);
@@ -162,7 +162,7 @@ class AdminEventServiceTest {
assertThat(out).containsEntry("totalElements", 41L).containsEntry("totalPages", 3).containsEntry("number", 2).containsEntry("size", 20);
Map<String, Object> row = ((List<Map<String, Object>>) out.get("content")).get(0);
assertThat(row).containsExactlyInAnyOrderEntriesOf(Map.of("uuid", "7123456789012345678", "name", "Old", "location", "Old place",
"startDate", "2026-05-01", "endDate", "2026-05-02", "enabled", true, "companyId", 5L));
"startDate", "2026-05-01", "endDate", "2026-05-02", "enabled", true, "companyId", 5L, "ticketsEnabled", false));
}
@Test
@@ -0,0 +1,203 @@
package com.solvway.mobile.api.service;
import com.solvway.core.model.User;
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.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
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: admin ticket settings, types and orders (spec: Ticket Settings, Ticket Types, Staff Order Screens and Actions). */
@SuppressWarnings({"unchecked", "rawtypes"})
class AdminTicketServiceTest {
private static final String EVENT = "/counter/event/findByUuid/{uuid}";
private static final String SETTINGS = "/counter/ticketType/settings";
private static final String TYPES = "/counter/ticketType/list";
private static final String TYPE_SAVE = "/counter/ticketType/save";
private static final String TYPE_DELETE = "/counter/ticketType/delete";
private static final String ORDERS = "/counter/ticketOrder/list";
private static final String ORDER = "/counter/ticketOrder/get";
private static final String PAID = "/counter/ticketOrder/markPaid";
private static final String CANCEL = "/counter/ticketOrder/cancel";
private static final String CANCEL_TICKET = "/counter/ticketOrder/cancelTicket";
private static final String RESEND = "/counter/ticketOrder/resend";
private static final long EV = 3312726793093644288L;
private static final long COMPANY = 5L;
private RestTemplateCustomUtil rest;
private AdminTicketService service;
private MockedStatic<HttpReqRespUtils> http;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
service = new AdminTicketService(rest, new AdminEventLeadService(rest, auth, new AdminCompanyScope()));
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
User caller = new User();
caller.setId(21L);
caller.setUsername("finance1");
caller.setCompanyId(COMPANY);
when(auth.loadUserByToken("tok")).thenReturn(caller);
stubEvent(COMPANY);
when(rest.postForEntity(anyString(), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of()));
}
@AfterEach
void close() { http.close(); }
private void stubEvent(long company) {
CompanyEvent e = new CompanyEvent();
e.setCompanyId(company);
e.setUuid(EV);
e.setName("KL Hotel Tech Day");
e.setDateStart(LocalDateTime.of(2027, 1, 15, 9, 0));
e.setDateEnd(LocalDateTime.of(2027, 1, 16, 18, 0));
e.setTicketsEnabled(true);
e.setPaymentInstructions("Maybank 5140");
e.setHoldDays(3);
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
}
private Map<String, Object> sent(String api) {
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(api), 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 code) {
String body = "{\"type\":\"about:blank\",\"status\":" + status.value() + ",\"detail\":\"" + code + "\"}";
return HttpClientErrorException.create(status, status.getReasonPhrase(), null, body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
}
private final String ev = String.valueOf(EV);
@Test
void anotherCompanysEventIsNotFoundOnEveryOperation() {
stubEvent(99L);
assertCoded(() -> service.settings(ev), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
assertCoded(() -> service.saveSettings(ev, new AdminTicketService.SettingsBody(true, "x", 3)), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
assertCoded(() -> service.types(ev), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
assertCoded(() -> service.saveType(ev, null, new AdminTicketService.TypeBody("General", 25000, 100, null, 0, true)),
HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
assertCoded(() -> service.deleteType(ev, "2"), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
assertCoded(() -> service.orders(ev, null, null, 0), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
assertCoded(() -> service.order(ev, "300"), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
assertCoded(() -> service.markPaid(ev, "300", null), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
assertCoded(() -> service.cancel(ev, "300"), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
assertCoded(() -> service.cancelTicket(ev, "300", "1"), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
assertCoded(() -> service.resend(ev, "300"), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND");
verify(rest, never()).postForEntity(anyString(), any(ParameterizedTypeReference.class), any());
}
@Test
void settingsAreReadFromTheEventAndSavedWithTheCaller() {
assertThat(service.settings(ev)).containsEntry("ticketsEnabled", true).containsEntry("paymentInstructions", "Maybank 5140")
.containsEntry("holdDays", 3);
service.saveSettings(ev, new AdminTicketService.SettingsBody(true, "CIMB 8000", 5));
assertThat(sent(SETTINGS)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("ticketsEnabled", true)
.containsEntry("paymentInstructions", "CIMB 8000").containsEntry("holdDays", 5).containsEntry("doneBy", "finance1");
}
@Test
void aCounterRefusalKeepsItsStatusAndCodeAndNamesTheField() {
when(rest.postForEntity(eq(SETTINGS), any(ParameterizedTypeReference.class), any()))
.thenThrow(counter(HttpStatus.BAD_REQUEST, "PAYMENT_INSTRUCTIONS_REQUIRED"));
assertThatThrownBy(() -> service.saveSettings(ev, new AdminTicketService.SettingsBody(true, " ", 3)))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getCode()).isEqualTo("PAYMENT_INSTRUCTIONS_REQUIRED");
assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("field", "paymentInstructions");
});
when(rest.postForEntity(eq(TYPE_SAVE), any(ParameterizedTypeReference.class), any())).thenThrow(counter(HttpStatus.CONFLICT, "QUANTITY_BELOW_HELD"));
assertCoded(() -> service.saveType(ev, "2", new AdminTicketService.TypeBody("General", 25000, 1, null, 0, true)),
HttpStatus.CONFLICT, "QUANTITY_BELOW_HELD");
}
@Test
void typesAreListedSavedAndDeletedForTheEvent() {
when(rest.postForEntity(eq(TYPES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(Map.of("id", 2))));
assertThat(service.types(ev)).hasSize(1);
assertThat(sent(TYPES)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV);
service.saveType(ev, "2", new AdminTicketService.TypeBody("General", 25000, 100, "2027-01-10", 1, true));
assertThat(sent(TYPE_SAVE)).containsEntry("id", 2L).containsEntry("name", "General").containsEntry("priceSen", 25000)
.containsEntry("quantity", 100).containsEntry("salesEndDate", "2027-01-10").containsEntry("doneBy", "finance1");
service.deleteType(ev, "2");
assertThat(sent(TYPE_DELETE)).containsEntry("id", 2L).containsEntry("doneBy", "finance1");
}
@Test
void aBadSalesEndDateIsRefusedHere() {
assertCoded(() -> service.saveType(ev, null, new AdminTicketService.TypeBody("General", 25000, 100, "10/01/2027", 1, true)),
HttpStatus.BAD_REQUEST, "DATE_INVALID");
verify(rest, never()).postForEntity(eq(TYPE_SAVE), any(ParameterizedTypeReference.class), any());
}
@Test
void ordersAreListedFiftyAPageWithTheFilter() {
service.orders(ev, "AWAITING", "aisyah", 2);
assertThat(sent(ORDERS)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("status", "AWAITING")
.containsEntry("q", "aisyah").containsEntry("page", 2).containsEntry("size", 50);
}
@Test
void orderActionsCarryTheEventTheOrderAndTheCaller() {
service.order(ev, "300");
assertThat(sent(ORDER)).containsEntry("eventUuid", EV).containsEntry("orderId", 300L);
service.markPaid(ev, "300", new AdminTicketService.PayBody("MBB 0412 883"));
assertThat(sent(PAID)).containsEntry("orderId", 300L).containsEntry("paymentRef", "MBB 0412 883").containsEntry("doneBy", "finance1");
service.cancel(ev, "300");
assertThat(sent(CANCEL)).containsEntry("orderId", 300L).containsEntry("doneBy", "finance1");
service.cancelTicket(ev, "300", "7");
assertThat(sent(CANCEL_TICKET)).containsEntry("ticketId", 7L).containsEntry("doneBy", "finance1");
service.resend(ev, "300");
assertThat(sent(RESEND)).containsEntry("orderId", 300L);
}
@Test
void anUnknownOrderIsNotFound() {
assertCoded(() -> service.order(ev, "abc"), HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND");
when(rest.postForEntity(eq(ORDER), any(ParameterizedTypeReference.class), any())).thenThrow(counter(HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND"));
assertCoded(() -> service.order(ev, "301"), HttpStatus.NOT_FOUND, "ORDER_NOT_FOUND");
}
@Test
void seatsGoneIsAConflict() {
when(rest.postForEntity(eq(PAID), any(ParameterizedTypeReference.class), any())).thenThrow(counter(HttpStatus.CONFLICT, "SEATS_GONE"));
assertCoded(() -> service.markPaid(ev, "300", null), HttpStatus.CONFLICT, "SEATS_GONE");
}
}