diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 29366f6..16c33f4 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -523,3 +523,106 @@ ALTER TABLE `notification` -- add-page-drafts-and-templates: a published page's unpublished draft USE `service-counter`; ALTER TABLE `cms_page` ADD COLUMN `draft` json NULL COMMENT 'Unpublished changes of a published page: slug, title, metaDescription, hideHeader, blocks' AFTER `blocks`; +-- add-event-ticket-orders/sql/01-event-ticket-orders.sql +USE `service-counter`; + +ALTER TABLE `event` + ADD COLUMN `tickets_enabled` tinyint(1) NOT NULL DEFAULT 0, + ADD COLUMN `payment_instructions` varchar(1000) NULL, + ADD COLUMN `hold_days` int NOT NULL DEFAULT 3; + +CREATE TABLE IF NOT EXISTS `ticket_type` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `event_uuid` bigint NOT NULL, + `name` varchar(80) NOT NULL, + `price_sen` int NOT NULL, + `quantity` int NOT NULL, + `sales_end_date` date NULL, + `sort` int NOT NULL DEFAULT 0, + `enabled` tinyint(1) NOT NULL DEFAULT 1, + `created_by` varchar(255) NULL, + `created_at` datetime NULL DEFAULT CURRENT_TIMESTAMP, + `updated_by` varchar(255) NULL, + `updated_at` datetime NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_ticket_type_name` (`event_uuid`, `name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS `shop_order` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `event_uuid` bigint NULL COMMENT 'Null is reserved for a later standalone shop', + `reference` varchar(12) NOT NULL, + `token` varchar(32) NOT NULL, + `buyer_name` varchar(100) NOT NULL, + `buyer_email` varchar(254) NOT NULL, + `buyer_mobile_e164` varchar(20) NULL, + `buyer_company` varchar(150) NULL, + `lead_uuid` bigint NULL, + `event_lead_uuid` bigint NULL, + `status` varchar(20) NOT NULL COMMENT 'AWAITING, PAID, CANCELLED, EXPIRED', + `total_sen` int NOT NULL, + `hold_until` datetime NULL, + `paid_at` datetime NULL, + `paid_by` varchar(255) NULL, + `payment_ref` varchar(100) NULL, + `cancelled_at` datetime NULL, + `cancelled_by` varchar(255) NULL, + `expired_at` datetime NULL, + `consent_at` datetime NULL, + `consent_notice_id` bigint NULL, + `page_path` varchar(200) NULL, + `utm_source` varchar(100) NULL, + `utm_medium` varchar(100) NULL, + `utm_campaign` varchar(100) NULL, + `last_email` varchar(20) NULL COMMENT 'RECEIVED, PAID, EXPIRED, CANCELLED', + `created_at` datetime NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_shop_order_reference` (`company_id`, `reference`), + UNIQUE KEY `uk_shop_order_token` (`token`), + KEY `idx_shop_order_event_status` (`event_uuid`, `status`), + KEY `idx_shop_order_hold` (`status`, `hold_until`), + KEY `idx_shop_order_buyer` (`event_uuid`, `buyer_email`, `status`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS `shop_order_line` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `order_id` bigint NOT NULL, + `kind` varchar(10) NOT NULL COMMENT 'TICKET; PICKUP and SHIP reserved for merch', + `item_id` bigint NOT NULL COMMENT 'ticket_type.id for TICKET', + `name` varchar(80) NOT NULL, + `unit_price_sen` int NOT NULL, + `quantity` int NOT NULL, + PRIMARY KEY (`id`), + KEY `idx_shop_order_line_order` (`order_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS `ticket` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `event_uuid` bigint NOT NULL, + `order_id` bigint NOT NULL, + `order_line_id` bigint NOT NULL, + `ticket_type_id` bigint NOT NULL, + `code` varchar(32) NULL COMMENT 'QR code, issued by add-event-tickets', + `attendee_name` varchar(100) NULL, + `attendee_mobile_e164` varchar(20) NULL, + `attendee_email` varchar(254) NULL, + `event_lead_uuid` bigint NULL, + `status` varchar(10) NOT NULL DEFAULT 'ACTIVE' COMMENT 'ACTIVE, CANCELLED', + `cancelled_at` datetime NULL, + `cancelled_by` varchar(255) NULL, + `checked_in_at` datetime NULL, + `checked_in_by` varchar(255) NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_ticket_code` (`code`), + KEY `idx_ticket_type_status` (`ticket_type_id`, `status`), + KEY `idx_ticket_order` (`order_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- add-event-ticket-orders/sql/02-event-tickets-module.sql +USE `service-system`; + +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (41160000, 'BO_EVENT_TICKETS', 'Event tickets', 'BO', 'M', 40000000, NULL, NULL); diff --git a/openspec/changes/add-event-ticket-orders/design.md b/openspec/changes/add-event-ticket-orders/design.md index f2861cf..e1701e3 100644 --- a/openspec/changes/add-event-ticket-orders/design.md +++ b/openspec/changes/add-event-ticket-orders/design.md @@ -100,7 +100,8 @@ Staff "mark paid" on an Expired order, and a type's quantity edit, take the same All take JSON. `companyId` is always concrete and is set by mobile-api. - **Settings:** - - `POST /counter/event/save` accepts `ticketsEnabled`, `paymentInstructions` and `holdDays`. It returns 400 on the field when switching on with blank instructions or when hold days are outside 1 to 14. mobile-api passes these only for callers with `BO_EVENT_TICKETS`. + - `POST /counter/ticketType/settings {companyId, eventUuid, ticketsEnabled, paymentInstructions, holdDays, doneBy}`. It returns 400 `PAYMENT_INSTRUCTIONS_REQUIRED`, `PAYMENT_INSTRUCTIONS_TOO_LONG` or `HOLD_DAYS_INVALID`. + - `event/save` keeps the stored ticket settings on every edit, and starts a new event with tickets off. This is so a mobile-api event edit, which round-trips the whole event, can never reset them. - **Ticket types:** - `POST /counter/ticketType/list {companyId, eventUuid}` returns `[{id, name, priceSen, quantity, salesEndDate, sort, enabled, held, left}]`. - `POST /counter/ticketType/save {companyId, eventUuid, id?, name, priceSen, quantity, salesEndDate, sort, enabled, doneBy}` returns 409 `QUANTITY_BELOW_HELD` or `NAME_TAKEN`. @@ -191,7 +192,12 @@ All take JSON. `companyId` is always concrete and is set by mobile-api. ## Risks / Trade-offs -- **Event row lock under a rush.** Requests for one event are serialised. That is fine at the expected volume (tens per minute). If a big launch needs more, move to per-type locks. +- **Event row lock under a rush.** Requests for one event are serialised. That is fine at the expected volume (hundreds per minute). The upgrade path was agreed with the owner on 2026-12-04: + 1. A conditional single-statement seat update (`... WHERE held + n <= quantity`), with no event lock. + 2. Then a Redis seat counter backed by the database, a CDN-cached event page, a CAPTCHA and a load test. + 3. At concert scale: a virtual waiting room, queued order allocation, member-only sales, and ticketing as its own service. + + Seats are counted from `ticket` rows on one table, so step 1 is a local change. - **Seat hoarding.** One email can hold up to 30 seats (3 orders × 10) for the hold days, and many emails can hold more. This is mitigated by the IP limit, the honeypot and staff cancel. A CAPTCHA is deferred. - **Emails in English and BM only,** matching invites. The zh-CN email text is deferred with the rest of the email localisation. - **Expired orders may still be paid.** Staff can rescue them only while their seats are free. This is refused clearly otherwise. diff --git a/openspec/changes/add-event-ticket-orders/sql/01-event-ticket-orders.sql b/openspec/changes/add-event-ticket-orders/sql/01-event-ticket-orders.sql new file mode 100644 index 0000000..2da2cc8 --- /dev/null +++ b/openspec/changes/add-event-ticket-orders/sql/01-event-ticket-orders.sql @@ -0,0 +1,99 @@ +-- Co-Lite change add-event-ticket-orders: ticket settings, ticket types, orders and tickets (design decision 1). +-- Target: `service-counter`. Additive only. Run before the new images go live. Needs a user that may alter tables. +-- Money is integer sen. `shop_order` / `shop_order_line` stay apart from the legacy Tastefully `orders` tables. +USE `service-counter`; + +ALTER TABLE `event` + ADD COLUMN `tickets_enabled` tinyint(1) NOT NULL DEFAULT 0, + ADD COLUMN `payment_instructions` varchar(1000) NULL, + ADD COLUMN `hold_days` int NOT NULL DEFAULT 3; + +CREATE TABLE IF NOT EXISTS `ticket_type` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `event_uuid` bigint NOT NULL, + `name` varchar(80) NOT NULL, + `price_sen` int NOT NULL, + `quantity` int NOT NULL, + `sales_end_date` date NULL, + `sort` int NOT NULL DEFAULT 0, + `enabled` tinyint(1) NOT NULL DEFAULT 1, + `created_by` varchar(255) NULL, + `created_at` datetime NULL DEFAULT CURRENT_TIMESTAMP, + `updated_by` varchar(255) NULL, + `updated_at` datetime NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_ticket_type_name` (`event_uuid`, `name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS `shop_order` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `event_uuid` bigint NULL COMMENT 'Null is reserved for a later standalone shop', + `reference` varchar(12) NOT NULL, + `token` varchar(32) NOT NULL, + `buyer_name` varchar(100) NOT NULL, + `buyer_email` varchar(254) NOT NULL, + `buyer_mobile_e164` varchar(20) NULL, + `buyer_company` varchar(150) NULL, + `lead_uuid` bigint NULL, + `event_lead_uuid` bigint NULL, + `status` varchar(20) NOT NULL COMMENT 'AWAITING, PAID, CANCELLED, EXPIRED', + `total_sen` int NOT NULL, + `hold_until` datetime NULL, + `paid_at` datetime NULL, + `paid_by` varchar(255) NULL, + `payment_ref` varchar(100) NULL, + `cancelled_at` datetime NULL, + `cancelled_by` varchar(255) NULL, + `expired_at` datetime NULL, + `consent_at` datetime NULL, + `consent_notice_id` bigint NULL, + `page_path` varchar(200) NULL, + `utm_source` varchar(100) NULL, + `utm_medium` varchar(100) NULL, + `utm_campaign` varchar(100) NULL, + `last_email` varchar(20) NULL COMMENT 'RECEIVED, PAID, EXPIRED, CANCELLED', + `created_at` datetime NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_shop_order_reference` (`company_id`, `reference`), + UNIQUE KEY `uk_shop_order_token` (`token`), + KEY `idx_shop_order_event_status` (`event_uuid`, `status`), + KEY `idx_shop_order_hold` (`status`, `hold_until`), + KEY `idx_shop_order_buyer` (`event_uuid`, `buyer_email`, `status`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS `shop_order_line` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `order_id` bigint NOT NULL, + `kind` varchar(10) NOT NULL COMMENT 'TICKET; PICKUP and SHIP reserved for merch', + `item_id` bigint NOT NULL COMMENT 'ticket_type.id for TICKET', + `name` varchar(80) NOT NULL, + `unit_price_sen` int NOT NULL, + `quantity` int NOT NULL, + PRIMARY KEY (`id`), + KEY `idx_shop_order_line_order` (`order_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS `ticket` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `event_uuid` bigint NOT NULL, + `order_id` bigint NOT NULL, + `order_line_id` bigint NOT NULL, + `ticket_type_id` bigint NOT NULL, + `code` varchar(32) NULL COMMENT 'QR code, issued by add-event-tickets', + `attendee_name` varchar(100) NULL, + `attendee_mobile_e164` varchar(20) NULL, + `attendee_email` varchar(254) NULL, + `event_lead_uuid` bigint NULL, + `status` varchar(10) NOT NULL DEFAULT 'ACTIVE' COMMENT 'ACTIVE, CANCELLED', + `cancelled_at` datetime NULL, + `cancelled_by` varchar(255) NULL, + `checked_in_at` datetime NULL, + `checked_in_by` varchar(255) NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_ticket_code` (`code`), + KEY `idx_ticket_type_status` (`ticket_type_id`, `status`), + KEY `idx_ticket_order` (`order_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/openspec/changes/add-event-ticket-orders/sql/02-event-tickets-module.sql b/openspec/changes/add-event-ticket-orders/sql/02-event-tickets-module.sql new file mode 100644 index 0000000..d589bd2 --- /dev/null +++ b/openspec/changes/add-event-ticket-orders/sql/02-event-tickets-module.sql @@ -0,0 +1,6 @@ +-- Co-Lite change add-event-ticket-orders: permission-only module for ticket settings, ticket types and orders. +-- Target: `service-system`. No role gets it by default; a super admin grants it under Roles. +USE `service-system`; + +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (41160000, 'BO_EVENT_TICKETS', 'Event tickets', 'BO', 'M', 40000000, NULL, NULL); diff --git a/openspec/changes/add-event-ticket-orders/sql/99-rollback.sql b/openspec/changes/add-event-ticket-orders/sql/99-rollback.sql new file mode 100644 index 0000000..3e72bc1 --- /dev/null +++ b/openspec/changes/add-event-ticket-orders/sql/99-rollback.sql @@ -0,0 +1,11 @@ +-- Co-Lite change add-event-ticket-orders: rollback. Drops every ticket order and ticket. Run only to remove the data too. +USE `service-counter`; +DROP TABLE IF EXISTS `ticket`; +DROP TABLE IF EXISTS `shop_order_line`; +DROP TABLE IF EXISTS `shop_order`; +DROP TABLE IF EXISTS `ticket_type`; +ALTER TABLE `event` DROP COLUMN `tickets_enabled`, DROP COLUMN `payment_instructions`, DROP COLUMN `hold_days`; + +USE `service-system`; +DELETE FROM `modules_roles` WHERE `module_id` = 41160000; +DELETE FROM `module` WHERE `id` = 41160000; diff --git a/openspec/changes/add-event-ticket-orders/tasks.md b/openspec/changes/add-event-ticket-orders/tasks.md index 55e0e18..92d8a12 100644 --- a/openspec/changes/add-event-ticket-orders/tasks.md +++ b/openspec/changes/add-event-ticket-orders/tasks.md @@ -6,7 +6,7 @@ Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-04 ## 1. Data -- [ ] 1.1 Write the SQL: +- [x] 1.1 Write the SQL: - `sql/01-event-ticket-orders.sql`: the event columns, `ticket_type`, `shop_order`, `shop_order_line` and `ticket`; - `sql/02-event-tickets-module.sql`: `BO_EVENT_TICKETS`; - `sql/99-rollback.sql`. @@ -18,11 +18,11 @@ Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-04 ## 2. services-counter -- [ ] 2.1 Ticket entities, settings and ticket types. +- [x] 2.1 Ticket entities, settings and ticket types. - Depends on: 1.1 - Tests first: - **Entities:** they map to the DDL. - - **Event save:** + - **Ticket settings** (own endpoint `ticketType/settings`; an event edit keeps the stored settings): - switching on with blank instructions is refused on the field; - hold days 0 or 15 are refused; - a valid save persists. @@ -48,7 +48,7 @@ Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-04 - **Capacity:** - before the event days, guests plus walk-ins plus held tickets over capacity gives `EVENT_FULL` with `left`; - on the event days it does not. - - **Concurrency:** two threads request the last seat; exactly one order is created (integration test on the real lock). + - **Concurrency:** the unit test proves the event lock is taken before seats are counted. The module has no test database, and adding H2 or Testcontainers would be a new dependency for one test. So the real lock and the JPQL are checked against the local MySQL stack in 5.1: the counter boots, which validates the queries, and two parallel requests race for the last seat. - **Buyer lead:** - a new buyer gets an event lead with source `TICKET` and the UTM values; - a buyer already captured keeps the old source and gets a note naming the reference. diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/TicketTypeController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/TicketTypeController.java new file mode 100644 index 0000000..4829a23 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/TicketTypeController.java @@ -0,0 +1,51 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.service.EventService; +import com.solvway.services.counter.service.TicketTypeService; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** Ticket settings and types (add-event-ticket-orders). onSale is the only public path. */ +@RestController +@RequestMapping("/counter/ticketType") +@AllArgsConstructor +public class TicketTypeController { + private final TicketTypeService service; + private final EventService eventService; + + @PostMapping("/settings") + public Map settings(@RequestBody EventService.TicketSettingsRequest req) { + Event e = eventService.ticketSettings(req); + return Map.of("ticketsEnabled", e.isTicketsEnabled(), "paymentInstructions", e.getPaymentInstructions() == null ? "" : e.getPaymentInstructions(), + "holdDays", e.getHoldDays()); + } + + @PostMapping("/list") + public List list(@RequestBody TicketTypeService.ListRequest req) { + return service.list(req); + } + + @PostMapping("/save") + public TicketTypeService.TypeRow save(@RequestBody TicketTypeService.SaveRequest req) { + return service.save(req); + } + + @PostMapping("/delete") + public void delete(@RequestBody TicketTypeService.DeleteRequest req) { + service.delete(req); + } + + @GetMapping("/onSale/{eventUuid}") + public TicketTypeService.OnSale onSale(@PathVariable("eventUuid") long eventUuid) { + return service.onSale(eventUuid); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java index 68c4b05..6ceb03d 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java @@ -28,6 +28,13 @@ public class Event implements Serializable { private Integer invitationCap; @Column(name = "checkin_token", updatable = false) private String checkinToken; + /** Ticket settings (add-event-ticket-orders): changed only through EventService.ticketSettings. */ + @Column(name = "tickets_enabled") + private boolean ticketsEnabled = false; + @Column(name = "payment_instructions") + private String paymentInstructions; + @Column(name = "hold_days") + private int holdDays = 3; private String uploadFloorPlan; private String uploadStageActivities; private String uploadLuckyDraw; diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/ShopOrder.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/ShopOrder.java new file mode 100644 index 0000000..ad36434 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/ShopOrder.java @@ -0,0 +1,107 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +/** An order of a buyer: ticket lines now, merch lines later (add-event-ticket-orders). Money in sen. */ +@Getter +@Setter +@Entity +@Table(name = "shop_order", uniqueConstraints = { + @UniqueConstraint(columnNames = {"company_id", "reference"}), + @UniqueConstraint(columnNames = {"token"}) +}) +public class ShopOrder { + public static final String AWAITING = "AWAITING"; + public static final String PAID = "PAID"; + public static final String CANCELLED = "CANCELLED"; + public static final String EXPIRED = "EXPIRED"; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "company_id") + private long companyId; + + @Column(name = "event_uuid") + private Long eventUuid; + + @Column(name = "reference") + private String reference; + + @Column(name = "token", length = 32) + private String token; + + @Column(name = "buyer_name") + private String buyerName; + + @Column(name = "buyer_email") + private String buyerEmail; + + @Column(name = "buyer_mobile_e164") + private String buyerMobileE164; + + @Column(name = "buyer_company") + private String buyerCompany; + + @Column(name = "lead_uuid") + private Long leadUuid; + + @Column(name = "event_lead_uuid") + private Long eventLeadUuid; + + @Column(name = "status") + private String status; + + @Column(name = "total_sen") + private int totalSen; + + @Column(name = "hold_until") + private LocalDateTime holdUntil; + + @Column(name = "paid_at") + private LocalDateTime paidAt; + + @Column(name = "paid_by") + private String paidBy; + + @Column(name = "payment_ref") + private String paymentRef; + + @Column(name = "cancelled_at") + private LocalDateTime cancelledAt; + + @Column(name = "cancelled_by") + private String cancelledBy; + + @Column(name = "expired_at") + private LocalDateTime expiredAt; + + @Column(name = "consent_at") + private LocalDateTime consentAt; + + @Column(name = "consent_notice_id") + private Long consentNoticeId; + + @Column(name = "page_path") + private String pagePath; + + @Column(name = "utm_source") + private String utmSource; + + @Column(name = "utm_medium") + private String utmMedium; + + @Column(name = "utm_campaign") + private String utmCampaign; + + @Column(name = "last_email") + private String lastEmail; + + @Column(name = "created_at", updatable = false) + private LocalDateTime createdAt; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/ShopOrderLine.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/ShopOrderLine.java new file mode 100644 index 0000000..2997cdf --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/ShopOrderLine.java @@ -0,0 +1,36 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +/** One line of an order, keeping the item's name and price at the time (add-event-ticket-orders). */ +@Getter +@Setter +@Entity +@Table(name = "shop_order_line") +public class ShopOrderLine { + public static final String TICKET = "TICKET"; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "order_id") + private long orderId; + + @Column(name = "kind") + private String kind; + + @Column(name = "item_id") + private long itemId; + + @Column(name = "name") + private String name; + + @Column(name = "unit_price_sen") + private int unitPriceSen; + + @Column(name = "quantity") + private int quantity; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Ticket.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Ticket.java new file mode 100644 index 0000000..1e5af2c --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Ticket.java @@ -0,0 +1,66 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +/** One seat of an order. The code, attendee and check-in columns are filled by add-event-tickets. */ +@Getter +@Setter +@Entity +@Table(name = "ticket") +public class Ticket { + public static final String ACTIVE = "ACTIVE"; + public static final String CANCELLED = "CANCELLED"; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "company_id") + private long companyId; + + @Column(name = "event_uuid") + private long eventUuid; + + @Column(name = "order_id") + private long orderId; + + @Column(name = "order_line_id") + private long orderLineId; + + @Column(name = "ticket_type_id") + private long ticketTypeId; + + @Column(name = "code", length = 32) + private String code; + + @Column(name = "attendee_name") + private String attendeeName; + + @Column(name = "attendee_mobile_e164") + private String attendeeMobileE164; + + @Column(name = "attendee_email") + private String attendeeEmail; + + @Column(name = "event_lead_uuid") + private Long eventLeadUuid; + + @Column(name = "status") + private String status = ACTIVE; + + @Column(name = "cancelled_at") + private LocalDateTime cancelledAt; + + @Column(name = "cancelled_by") + private String cancelledBy; + + @Column(name = "checked_in_at") + private LocalDateTime checkedInAt; + + @Column(name = "checked_in_by") + private String checkedInBy; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/TicketType.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/TicketType.java new file mode 100644 index 0000000..c7fb5fd --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/TicketType.java @@ -0,0 +1,55 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** A kind of ticket an event sells (add-event-ticket-orders). Price in sen. */ +@Getter +@Setter +@Entity +@Table(name = "ticket_type", uniqueConstraints = @UniqueConstraint(columnNames = {"event_uuid", "name"})) +public class TicketType { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "company_id") + private long companyId; + + @Column(name = "event_uuid") + private long eventUuid; + + @Column(name = "name") + private String name; + + @Column(name = "price_sen") + private int priceSen; + + @Column(name = "quantity") + private int quantity; + + @Column(name = "sales_end_date") + private LocalDate salesEndDate; + + @Column(name = "sort") + private int sort; + + @Column(name = "enabled") + private boolean enabled = true; + + @Column(name = "created_by", updatable = false) + private String createdBy; + + @Column(name = "created_at", updatable = false) + private LocalDateTime createdAt = LocalDateTime.now(); + + @Column(name = "updated_by") + private String updatedBy; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java index 4866b33..7c562d5 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepository.java @@ -18,6 +18,11 @@ public interface EventRepository extends JpaRepository , JpaReposito Optional findByUuid(long uuid); Optional findByCheckinToken(String checkinToken); + /** Locks the event row for the rest of the transaction: ticket requests and seat changes of one event run one at a time. */ + @org.springframework.data.jpa.repository.Lock(jakarta.persistence.LockModeType.PESSIMISTIC_WRITE) + @Query("SELECT e FROM Event e WHERE e.uuid = :uuid") + Optional lockByUuid(@Param("uuid") long uuid); + /** Sets the check-in token only while none exists; returns rows changed. Atomic, so concurrent callers agree on one token. */ @Modifying(clearAutomatically = true) @Transactional diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/ShopOrderLineRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/ShopOrderLineRepository.java new file mode 100644 index 0000000..e6e7d8a --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/ShopOrderLineRepository.java @@ -0,0 +1,14 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.ShopOrderLine; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface ShopOrderLineRepository extends JpaRepository { + boolean existsByKindAndItemId(String kind, long itemId); + + List findByOrderIdOrderByIdAsc(long orderId); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/ShopOrderRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/ShopOrderRepository.java new file mode 100644 index 0000000..d6d6da1 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/ShopOrderRepository.java @@ -0,0 +1,12 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.ShopOrder; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface ShopOrderRepository extends JpaRepository { + Optional findByToken(String token); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketHeld.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketHeld.java new file mode 100644 index 0000000..5077e94 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketHeld.java @@ -0,0 +1,4 @@ +package com.solvway.services.counter.repo; + +/** Seats a ticket type holds: active tickets of orders awaiting payment or paid. */ +public record TicketHeld(Long typeId, Long held) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketRepository.java new file mode 100644 index 0000000..c2c4ca5 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketRepository.java @@ -0,0 +1,20 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.Ticket; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface TicketRepository extends JpaRepository { + /** Held seats per ticket type of an event: one grouped count, so it never drifts. */ + @Query("select new com.solvway.services.counter.repo.TicketHeld(t.ticketTypeId, count(t)) from Ticket t, ShopOrder o" + + " where o.id = t.orderId and t.eventUuid = :eventUuid and t.status = 'ACTIVE' and o.status in ('AWAITING', 'PAID')" + + " group by t.ticketTypeId") + List heldByType(@Param("eventUuid") long eventUuid); + + List findByOrderIdOrderByIdAsc(long orderId); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketTypeRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketTypeRepository.java new file mode 100644 index 0000000..1053691 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/TicketTypeRepository.java @@ -0,0 +1,15 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.model.TicketType; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface TicketTypeRepository extends JpaRepository { + List findByEventUuidOrderBySortAscIdAsc(long eventUuid); + + Optional findByEventUuidAndName(long eventUuid, String name); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java index 248302f..ce6a7c4 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java @@ -50,11 +50,17 @@ public class EventService { if (event.getInvitationCap() != null && event.getInvitationCap() < 1) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVITATION_CAP_INVALID"); if (event.getId() == null) { if (event.getCompanyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); + event.setTicketsEnabled(false); // ticket settings change only through ticketSettings + event.setPaymentInstructions(null); + event.setHoldDays(3); } else { // company is immutable: always carry the stored one so entity and cache match the DB Optional stored = eventRepository.findById(event.getId()); if (stored.isPresent()) { event.setCompanyId(stored.get().getCompanyId()); + event.setTicketsEnabled(stored.get().isTicketsEnabled()); + event.setPaymentInstructions(stored.get().getPaymentInstructions()); + event.setHoldDays(stored.get().getHoldDays()); if (event.getInvitationCap() != null && guestRepository != null && guestRepository.countByEventUuid(stored.get().getUuid()) > event.getInvitationCap()) { throw new ResponseStatusException(HttpStatus.CONFLICT, "CAP_BELOW_GUESTS"); @@ -65,6 +71,28 @@ public class EventService { updateEventCache(event); return event; } + public record TicketSettingsRequest(Long companyId, long eventUuid, boolean ticketsEnabled, String paymentInstructions, + Integer holdDays, String doneBy) {} + + /** Tickets switch, payment instructions and hold days; the only way they change. */ + @Transactional + public Event ticketSettings(TicketSettingsRequest r) { + Event event = eventRepository.findByUuid(r.eventUuid()) + .filter(e -> r.companyId() != null && r.companyId().equals(e.getCompanyId())) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND")); + String text = r.paymentInstructions() == null ? "" : r.paymentInstructions().strip(); + if (r.ticketsEnabled() && text.isEmpty()) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "PAYMENT_INSTRUCTIONS_REQUIRED"); + if (text.length() > 1000) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "PAYMENT_INSTRUCTIONS_TOO_LONG"); + if (r.holdDays() == null || r.holdDays() < 1 || r.holdDays() > 14) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "HOLD_DAYS_INVALID"); + event.setTicketsEnabled(r.ticketsEnabled()); + event.setPaymentInstructions(text.isEmpty() ? null : text); + event.setHoldDays(r.holdDays()); + event.setDoneBy(r.doneBy()); + event = eventRepository.save(event); + updateEventCache(event); + return event; + } + public List findAll(){ return eventRepository.findAll(); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketTypeService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketTypeService.java new file mode 100644 index 0000000..d04d47b --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/TicketTypeService.java @@ -0,0 +1,142 @@ +package com.solvway.services.counter.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.ShopOrderLine; +import com.solvway.services.counter.model.TicketType; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.ShopOrderLineRepository; +import com.solvway.services.counter.repo.TicketHeld; +import com.solvway.services.counter.repo.TicketRepository; +import com.solvway.services.counter.repo.TicketTypeRepository; +import lombok.AllArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** Ticket types of an event, their held seats, and the public on-sale view (add-event-ticket-orders). */ +@Service +@AllArgsConstructor +public class TicketTypeService { + static final ZoneId MALAYSIA = ZoneId.of("Asia/Kuala_Lumpur"); + private static final int MAX_PRICE_SEN = 9_999_999; + + private final EventRepository events; + private final TicketTypeRepository types; + private final TicketRepository tickets; + private final ShopOrderLineRepository lines; + + public record ListRequest(Long companyId, long eventUuid) {} + + public record TypeRow(Long id, String name, int priceSen, int quantity, LocalDate salesEndDate, int sort, boolean enabled, + long held, long left) {} + + public record SaveRequest(Long companyId, long eventUuid, Long id, String name, Integer priceSen, Integer quantity, + LocalDate salesEndDate, Integer sort, Boolean enabled, String doneBy) {} + + public record DeleteRequest(Long companyId, long eventUuid, Long id, String doneBy) {} + + public record PublicType(Long id, String name, int priceSen, long left, String state) {} + + public record OnSale(boolean ticketsOpen, String paymentInstructions, List types) {} + + public List list(ListRequest r) { + event(r.companyId(), r.eventUuid(), false); + Map held = held(r.eventUuid()); + return types.findByEventUuidOrderBySortAscIdAsc(r.eventUuid()).stream().map(t -> row(t, held)).toList(); + } + + @Transactional + public TypeRow save(SaveRequest r) { + Event event = event(r.companyId(), r.eventUuid(), true); // seat changes run one at a time per event + String name = r.name() == null ? "" : r.name().strip(); + if (name.isEmpty() || name.length() > 80) throw status(HttpStatus.BAD_REQUEST, "NAME_INVALID"); + if (r.priceSen() == null || r.priceSen() < 0 || r.priceSen() > MAX_PRICE_SEN) throw status(HttpStatus.BAD_REQUEST, "PRICE_INVALID"); + if (r.quantity() == null || r.quantity() < 1) throw status(HttpStatus.BAD_REQUEST, "QUANTITY_INVALID"); + TicketType t = r.id() == null ? new TicketType() : types.findById(r.id()) + .filter(x -> x.getEventUuid() == event.getUuid()) + .orElseThrow(() -> status(HttpStatus.NOT_FOUND, "TYPE_NOT_FOUND")); + types.findByEventUuidAndName(event.getUuid(), name) + .filter(other -> !other.getId().equals(t.getId())) + .ifPresent(other -> { throw status(HttpStatus.CONFLICT, "NAME_TAKEN"); }); + Map held = held(event.getUuid()); + if (t.getId() != null && r.quantity() < held.getOrDefault(t.getId(), 0L)) throw status(HttpStatus.CONFLICT, "QUANTITY_BELOW_HELD"); + if (t.getId() == null) { + t.setCompanyId(event.getCompanyId()); + t.setEventUuid(event.getUuid()); + t.setCreatedBy(r.doneBy()); + } else { + t.setUpdatedBy(r.doneBy()); + t.setUpdatedAt(LocalDateTime.now()); + } + t.setName(name); + t.setPriceSen(r.priceSen()); + t.setQuantity(r.quantity()); + t.setSalesEndDate(r.salesEndDate()); + t.setSort(r.sort() == null ? 0 : r.sort()); + t.setEnabled(r.enabled() == null || r.enabled()); + return row(types.save(t), held); + } + + @Transactional + public void delete(DeleteRequest r) { + Event event = event(r.companyId(), r.eventUuid(), true); + TicketType t = types.findById(r.id()).filter(x -> x.getEventUuid() == event.getUuid()) + .orElseThrow(() -> status(HttpStatus.NOT_FOUND, "TYPE_NOT_FOUND")); + if (lines.existsByKindAndItemId(ShopOrderLine.TICKET, t.getId())) throw status(HttpStatus.CONFLICT, "TYPE_HAS_ORDERS"); + types.delete(t); + } + + /** What a visitor may see: enabled types only, no company data. */ + public OnSale onSale(long eventUuid) { + Event event = events.findByUuid(eventUuid).orElseThrow(() -> status(HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND")); + LocalDate today = LocalDate.now(MALAYSIA); + Map held = held(eventUuid); + List shown = types.findByEventUuidOrderBySortAscIdAsc(eventUuid).stream().filter(TicketType::isEnabled).map(t -> { + long left = Math.max(0, t.getQuantity() - held.getOrDefault(t.getId(), 0L)); + String state = salesEnded(t, event, today) ? "ENDED" : left == 0 ? "SOLD_OUT" : "ON_SALE"; + return new PublicType(t.getId(), t.getName(), t.getPriceSen(), left, state); + }).toList(); + return new OnSale(ticketsOpen(event, today), event.getPaymentInstructions(), shown); + } + + static boolean ticketsOpen(Event event, LocalDate today) { + return event.isTicketsEnabled() && event.getEnabled() == GeneralEnum.FlagYesNo.Y + && event.getDateEnd() != null && !today.isAfter(event.getDateEnd().toLocalDate()); + } + + /** A type's sales end on its own date, else on the event's last day. */ + static boolean salesEnded(TicketType t, Event event, LocalDate today) { + LocalDate end = t.getSalesEndDate() != null ? t.getSalesEndDate() + : event.getDateEnd() == null ? null : event.getDateEnd().toLocalDate(); + return end == null || today.isAfter(end); + } + + Map held(long eventUuid) { + return tickets.heldByType(eventUuid).stream().collect(Collectors.toMap(TicketHeld::typeId, TicketHeld::held)); + } + + private Event event(Long companyId, long eventUuid, boolean lock) { + return (lock ? events.lockByUuid(eventUuid) : events.findByUuid(eventUuid)) + .filter(e -> companyId != null && companyId.equals(e.getCompanyId())) + .orElseThrow(() -> status(HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND")); + } + + private static TypeRow row(TicketType t, Map held) { + long h = held.getOrDefault(t.getId(), 0L); + return new TypeRow(t.getId(), t.getName(), t.getPriceSen(), t.getQuantity(), t.getSalesEndDate(), t.getSort(), t.isEnabled(), + h, Math.max(0, t.getQuantity() - h)); + } + + static ResponseStatusException status(HttpStatus s, String reason) { + return new ResponseStatusException(s, reason); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/model/TicketMappingTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/model/TicketMappingTest.java new file mode 100644 index 0000000..8f45f73 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/model/TicketMappingTest.java @@ -0,0 +1,57 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Table; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** add-event-ticket-orders: the entities map 01-event-ticket-orders.sql. */ +class TicketMappingTest { + @Test + void tables() { + assertThat(TicketType.class.getAnnotation(Table.class).name()).isEqualTo("ticket_type"); + assertThat(ShopOrder.class.getAnnotation(Table.class).name()).isEqualTo("shop_order"); + assertThat(ShopOrderLine.class.getAnnotation(Table.class).name()).isEqualTo("shop_order_line"); + assertThat(Ticket.class.getAnnotation(Table.class).name()).isEqualTo("ticket"); + assertThat(uniques(TicketType.class)).containsExactly(List.of("event_uuid", "name")); + assertThat(uniques(ShopOrder.class)).containsExactlyInAnyOrder(List.of("company_id", "reference"), List.of("token")); + } + + @Test + void columns() throws Exception { + assertThat(column(TicketType.class, "priceSen")).isEqualTo("price_sen"); + assertThat(column(TicketType.class, "salesEndDate")).isEqualTo("sales_end_date"); + assertThat(column(ShopOrder.class, "buyerMobileE164")).isEqualTo("buyer_mobile_e164"); + assertThat(column(ShopOrder.class, "eventLeadUuid")).isEqualTo("event_lead_uuid"); + assertThat(column(ShopOrder.class, "holdUntil")).isEqualTo("hold_until"); + assertThat(column(ShopOrder.class, "consentNoticeId")).isEqualTo("consent_notice_id"); + assertThat(column(ShopOrderLine.class, "unitPriceSen")).isEqualTo("unit_price_sen"); + assertThat(column(ShopOrderLine.class, "orderId")).isEqualTo("order_id"); + assertThat(column(Ticket.class, "ticketTypeId")).isEqualTo("ticket_type_id"); + assertThat(column(Ticket.class, "orderLineId")).isEqualTo("order_line_id"); + assertThat(new Ticket().getStatus()).isEqualTo("ACTIVE"); + assertThat(new TicketType().isEnabled()).isTrue(); + } + + @Test + void eventTicketSettingsDefaultOff() throws Exception { + Event e = new Event(); + assertThat(e.isTicketsEnabled()).isFalse(); + assertThat(e.getHoldDays()).isEqualTo(3); + assertThat(column(Event.class, "ticketsEnabled")).isEqualTo("tickets_enabled"); + assertThat(column(Event.class, "paymentInstructions")).isEqualTo("payment_instructions"); + assertThat(column(Event.class, "holdDays")).isEqualTo("hold_days"); + } + + private static List> uniques(Class c) { + return Arrays.stream(c.getAnnotation(Table.class).uniqueConstraints()).map(u -> List.of(u.columnNames())).toList(); + } + + private static String column(Class c, String field) throws Exception { + return c.getDeclaredField(field).getAnnotation(Column.class).name(); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventTicketSettingsTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventTicketSettingsTest.java new file mode 100644 index 0000000..a1528b7 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventTicketSettingsTest.java @@ -0,0 +1,115 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.repo.EventGuestRepository; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.util.redis.RedisUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +/** add-event-ticket-orders: ticket settings change only through their own endpoint; an event edit keeps them. */ +@ExtendWith(MockitoExtension.class) +class EventTicketSettingsTest { + private static final long EVENT = 900L; + @Mock private EventRepository eventRepository; + @Mock private RedisUtil redisUtil; + @Mock private EventGuestRepository guestRepository; + + private EventService service; + private Event stored; + + @BeforeEach + void setUp() { + service = new EventService(eventRepository, redisUtil, guestRepository); + lenient().when(eventRepository.save(any(Event.class))).thenAnswer(i -> i.getArgument(0)); + stored = new Event(); + stored.setId(5L); + stored.setUuid(EVENT); + stored.setCompanyId(7L); + stored.setTicketsEnabled(true); + stored.setPaymentInstructions("Maybank 5140"); + stored.setHoldDays(5); + lenient().when(eventRepository.findById(5L)).thenReturn(Optional.of(stored)); + lenient().when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(stored)); + } + + private EventService.TicketSettingsRequest settings(Long company, boolean on, String text, Integer days) { + return new EventService.TicketSettingsRequest(company, EVENT, on, text, days, "admin"); + } + + private void assertRejected(EventService.TicketSettingsRequest r, int status, String reason) { + assertThatThrownBy(() -> service.ticketSettings(r)).isInstanceOfSatisfying(ResponseStatusException.class, ex -> { + assertThat(ex.getStatusCode().value()).isEqualTo(status); + assertThat(ex.getReason()).isEqualTo(reason); + }); + verify(eventRepository, never()).save(any(Event.class)); + } + + @Test + void anEventEditKeepsTheStoredTicketSettings() { + Event incoming = new Event(); + incoming.setId(5L); + incoming.setName("KL Hotel Tech Day"); + Event saved = service.save(incoming); + assertThat(saved.isTicketsEnabled()).isTrue(); + assertThat(saved.getPaymentInstructions()).isEqualTo("Maybank 5140"); + assertThat(saved.getHoldDays()).isEqualTo(5); + } + + @Test + void aNewEventStartsWithTicketsOff() { + Event incoming = new Event(); + incoming.setCompanyId(7L); + incoming.setTicketsEnabled(true); + incoming.setHoldDays(9); + Event saved = service.save(incoming); + assertThat(saved.isTicketsEnabled()).isFalse(); + assertThat(saved.getHoldDays()).isEqualTo(3); + } + + @Test + void savesValidSettings() { + Event saved = service.ticketSettings(settings(7L, true, " CIMB 8001 ", 3)); + assertThat(saved.isTicketsEnabled()).isTrue(); + assertThat(saved.getPaymentInstructions()).isEqualTo("CIMB 8001"); + assertThat(saved.getHoldDays()).isEqualTo(3); + assertThat(saved.getDoneBy()).isEqualTo("admin"); + } + + @Test + void turningTicketsOnNeedsInstructions() { + assertRejected(settings(7L, true, " ", 3), 400, "PAYMENT_INSTRUCTIONS_REQUIRED"); + assertRejected(settings(7L, true, null, 3), 400, "PAYMENT_INSTRUCTIONS_REQUIRED"); + assertRejected(settings(7L, true, "x".repeat(1001), 3), 400, "PAYMENT_INSTRUCTIONS_TOO_LONG"); + } + + @Test + void ticketsOffAllowsEmptyInstructions() { + assertThat(service.ticketSettings(settings(7L, false, "", 3)).isTicketsEnabled()).isFalse(); + } + + @Test + void holdDaysOneToFourteen() { + assertRejected(settings(7L, true, "x", 0), 400, "HOLD_DAYS_INVALID"); + assertRejected(settings(7L, true, "x", 15), 400, "HOLD_DAYS_INVALID"); + assertRejected(settings(7L, true, "x", null), 400, "HOLD_DAYS_INVALID"); + } + + @Test + void anotherCompanysEventIsNotFound() { + assertRejected(settings(8L, true, "x", 3), 404, "EVENT_NOT_FOUND"); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketTypeServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketTypeServiceTest.java new file mode 100644 index 0000000..ba25dbf --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/TicketTypeServiceTest.java @@ -0,0 +1,206 @@ +package com.solvway.services.counter.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.model.TicketType; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.repo.ShopOrderLineRepository; +import com.solvway.services.counter.repo.TicketHeld; +import com.solvway.services.counter.repo.TicketRepository; +import com.solvway.services.counter.repo.TicketTypeRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** add-event-ticket-orders: ticket types, held seats and the public on-sale view. */ +@ExtendWith(MockitoExtension.class) +class TicketTypeServiceTest { + private static final long COMPANY = 7L; + private static final long EVENT = 900L; + private static final LocalDate TODAY = LocalDate.now(ZoneId.of("Asia/Kuala_Lumpur")); + + @Mock private EventRepository events; + @Mock private TicketTypeRepository types; + @Mock private TicketRepository tickets; + @Mock private ShopOrderLineRepository lines; + + private TicketTypeService service; + private Event event; + + @BeforeEach + void setUp() { + service = new TicketTypeService(events, types, tickets, lines); + event = new Event(); + event.setUuid(EVENT); + event.setCompanyId(COMPANY); + event.setDateStart(TODAY.plusDays(7).atTime(9, 0)); + event.setDateEnd(TODAY.plusDays(8).atTime(18, 0)); + event.setTicketsEnabled(true); + event.setPaymentInstructions("Maybank 5140 1234 5678"); + lenient().when(events.findByUuid(EVENT)).thenReturn(Optional.of(event)); + lenient().when(events.lockByUuid(EVENT)).thenReturn(Optional.of(event)); + lenient().when(types.save(any(TicketType.class))).thenAnswer(i -> { + TicketType t = i.getArgument(0); + if (t.getId() == null) t.setId(55L); + return t; + }); + } + + private static TicketType type(long id, String name, int price, int qty, int sort, boolean enabled, LocalDate salesEnd) { + TicketType t = new TicketType(); + t.setId(id); + t.setCompanyId(COMPANY); + t.setEventUuid(EVENT); + t.setName(name); + t.setPriceSen(price); + t.setQuantity(qty); + t.setSort(sort); + t.setEnabled(enabled); + t.setSalesEndDate(salesEnd); + return t; + } + + private TicketTypeService.SaveRequest save(Long id, String name, Integer price, Integer qty) { + return new TicketTypeService.SaveRequest(COMPANY, EVENT, id, name, price, qty, null, 0, true, "admin"); + } + + private static void assertStatus(Runnable r, int status, String reason) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(ResponseStatusException.class, ex -> { + assertThat(ex.getStatusCode().value()).isEqualTo(status); + assertThat(ex.getReason()).isEqualTo(reason); + }); + } + + @Test + void listShowsHeldAndLeftInSortOrder() { + when(types.findByEventUuidOrderBySortAscIdAsc(EVENT)).thenReturn(List.of( + type(1, "Early bird", 15000, 20, 0, true, null), type(2, "General", 25000, 100, 1, true, null))); + when(tickets.heldByType(EVENT)).thenReturn(List.of(new TicketHeld(1L, 12L))); + List rows = service.list(new TicketTypeService.ListRequest(COMPANY, EVENT)); + assertThat(rows).extracting(TicketTypeService.TypeRow::name).containsExactly("Early bird", "General"); + assertThat(rows.get(0).held()).isEqualTo(12); + assertThat(rows.get(0).left()).isEqualTo(8); + assertThat(rows.get(1).left()).isEqualTo(100); + } + + @Test + void anotherCompanysEventIsNotFound() { + assertStatus(() -> service.list(new TicketTypeService.ListRequest(8L, EVENT)), 404, "EVENT_NOT_FOUND"); + assertStatus(() -> service.save(new TicketTypeService.SaveRequest(8L, EVENT, null, "General", 100, 1, null, 0, true, "x")), 404, "EVENT_NOT_FOUND"); + } + + @Test + void savesANewType() { + TicketTypeService.TypeRow row = service.save(save(null, " General ", 25000, 100)); + assertThat(row.id()).isEqualTo(55L); + assertThat(row.name()).isEqualTo("General"); + assertThat(row.left()).isEqualTo(100); + } + + @Test + void refusesBadFields() { + assertStatus(() -> service.save(save(null, " ", 100, 1)), 400, "NAME_INVALID"); + assertStatus(() -> service.save(save(null, "x".repeat(81), 100, 1)), 400, "NAME_INVALID"); + assertStatus(() -> service.save(save(null, "General", -1, 1)), 400, "PRICE_INVALID"); + assertStatus(() -> service.save(save(null, "General", 10000000, 1)), 400, "PRICE_INVALID"); + assertStatus(() -> service.save(save(null, "General", 100, 0)), 400, "QUANTITY_INVALID"); + verify(types, never()).save(any()); + } + + @Test + void refusesADuplicateName() { + when(types.findByEventUuidAndName(EVENT, "General")).thenReturn(Optional.of(type(2, "General", 1, 1, 0, true, null))); + assertStatus(() -> service.save(save(null, "General", 100, 1)), 409, "NAME_TAKEN"); + } + + @Test + void quantityCannotDropBelowHeldSeats() { + when(types.findById(1L)).thenReturn(Optional.of(type(1, "Early bird", 15000, 20, 0, true, null))); + when(tickets.heldByType(EVENT)).thenReturn(List.of(new TicketHeld(1L, 12L))); + assertStatus(() -> service.save(save(1L, "Early bird", 15000, 10)), 409, "QUANTITY_BELOW_HELD"); + verify(events).lockByUuid(EVENT); + assertThat(service.save(save(1L, "Early bird", 15000, 12)).left()).isZero(); + } + + @Test + void aTypeOfAnotherEventIsNotFound() { + TicketType other = type(1, "VIP", 1, 1, 0, true, null); + other.setEventUuid(901L); + when(types.findById(1L)).thenReturn(Optional.of(other)); + assertStatus(() -> service.save(save(1L, "VIP", 1, 1)), 404, "TYPE_NOT_FOUND"); + } + + @Test + void aTypeWithOrdersCannotBeDeleted() { + when(types.findById(1L)).thenReturn(Optional.of(type(1, "Early bird", 15000, 20, 0, true, null))); + when(lines.existsByKindAndItemId("TICKET", 1L)).thenReturn(true); + assertStatus(() -> service.delete(new TicketTypeService.DeleteRequest(COMPANY, EVENT, 1L, "admin")), 409, "TYPE_HAS_ORDERS"); + verify(types, never()).delete(any()); + } + + @Test + void aTypeWithoutOrdersIsDeleted() { + TicketType t = type(1, "Early bird", 15000, 20, 0, true, null); + when(types.findById(1L)).thenReturn(Optional.of(t)); + service.delete(new TicketTypeService.DeleteRequest(COMPANY, EVENT, 1L, "admin")); + verify(types).delete(t); + } + + @Test + void onSaleShowsEnabledTypesWithStates() { + when(types.findByEventUuidOrderBySortAscIdAsc(EVENT)).thenReturn(List.of( + type(1, "Early bird", 15000, 20, 0, true, TODAY.minusDays(1)), + type(2, "General", 25000, 100, 1, true, null), + type(3, "VIP", 50000, 5, 2, true, null), + type(4, "Staff", 0, 5, 3, false, null))); + when(tickets.heldByType(EVENT)).thenReturn(List.of(new TicketHeld(3L, 5L), new TicketHeld(2L, 20L))); + TicketTypeService.OnSale view = service.onSale(EVENT); + assertThat(view.ticketsOpen()).isTrue(); + assertThat(view.paymentInstructions()).isEqualTo("Maybank 5140 1234 5678"); + assertThat(view.types()).extracting(TicketTypeService.PublicType::name).containsExactly("Early bird", "General", "VIP"); + assertThat(view.types()).extracting(TicketTypeService.PublicType::state).containsExactly("ENDED", "ON_SALE", "SOLD_OUT"); + assertThat(view.types().get(1).left()).isEqualTo(80); + } + + @Test + void salesEndDefaultsToTheEventsEndDate() { + event.setDateEnd(LocalDateTime.of(TODAY.minusDays(1), java.time.LocalTime.NOON)); + event.setDateStart(event.getDateEnd().minusDays(1)); + when(types.findByEventUuidOrderBySortAscIdAsc(EVENT)).thenReturn(List.of(type(2, "General", 25000, 100, 1, true, null))); + TicketTypeService.OnSale view = service.onSale(EVENT); + assertThat(view.ticketsOpen()).isFalse(); + assertThat(view.types().get(0).state()).isEqualTo("ENDED"); + } + + @Test + void onSaleIsClosedWhenTicketsAreOffOrTheEventIsDisabled() { + event.setTicketsEnabled(false); + assertThat(service.onSale(EVENT).ticketsOpen()).isFalse(); + event.setTicketsEnabled(true); + event.setEnabled(GeneralEnum.FlagYesNo.N); + assertThat(service.onSale(EVENT).ticketsOpen()).isFalse(); + } + + @Test + void onSaleOfAnUnknownEventIsNotFound() { + when(events.findByUuid(1L)).thenReturn(Optional.empty()); + assertStatus(() -> service.onSale(1L), 404, "EVENT_NOT_FOUND"); + } +}