From 6562610dbb144d414e9acaf300376210f90dc2ca Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:19:12 +0000 Subject: [PATCH 1/3] [MBA-3829] Waitlist auto-offer: offer a freed seat to the next waitlisted candidate WaitlistOfferPolicy offers seats freed by cancel, reschedule-out, capacity increase, decline, expiry and withdrawal to the lowest-position eligible waitlist entry (ET25/ET50 skipped while no accommodation seat is free). Pending offers hold the seat. Accept/decline endpoints under /api/v2/offers, expiry job, seat_offer table (V3), SeatOffered/Accepted/Declined/Expired/Withdrawn outbox events, UI in My bookings and the admin waitlist. ADR 0004. Co-Authored-By: Mason --- docs/adr/0002-ported-rule-decisions.md | 2 +- docs/adr/0004-waitlist-auto-offer.md | 56 +++ docs/runbooks/scheduling-service.md | 18 + services/scheduling-service/api/openapi.yaml | 322 ++++++++++++++++- .../frontend/src/api.contract.ts | 5 +- .../scheduling-service/frontend/src/api.ts | 17 +- .../frontend/src/components/WaitlistTable.tsx | 9 +- .../frontend/src/pages/AdminSession.tsx | 2 +- .../frontend/src/pages/MyBookings.tsx | 30 +- .../scheduling/domain/ErrorCode.java | 6 +- .../scheduling/domain/OfferStatus.java | 6 + .../scheduling/domain/SeatFormula.java | 5 +- .../scheduling/domain/SessionCapacity.java | 18 +- .../scheduling/domain/WaitlistOfferRules.java | 43 +++ .../scheduling/domain/WaitlistSlot.java | 9 + .../scheduling/importer/SnapshotWriter.java | 3 +- .../scheduling/outbox/OutboxEventType.java | 14 +- .../scheduling/persistence/Rows.java | 19 +- .../persistence/SchedulingRepository.java | 110 +++++- .../scheduling/service/SchedulingService.java | 116 ++++++- .../service/WaitlistOfferExpiryJob.java | 40 +++ .../service/WaitlistOfferPolicy.java | 112 ++++++ .../com/northwind/scheduling/web/Dtos.java | 32 +- .../scheduling/web/OpenApiConfig.java | 51 ++- .../web/SchedulingApiController.java | 22 ++ .../src/main/resources/application.yml | 6 + .../db/migration/V3__waitlist_offers.sql | 29 ++ .../domain/WaitlistOfferRulesTest.java | 76 ++++ .../northwind/scheduling/relay/RelayIT.java | 55 +++ .../scheduling/service/WaitlistOfferIT.java | 324 ++++++++++++++++++ .../scheduling/web/SchedulingApiIT.java | 8 +- .../src/test/resources/application.properties | 1 + 32 files changed, 1517 insertions(+), 49 deletions(-) create mode 100644 docs/adr/0004-waitlist-auto-offer.md create mode 100644 services/scheduling-service/src/main/java/com/northwind/scheduling/domain/OfferStatus.java create mode 100644 services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistOfferRules.java create mode 100644 services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistSlot.java create mode 100644 services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferExpiryJob.java create mode 100644 services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferPolicy.java create mode 100644 services/scheduling-service/src/main/resources/db/migration/V3__waitlist_offers.sql create mode 100644 services/scheduling-service/src/test/java/com/northwind/scheduling/domain/WaitlistOfferRulesTest.java create mode 100644 services/scheduling-service/src/test/java/com/northwind/scheduling/service/WaitlistOfferIT.java diff --git a/docs/adr/0002-ported-rule-decisions.md b/docs/adr/0002-ported-rule-decisions.md index 33acc41d..9255308e 100644 --- a/docs/adr/0002-ported-rule-decisions.md +++ b/docs/adr/0002-ported-rule-decisions.md @@ -32,7 +32,7 @@ drift, which is what settles ODD-01, ODD-05, ODD-10 (seat part) and ODD-13. | ODD-06 | 6. accommodation floor on capacity reductions | **Keep** (`scheduling.rules.accommodation-floor: allocated`) | Capacity below `AccommodationCapacity` (or negative) is rejected with `INVALID_CAPACITY` (HTTP 409, legacy code 50005 = state 5), and nothing changes. `booked` (floor = extra-time seats in use) is opt-in and not legacy behaviour. Equal to the allocation is allowed (`CP-08`). | portal `CP-05`, `CP-08`; db `CP-06` | `022_usp_ChangeCapacity.sql` (state 5; PR 51 not in `legacy-baseline`), HB-14 | `AccommodationFloorPolicy`, `CapacityChange` | | ODD-07 | 6a. blank accommodation code | **Keep API meaning** | Blank / missing code = no accommodation (stored NULL, no accommodation seat used), as in booking-api. The portal's silent fallback to the profile default moves into the UI, which shows the code explicitly. Unknown codes -> `VALIDATION` 400. `ET25`/`ET50` consume accommodation seats, `SR`/`RB` never do (`AC-01..AC-04`, `AC-07`, `AC-08`). | portal `AC-05`; api `AC-06` | booking-api `StringUtils.trimToNull`, portal `AccommodationCodes.cs` / `BookingService.cs` (HB-09) | `AccommodationCodes` | | ODD-08 | 6b. reschedule onto the same session | **Keep API rule** | Refused on every channel with `SAME_SESSION` (409). The portal's cancel + re-book on the same session (new id, seat released and re-taken) is not reproduced. | portal `RS-05`; api `RS-06` | booking-api `BookingService.reschedule`, `023_usp_RescheduleBooking.sql` (HB-10, HB-11) | `ReschedulePolicy` | -| ODD-09 | - | **Keep** | Cancelling a BOOKED seat frees it but promotes nobody. Cancelling a WAITLISTED booking deletes its waitlist entry, and the other positions are not renumbered. A second cancel -> `NOT_CANCELLABLE` (409 / 50004). Automatic promotion is a product decision for a later story. | portal `CN-05`, `CN-03`, `CN-07`; api `CN-06`, `CN-04`, `CN-08` | `021_usp_CancelBooking.sql` (HB-06) | `BookingRules.checkCancellable`, `SchedulingService.cancel` | +| ODD-09 | - | **Keep** | Cancelling a BOOKED seat frees it but promotes nobody. Cancelling a WAITLISTED booking deletes its waitlist entry, and the other positions are not renumbered. A second cancel -> `NOT_CANCELLABLE` (409 / 50004). Automatic promotion is a product decision for a later story: superseded for BOOKED cancels by [ADR 0004](0004-waitlist-auto-offer.md) (MBA-3829, the freed seat is offered to the waitlist; legacy unchanged). | portal `CN-05`, `CN-03`, `CN-07`; api `CN-06`, `CN-04`, `CN-08` | `021_usp_CancelBooking.sql` (HB-06) | `BookingRules.checkCancellable`, `SchedulingService.cancel` | | ODD-10 | - | **Change** | A rescheduled booking keeps the original `channel`, `external_ref` and accommodation code, so partner references (PX-3008) survive. | portal `RS-08` | `023_usp_RescheduleBooking.sql` (HB-10) | `ReschedulePolicy`, `SchedulingService.reschedule` | | ODD-11 | - | **Change (mapping)** | Errors carry a symbolic `error` and `legacyCode = 50000 + proc state`: `SESSION_NOT_OPEN` 50001, `DUPLICATE_BOOKING` 50002, `NO_ACCOMMODATION_SEAT` 50003, `NOT_CANCELLABLE` 50004, `INVALID_CAPACITY` 50005, `DIFFERENT_EXAM` 50006. This is the documented 5000x table the procs never raised. | db `BK-07`, `CP-06`, `RS-07` | `db/procs/020..023` (HB-14) | `ErrorCode`, `web/ApiExceptionHandler` | | ODD-12 | - | **Change** | Every channel gets booking-api's shape: HTTP 409 `{error, message, legacyCode}` (404 / 400 for not found / validation), never an HTTP 200 page with an alert. The UI shows these as toasts and inline errors. | portal `BK-05`, `BK-08`, `BK-10`, `CP-05`, `RS-03`; api `BK-06`, `BK-09`, `BK-11`, `RS-04` | portal controllers vs booking-api (HB-14) | `web/ApiExceptionHandler` | diff --git a/docs/adr/0004-waitlist-auto-offer.md b/docs/adr/0004-waitlist-auto-offer.md new file mode 100644 index 00000000..5ecf8a2a --- /dev/null +++ b/docs/adr/0004-waitlist-auto-offer.md @@ -0,0 +1,56 @@ +# ADR 0004: freed seats are offered to the waitlist (MBA-3829, A4) + +Status: accepted. Deliberate behaviour change to [ADR 0002](0002-ported-rule-decisions.md) ODD-09, built on the single +writer and outbox of [ADR 0003](0003-single-writer-outbox-relay.md). + +## Context + +Legacy never promotes anyone: `usp_CancelBooking` frees the seat and leaves the waitlist untouched +([HB-06](../as-is/hidden-behaviours.md), [MR-12](../as-is/migration-risks.md)); centre staff promote by hand. ADR 0002 +kept that behaviour (ODD-09) and left automatic promotion to a later story. Since M4 scheduling-service is the only +writer of bookings, waitlist and capacity, so the rule can change in one place and the relay carries the result to +every legacy reader. + +## Decisions + +1. **Trigger.** Whenever a seat frees up in an `OPEN` session (cancel of a BOOKED booking, reschedule out, capacity + increase, an offer declined, expired or withdrawn), `WaitlistOfferPolicy` offers it, in the same transaction and + under the same session lock (`UPDLOCK` on `exam_session`) as the change that freed it. Closed, delivered and + cancelled sessions make no offers. +2. **Who.** The lowest-position `WAITLISTED` entry without a pending offer whose accommodation needs fit + (`WaitlistOfferRules`, pure domain). `ET25`/`ET50` need a free accommodation seat; while none is free they are + skipped and keep their position, and the next standard entry is offered. Several free seats give several offers in + position order. +3. **Offer and hold.** A `seat_offer` row (`V3__waitlist_offers.sql`) with status `PENDING`, `expires_at = now + + scheduling.waitlist.offer-ttl` (default `PT24H`). A pending offer holds its seat (and the accommodation seat for + ET entries): `SessionCapacity.heldSeats` is subtracted from `seatsAvailable`, so a new booking is waitlisted, not + booked, and `seatsAvailable` stays 0. A filtered unique index allows one pending offer per booking, so concurrent + triggers cannot double-offer. +4. **Accept** (`POST /api/v2/offers/{offerId}/accept`, before expiry): the booking becomes `BOOKED`, its waitlist entry + is removed and later positions move up by one. **Decline** (`.../decline`) and **expiry** (`WaitlistOfferExpiryJob`, + every `scheduling.waitlist.expiry-poll`, default `PT1M`) cancel the waitlisted booking (reason `Waitlist offer + declined` / `Waitlist offer expired`), remove its entry, shift later positions, and offer the seat to the next + eligible entry; if nobody is left the seat is simply available. Accepting an expired offer answers + `409 OFFER_NOT_PENDING` even if the job has not swept it yet. +5. **Withdraw.** Cancelling or rescheduling a booking with a pending offer withdraws the offer (`WITHDRAWN`) and passes + the seat on; a capacity decrease withdraws the newest pending offers that no longer fit. Withdrawn candidates keep + their position. +6. **Outbox.** New event types `SeatOffered`, `SeatOfferAccepted`, `SeatOfferDeclined`, `SeatOfferExpired`, + `SeatOfferWithdrawn`, written in the same transaction and carrying the full resulting booking/session state like + every M4 event (state transfer). The relay needs no new code: acceptance projects as `BOOKED` in `dbo.Booking`, the + `dbo.Waitlist` row is deleted and the remaining positions are rewritten. +7. **Legacy view of a hold.** The hold exists only in scheduling-service. In legacy the offered booking stays + `WAITLISTED` and `ExamSession.SeatsAvailable` stays `Capacity - (BOOKED + ATTENDED)` (the formula + `db/checks/seat-drift.sql` checks), so reconciliation and seat drift stay at 0 during and after an offer cycle. + Legacy writes are denied (ADR 0003), so no legacy path can take the held seat. +8. **Waitlisted cancel** keeps ODD-09: cancelling a waitlisted booking without an offer deletes its entry and does not + renumber. Accept, decline and expiry renumber because the ticket requires positions 2-3 to become 1-2. + +## Consequences + +* Candidates see a pending offer under My bookings with Accept / Decline; the admin waitlist table shows offer state + and the session page counts held seats. +* Authorisation is the same as for the other `/api/v2` candidate writes (cancel, reschedule): none beyond the gateway. + Candidate authentication is out of scope for the scheduling slice. +* Rolling back a centre to legacy (runbook section 5) leaves pending offers in Scheduling only; the legacy waitlist is + intact, so staff promote by hand as before. diff --git a/docs/runbooks/scheduling-service.md b/docs/runbooks/scheduling-service.md index a96f96b7..deb4075d 100644 --- a/docs/runbooks/scheduling-service.md +++ b/docs/runbooks/scheduling-service.md @@ -145,6 +145,24 @@ event id in `dbo.RelayCheckpoint` ([ADR 0003](../adr/0003-single-writer-outbox-r - While lag is high, legacy readers (portal pages, booking-api `GET`, results) show stale availability. Writes are not affected (scheduling-service is the only writer). +### Waitlist offers stuck or not made (MBA-3829) + +A seat freed in an `OPEN` session is offered to the next eligible waitlist entry and held while the offer is +`PENDING` ([ADR 0004](../adr/0004-waitlist-auto-offer.md)). Config: `scheduling.waitlist.offer-ttl` +(`SCHEDULING_WAITLIST_OFFER_TTL`, default `PT24H`), `scheduling.waitlist.expiry-enabled` (`..._EXPIRY_ENABLED`, +default `true`), `scheduling.waitlist.expiry-poll` (`..._EXPIRY_POLL`, default `PT1M`). + +- Live offers: `SELECT offer_id, session_id, booking_id, position, offered_at, expires_at FROM seat_offer WHERE status = + 'PENDING' ORDER BY expires_at` in `Scheduling`. `GET /api/v2/sessions/{id}` shows `heldSeats`; the waitlist endpoint + shows `offerStatus` per entry. +- Offers past `expires_at` still `PENDING`: the expiry job is off or failing. Check `expiry-enabled` and WARN logs + `offer expiry failed`. Accepting such an offer already answers `409 OFFER_NOT_PENDING`, so nobody gets an expired + seat; the job releases it on its next pass. +- Seat free but nobody offered: the waitlist only holds ET25/ET50 entries and no accommodation seat is free (they are + skipped, by design), or the session is not `OPEN`. +- Offers do not change legacy until accepted: the offered booking stays `WAITLISTED` in `dbo.Booking`, and + `SeatsAvailable` counts the held seat as free there. Reconciliation is expected to stay at 0 during offers. + ### Non-zero reconciliation report `GET /internal/reconciliation` (or `java -jar target/scheduling-service-*.jar reconcile`, exit 0 only when diff --git a/services/scheduling-service/api/openapi.yaml b/services/scheduling-service/api/openapi.yaml index 4b968f25..6aeceb54 100644 --- a/services/scheduling-service/api/openapi.yaml +++ b/services/scheduling-service/api/openapi.yaml @@ -10,7 +10,8 @@ info: Every 4xx is an `ApiError`: `error` is the symbolic code, `message` is human readable, and `legacyCode` is `50000 + RAISERROR state` of the legacy procs (ODD-11, HB-14), e.g. `NO_ACCOMMODATION_SEAT` = 50003, or null when the rule never existed as a proc error. Malformed input (unreadable JSON, wrong path/param type) - answers `BAD_REQUEST` without `legacyCode`. + answers `BAD_REQUEST` without `legacyCode`. The offer operations (MBA-3829) answer `OFFER_NOT_FOUND` and + `OFFER_NOT_PENDING` as an `OfferError` (same shape). | error | HTTP | legacyCode | |---|---|---| @@ -30,6 +31,8 @@ info: | `DIFFERENT_EXAM` | 409 | 50006 | | `SAME_SESSION` | 409 | null | | `NOT_ELIGIBLE` | 409 | null | + | `OFFER_NOT_FOUND` | 404 | null | + | `OFFER_NOT_PENDING` | 409 | null | title: Northwind Scheduling API version: 2.0.0 servers: @@ -39,6 +42,7 @@ tags: - name: Bookings - name: Candidates - name: Capacity +- name: Offers - name: Reference data - name: Sessions paths: @@ -188,7 +192,8 @@ paths: schema: $ref: "#/components/schemas/ApiError" description: "Rule violation: NOT_CANCELLABLE" - summary: "Cancel a booking (frees the seat, nobody is promoted, ODD-09)" + summary: "Cancel a booking (frees the seat; it is offered to the next eligible\ + \ waitlist entry, MBA-3829 / ADR 0004)" tags: - Bookings get: @@ -641,6 +646,172 @@ paths: summary: List published exams tags: - Reference data + /api/v2/offers/{offerId}: + get: + operationId: offer + parameters: + - in: path + name: offerId + required: true + schema: + type: integer + format: int32 + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/OfferDto" + description: OK + "400": + content: + application/json: + examples: + BAD_REQUEST: + summary: BAD_REQUEST + value: + error: BAD_REQUEST + message: Failed to convert value of type 'java.lang.String' to + required type 'int' + schema: + $ref: "#/components/schemas/ApiError" + description: "Invalid input: BAD_REQUEST" + "404": + content: + application/json: + examples: + OFFER_NOT_FOUND: + summary: OFFER_NOT_FOUND + value: + error: OFFER_NOT_FOUND + legacyCode: null + message: Offer 99999 not found + schema: + $ref: "#/components/schemas/OfferError" + description: "Not found: OFFER_NOT_FOUND" + summary: Get a waitlist seat offer + tags: + - Offers + /api/v2/offers/{offerId}/accept: + post: + operationId: acceptOffer + parameters: + - in: path + name: offerId + required: true + schema: + type: integer + format: int32 + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/OfferResultDto" + description: OK + "400": + content: + application/json: + examples: + BAD_REQUEST: + summary: BAD_REQUEST + value: + error: BAD_REQUEST + message: Failed to convert value of type 'java.lang.String' to + required type 'int' + schema: + $ref: "#/components/schemas/ApiError" + description: "Invalid input: BAD_REQUEST" + "404": + content: + application/json: + examples: + OFFER_NOT_FOUND: + summary: OFFER_NOT_FOUND + value: + error: OFFER_NOT_FOUND + legacyCode: null + message: Offer 99999 not found + schema: + $ref: "#/components/schemas/OfferError" + description: "Not found: OFFER_NOT_FOUND" + "409": + content: + application/json: + examples: + OFFER_NOT_PENDING: + summary: OFFER_NOT_PENDING + value: + error: OFFER_NOT_PENDING + legacyCode: null + message: Offer 7 is EXPIRED + schema: + $ref: "#/components/schemas/OfferError" + description: "Rule violation: OFFER_NOT_PENDING" + summary: "Accept a pending seat offer (the waitlisted booking becomes BOOKED,\ + \ later waitlist positions move up)" + tags: + - Offers + /api/v2/offers/{offerId}/decline: + post: + operationId: declineOffer + parameters: + - in: path + name: offerId + required: true + schema: + type: integer + format: int32 + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/OfferResultDto" + description: OK + "400": + content: + application/json: + examples: + BAD_REQUEST: + summary: BAD_REQUEST + value: + error: BAD_REQUEST + message: Failed to convert value of type 'java.lang.String' to + required type 'int' + schema: + $ref: "#/components/schemas/ApiError" + description: "Invalid input: BAD_REQUEST" + "404": + content: + application/json: + examples: + OFFER_NOT_FOUND: + summary: OFFER_NOT_FOUND + value: + error: OFFER_NOT_FOUND + legacyCode: null + message: Offer 99999 not found + schema: + $ref: "#/components/schemas/OfferError" + description: "Not found: OFFER_NOT_FOUND" + "409": + content: + application/json: + examples: + OFFER_NOT_PENDING: + summary: OFFER_NOT_PENDING + value: + error: OFFER_NOT_PENDING + legacyCode: null + message: Offer 7 is EXPIRED + schema: + $ref: "#/components/schemas/OfferError" + description: "Rule violation: OFFER_NOT_PENDING" + summary: "Decline a pending seat offer (the waitlisted booking is cancelled,\ + \ the seat is offered to the next entry)" + tags: + - Offers /api/v2/sessions/{sessionId}: get: operationId: session @@ -977,6 +1148,22 @@ components: type: string example: PX-3008 nullable: true + offerExpiresAt: + type: string + description: "Server-local clock of the system that recorded it: the scheduling\ + \ service for new writes, the legacy estate for imported rows (not centre-local;\ + \ docs/as-is/smoke-test.md, HB-25, MR-06), ISO-8601 without offset" + example: 2026-11-11T09:15:00 + nullable: true + pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$" + offerId: + type: integer + format: int32 + example: 7 + nullable: true + offerStatus: + type: string + nullable: true rescheduledFrom: type: integer format: int32 @@ -1017,6 +1204,9 @@ components: - examCode - examTitle - externalRef + - offerExpiresAt + - offerId + - offerStatus - rescheduledFrom - sessionId - sessionStartsAt @@ -1239,6 +1429,109 @@ components: - examCode - retakeWaitDays - title + OfferDto: + type: object + properties: + bookingId: + type: integer + format: int32 + example: 1201 + candidateNumber: + type: string + example: NW00000920 + expiresAt: + type: string + description: "Server-local clock of the system that recorded it: the scheduling\ + \ service for new writes, the legacy estate for imported rows (not centre-local;\ + \ docs/as-is/smoke-test.md, HB-25, MR-06), ISO-8601 without offset" + example: 2026-11-11T09:15:00 + pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$" + offerId: + type: integer + format: int32 + example: 7 + offeredAt: + type: string + description: "Server-local clock of the system that recorded it: the scheduling\ + \ service for new writes, the legacy estate for imported rows (not centre-local;\ + \ docs/as-is/smoke-test.md, HB-25, MR-06), ISO-8601 without offset" + example: 2026-11-10T09:15:00 + pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$" + position: + type: integer + format: int32 + example: 1 + resolvedAt: + type: string + description: "Server-local clock of the system that recorded it: the scheduling\ + \ service for new writes, the legacy estate for imported rows (not centre-local;\ + \ docs/as-is/smoke-test.md, HB-25, MR-06), ISO-8601 without offset" + example: 2026-11-10T10:00:00 + nullable: true + pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$" + sessionId: + type: integer + format: int32 + example: 154 + status: + type: string + enum: + - PENDING + - ACCEPTED + - DECLINED + - EXPIRED + - WITHDRAWN + example: PENDING + required: + - bookingId + - candidateNumber + - expiresAt + - offerId + - offeredAt + - position + - resolvedAt + - sessionId + - status + OfferError: + type: object + description: 404/409 body of the waitlist offer operations (MBA-3829) + properties: + error: + type: string + description: Symbolic error code (booking-api vocabulary) + enum: + - OFFER_NOT_FOUND + - OFFER_NOT_PENDING + example: OFFER_NOT_FOUND + legacyCode: + type: integer + format: int32 + description: "50000 + legacy proc RAISERROR state (ODD-11): 50001..50006,\ + \ see the table in the API description; null when the rule had no proc\ + \ error. Present on /api/v2 rule errors, absent for BAD_REQUEST and on\ + \ /api/v1." + nullable: true + example: null + message: + type: string + description: Human-readable message + example: Offer 7 is EXPIRED + required: + - error + - message + OfferResultDto: + type: object + properties: + booking: + $ref: "#/components/schemas/BookingDto" + offer: + $ref: "#/components/schemas/OfferDto" + session: + $ref: "#/components/schemas/SessionDto" + required: + - booking + - offer + - session RescheduleRequest: type: object properties: @@ -1306,6 +1599,10 @@ components: examTitle: type: string example: Registered Nurse Part 1 + heldSeats: + type: integer + format: int32 + example: 1 roomName: type: string example: Room North @@ -1343,6 +1640,7 @@ components: - centerName - examCode - examTitle + - heldSeats - roomName - seatsAvailable - sessionId @@ -1373,15 +1671,35 @@ components: candidateNumber: type: string example: NW00000920 + offerExpiresAt: + type: string + description: "Server-local clock of the system that recorded it: the scheduling\ + \ service for new writes, the legacy estate for imported rows (not centre-local;\ + \ docs/as-is/smoke-test.md, HB-25, MR-06), ISO-8601 without offset" + example: 2026-11-11T09:15:00 + nullable: true + pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$" + offerId: + type: integer + format: int32 + example: 7 + nullable: true + offerStatus: + type: string + nullable: true position: type: integer format: int32 + example: 1 required: - accommodationCode - addedAt - bookingId - candidateName - candidateNumber + - offerExpiresAt + - offerId + - offerStatus - position securitySchemes: serviceToken: diff --git a/services/scheduling-service/frontend/src/api.contract.ts b/services/scheduling-service/frontend/src/api.contract.ts index 0c72b317..aa78acba 100644 --- a/services/scheduling-service/frontend/src/api.contract.ts +++ b/services/scheduling-service/frontend/src/api.contract.ts @@ -3,7 +3,7 @@ // accept fails `tsc`. import type { components } from './generated/openapi'; import type { - Booking, BookingResult, Candidate, CapacityResult, Center, Eligibility, Exam, Session, WaitlistEntry, + Booking, BookingResult, Candidate, CapacityResult, Center, Eligibility, Exam, Offer, OfferResult, Session, WaitlistEntry, } from './api'; export type Schemas = components['schemas']; @@ -21,7 +21,10 @@ export type ResponseContract = [ Accepts, Accepts, Accepts, + Accepts, + Accepts, Accepts<{ error: string; message: string; legacyCode?: number | null }, Schemas['ApiError']>, + Accepts<{ error: string; message: string; legacyCode?: number | null }, Schemas['OfferError']>, ]; export type BookRequest = Schemas['BookRequest']; diff --git a/services/scheduling-service/frontend/src/api.ts b/services/scheduling-service/frontend/src/api.ts index 25d16e70..03476057 100644 --- a/services/scheduling-service/frontend/src/api.ts +++ b/services/scheduling-service/frontend/src/api.ts @@ -6,15 +6,28 @@ export interface Session { sessionId: number; examCode: string; examTitle: string; centerCode: string; centerName: string; roomName: string; startsAt: string; status: string; capacity: number; accommodationCapacity: number; bookedSeats: number; seatsAvailable: number; accommodationUsed: number; accommodationAvailable: number; waitlistCount: number; + /** seats held by pending waitlist offers (MBA-3829) */ + heldSeats: number; } export interface Booking { bookingId: number; sessionId: number; candidateNumber: string; candidateName: string; examCode: string; examTitle: string; centerCode: string; centerName: string; sessionStartsAt: string; status: string; accommodationCode: string | null; channel: string; externalRef: string | null; bookedAt: string; cancelledAt: string | null; cancelReason: string | null; waitlistPosition: number | null; rescheduledFrom: number | null; + /** latest waitlist seat offer of this booking (MBA-3829) */ + offerId: number | null; offerStatus: string | null; offerExpiresAt: string | null; } export interface BookingResult { bookingId: number; status: string; waitlistPosition: number | null; booking: Booking; session: Session } -export interface WaitlistEntry { position: number; bookingId: number; candidateNumber: string; candidateName: string; accommodationCode: string | null; addedAt: string } +export interface WaitlistEntry { + position: number; bookingId: number; candidateNumber: string; candidateName: string; accommodationCode: string | null; addedAt: string; + /** pending seat offer (MBA-3829) */ + offerId: number | null; offerStatus: string | null; offerExpiresAt: string | null; +} +export interface Offer { + offerId: number; sessionId: number; bookingId: number; candidateNumber: string; position: number; status: string; + offeredAt: string; expiresAt: string; resolvedAt: string | null; +} +export interface OfferResult { offer: Offer; booking: Booking; session: Session } export interface Candidate { candidateNumber: string; firstName: string; lastName: string; email: string; defaultAccommodationCode: string | null } export interface Eligibility { eligible: boolean; reason: string; message: string; earliestRetakeDate: string | null; dayCounting: string } export interface CapacityResult { session: Session; oldCapacity: number; newCapacity: number; demotedBookingIds: number[] } @@ -61,6 +74,8 @@ export const api = { call('POST', '/bookings', { sessionId, candidateNumber, accommodationCode: accommodationCode || null } satisfies BookRequest), booking: (id: number) => call('GET', `/bookings/${id}`), cancel: (id: number) => call('DELETE', `/bookings/${id}`), + acceptOffer: (offerId: number) => call('POST', `/offers/${offerId}/accept`), + declineOffer: (offerId: number) => call('POST', `/offers/${offerId}/decline`), reschedule: (id: number, newSessionId: number) => call('POST', `/bookings/${id}/reschedule`, { newSessionId } satisfies RescheduleRequest), }; diff --git a/services/scheduling-service/frontend/src/components/WaitlistTable.tsx b/services/scheduling-service/frontend/src/components/WaitlistTable.tsx index 68c45151..c213abe7 100644 --- a/services/scheduling-service/frontend/src/components/WaitlistTable.tsx +++ b/services/scheduling-service/frontend/src/components/WaitlistTable.tsx @@ -5,7 +5,7 @@ export default function WaitlistTable({ entries }: { entries: WaitlistEntry[] }) return ( - + {entries.map((w) => ( @@ -15,7 +15,12 @@ export default function WaitlistTable({ entries }: { entries: WaitlistEntry[] }) {w.candidateNumber}{w.candidateName}{w.accommodationCode ? ` · ${w.accommodationCode}` : ''} · booking #{w.bookingId} - + + ))} diff --git a/services/scheduling-service/frontend/src/pages/AdminSession.tsx b/services/scheduling-service/frontend/src/pages/AdminSession.tsx index d626307f..f71a3124 100644 --- a/services/scheduling-service/frontend/src/pages/AdminSession.tsx +++ b/services/scheduling-service/frontend/src/pages/AdminSession.tsx @@ -27,7 +27,7 @@ export default function AdminSession() { {stat('Booked', session.bookedSeats)} {stat('Available', session.seatsAvailable)} {stat('Accommodation used / avail.', `${session.accommodationUsed} / ${session.accommodationAvailable}`)} - {stat('Waitlist', session.waitlistCount)} + {stat('Waitlist', session.heldSeats ? `${session.waitlistCount} (${session.heldSeats} seat${session.heldSeats === 1 ? '' : 's'} offered)` : session.waitlistCount)}

Waitlist

diff --git a/services/scheduling-service/frontend/src/pages/MyBookings.tsx b/services/scheduling-service/frontend/src/pages/MyBookings.tsx index e8ad4961..ac2cf04d 100644 --- a/services/scheduling-service/frontend/src/pages/MyBookings.tsx +++ b/services/scheduling-service/frontend/src/pages/MyBookings.tsx @@ -14,6 +14,7 @@ export default function MyBookings() { const [bookings, setBookings] = useState(null); const [loading, setLoading] = useState(false); const [toCancel, setToCancel] = useState(null); + const [busyOffer, setBusyOffer] = useState(null); const load = useCallback((n: string) => { if (!n) return; @@ -44,6 +45,23 @@ export default function MyBookings() { } } + async function respond(b: Booking, accept: boolean) { + if (b.offerId == null) return; + setBusyOffer(b.offerId); + try { + const r = accept ? await api.acceptOffer(b.offerId) : await api.declineOffer(b.offerId); + toast('success', accept ? `Seat accepted · booking #${r.booking.bookingId} is BOOKED` : `Offer declined`, + accept ? `${b.examCode} on ${fmtDateTime(b.sessionStartsAt)}` : 'You have left the waitlist; the seat goes to the next candidate.'); + load(candidate); + } catch (e) { + toast('error', accept ? 'Could not accept the offer' : 'Could not decline the offer', (e as ApiError).message); + load(candidate); + } finally { + setBusyOffer(null); + } + } + + const pendingOffer = (b: Booking) => b.status === 'WAITLISTED' && b.offerStatus === 'PENDING' && b.offerId != null; const active = (b: Booking) => b.status === 'BOOKED' || b.status === 'WAITLISTED'; return ( <> @@ -74,6 +92,16 @@ export default function MyBookings() {

{b.examTitle}

{fmtDateTime(b.sessionStartsAt)} · {b.centerName} · Session #{b.sessionId} · Booking #{b.bookingId}

{b.cancelReason &&

{b.cancelReason}

} + {pendingOffer(b) && ( +
+

A seat is being held for you

+

Accept before {b.offerExpiresAt ? fmtDateTime(b.offerExpiresAt) : 'the offer expires'} or it passes to the next candidate.

+
+ + +
+
+ )} {active(b) && (
@@ -88,7 +116,7 @@ export default function MyBookings() { setToCancel(null)}> {toCancel && ( <> -

Booking #{toCancel.bookingId} for {toCancel.examCode} on {fmtDateTime(toCancel.sessionStartsAt)} will be cancelled and the seat released. Waitlisted candidates are not promoted automatically.

+

Booking #{toCancel.bookingId} for {toCancel.examCode} on {fmtDateTime(toCancel.sessionStartsAt)} will be cancelled and the seat released. If anyone is waitlisted, the seat is offered to the next eligible candidate.

diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/ErrorCode.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/ErrorCode.java index dd2746dc..bb028f23 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/ErrorCode.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/ErrorCode.java @@ -31,7 +31,11 @@ public enum ErrorCode { /** booking-api only (ODD-08). */ SAME_SESSION(409, 0), /** booking-api RetakeEligibilityService / portal EligibilityService. */ - NOT_ELIGIBLE(409, 0); + NOT_ELIGIBLE(409, 0), + /** MBA-3829 waitlist offers (OfferError schema, kept out of ApiError like UNAUTHORIZED). */ + OFFER_NOT_FOUND(404, 0), + /** The offer is no longer PENDING (accepted, declined, expired or withdrawn), or its expiry has passed. */ + OFFER_NOT_PENDING(409, 0); private final int httpStatus; private final int legacyState; diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/OfferStatus.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/OfferStatus.java new file mode 100644 index 00000000..db074688 --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/OfferStatus.java @@ -0,0 +1,6 @@ +package com.northwind.scheduling.domain; + +/** seat_offer.status (V3__waitlist_offers.sql, ADR 0004). Only PENDING holds a seat. */ +public enum OfferStatus { + PENDING, ACCEPTED, DECLINED, EXPIRED, WITHDRAWN +} diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SeatFormula.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SeatFormula.java index a5bf486f..76e6372b 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SeatFormula.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SeatFormula.java @@ -6,7 +6,8 @@ * The two seat formulas found in the legacy estate (ODD-03, HB-05/HB-06): *
    *
  • {@link #STANDARD}: Capacity - (BOOKED + ATTENDED), the formula of db/procs/024 seat-drift, - * booking-api SeatCounter and SeatCounter.cs. Chosen by ADR 0002.
  • + * booking-api SeatCounter and SeatCounter.cs. Chosen by ADR 0002. Seats held by pending waitlist offers are not + * available either (MBA-3829, ADR 0004); legacy SeatsAvailable still excludes them (OutboxRepository). *
  • {@link #CAPACITY_SYNC}: Capacity - AccommodationCapacity - active standard (non ET) bookings, * floored at 0, from services/capacity-sync CapacitySyncService. Kept only for comparison.
  • *
@@ -23,7 +24,7 @@ public static SeatFormula parse(String value) { public int seatsAvailable(SessionCapacity s) { return switch (this) { - case STANDARD -> Math.max(0, s.capacity() - s.occupiedSeats()); + case STANDARD -> Math.max(0, s.capacity() - s.occupiedSeats() - s.heldSeats()); case CAPACITY_SYNC -> Math.max(0, s.capacity() - s.accommodationCapacity() - (s.occupiedSeats() - s.accommodationUsed())); }; diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SessionCapacity.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SessionCapacity.java index fbd57bd8..401bfd66 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SessionCapacity.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SessionCapacity.java @@ -10,16 +10,25 @@ * @param accommodationUsed BOOKED + ATTENDED bookings with ET25/ET50 (booking-api * BookingDao.countAccommodationSeatsUsed, usp_BookSeat) * @param waitlisted WAITLISTED bookings + * @param heldSeats seats held by PENDING waitlist offers (MBA-3829, ADR 0004) + * @param accommodationHeld held seats whose offered booking is ET25/ET50 (holds an accommodation seat too) */ public record SessionCapacity(int capacity, int accommodationCapacity, int occupiedSeats, int accommodationUsed, - int waitlisted) { + int waitlisted, int heldSeats, int accommodationHeld) { public SessionCapacity { - if (capacity < 0 || accommodationCapacity < 0 || occupiedSeats < 0 || accommodationUsed < 0 || waitlisted < 0) { + if (capacity < 0 || accommodationCapacity < 0 || occupiedSeats < 0 || accommodationUsed < 0 || waitlisted < 0 + || heldSeats < 0 || accommodationHeld < 0) { throw new IllegalArgumentException("seat counts cannot be negative"); } } + /** No pending offers. */ + public SessionCapacity(int capacity, int accommodationCapacity, int occupiedSeats, int accommodationUsed, + int waitlisted) { + this(capacity, accommodationCapacity, occupiedSeats, accommodationUsed, waitlisted, 0, 0); + } + public int seatsAvailable() { return SeatFormula.STANDARD.seatsAvailable(this); } @@ -28,8 +37,9 @@ public int seatsAvailable(SeatFormula formula) { return formula.seatsAvailable(this); } + /** Free and not held by a pending offer: what a new booking or a new offer can take. */ public int accommodationAvailable() { - return Math.max(0, accommodationCapacity - accommodationUsed); + return Math.max(0, accommodationCapacity - accommodationUsed - accommodationHeld); } public boolean isFull() { @@ -38,7 +48,7 @@ public boolean isFull() { /** True when an extra-time booking cannot get an accommodation seat (usp_BookSeat state 3). */ public boolean accommodationExhausted() { - return accommodationUsed >= accommodationCapacity; + return accommodationUsed + accommodationHeld >= accommodationCapacity; } /** False only for ET25/ET50 once every accommodation seat is taken; SR, RB and no code never need one. */ diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistOfferRules.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistOfferRules.java new file mode 100644 index 00000000..85cf871f --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistOfferRules.java @@ -0,0 +1,43 @@ +package com.northwind.scheduling.domain; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +/** + * Who gets a freed seat (MBA-3829, ADR 0004). Deliberate change from legacy, where usp_CancelBooking promotes + * nobody (HB-06, MR-12, ODD-09): every seat that is free and not held is offered, in waitlist position order, + * to the first entry whose accommodation needs fit. An ET25/ET50 entry is skipped (and keeps its place) while no + * accommodation seat is free; SR/RB/none only need a seat. Only OPEN sessions make offers. + */ +public final class WaitlistOfferRules { + + private WaitlistOfferRules() { + } + + /** Entries to offer a seat to now, in position order; one per free, unheld seat. */ + public static List select(SessionStatus status, SessionCapacity seats, List waitlist) { + List offers = new ArrayList<>(); + if (status == null || !status.acceptsBookings()) { + return offers; + } + int free = seats.seatsAvailable(); + int accommodationFree = seats.accommodationAvailable(); + List ordered = waitlist.stream() + .sorted(Comparator.comparingInt(WaitlistSlot::position)).toList(); + for (WaitlistSlot w : ordered) { + if (free == 0) { + break; + } + if (w.needsAccommodationSeat()) { + if (accommodationFree == 0) { + continue; + } + accommodationFree--; + } + offers.add(w); + free--; + } + return offers; + } +} diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistSlot.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistSlot.java new file mode 100644 index 00000000..4e890efe --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistSlot.java @@ -0,0 +1,9 @@ +package com.northwind.scheduling.domain; + +/** A WAITLISTED booking without a pending offer, as seen by {@link WaitlistOfferRules}. */ +public record WaitlistSlot(int bookingId, int position, String accommodationCode) { + + public boolean needsAccommodationSeat() { + return AccommodationCodes.isExtraTime(accommodationCode); + } +} diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/importer/SnapshotWriter.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/importer/SnapshotWriter.java index 9af7a2ce..f8d0ff58 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/importer/SnapshotWriter.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/importer/SnapshotWriter.java @@ -142,11 +142,12 @@ public void clearInventory() { // events for the inventory being replaced are moot: the re-import reads the legacy rows they targeted jdbc.update("DELETE FROM outbox_event WHERE relayed_at IS NULL"); jdbc.update("DELETE FROM capacity_change"); + jdbc.update("DELETE FROM seat_offer"); jdbc.update("DELETE FROM waitlist_entry"); jdbc.update("UPDATE booking SET rescheduled_from = NULL WHERE rescheduled_from IS NOT NULL"); jdbc.update("DELETE FROM booking"); jdbc.update("DELETE FROM exam_session"); - for (String table : List.of("waitlist_entry", "booking", "exam_session")) { + for (String table : List.of("seat_offer", "waitlist_entry", "booking", "exam_session")) { jdbc.execute("DBCC CHECKIDENT ('" + table + "', RESEED, 0) WITH NO_INFOMSGS"); } } diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxEventType.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxEventType.java index db9cc4dd..9b83bdf5 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxEventType.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxEventType.java @@ -1,6 +1,6 @@ package com.northwind.scheduling.outbox; -/** Outbox event types (MBA-3823); ck_outbox_event_type in V2__outbox.sql lists the same names. */ +/** Outbox event types (MBA-3823); ck_outbox_event_type (V2__outbox.sql, V3__waitlist_offers.sql) lists the same names. */ public enum OutboxEventType { BookingCreated("Booking", "BOOK"), BookingCancelled("Booking", "CANCEL"), @@ -9,7 +9,17 @@ public enum OutboxEventType { AttendanceRecorded("Booking", "ATTENDED"), CapacityChanged("ExamSession", "CAPACITY_CHANGE"), /** after a snapshot import: SeatsAvailable for every session (scheduling-service is the single seat writer) */ - InventoryBaselined("ExamSession", "SEAT_BASELINE"); + InventoryBaselined("ExamSession", "SEAT_BASELINE"), + /** MBA-3829 (ADR 0004): a held seat offered to a waitlisted booking; legacy rows unchanged (still WAITLISTED) */ + SeatOffered("Booking", "WAITLIST_OFFER"), + /** offer accepted: booking BOOKED, waitlist row removed, later positions shifted up */ + SeatOfferAccepted("Booking", "WAITLIST_OFFER_ACCEPT"), + /** offer declined: booking CANCELLED, waitlist row removed, later positions shifted up */ + SeatOfferDeclined("Booking", "WAITLIST_OFFER_DECLINE"), + /** offer expired (scheduling.waitlist.offer-ttl): booking CANCELLED, waitlist row removed, positions shifted */ + SeatOfferExpired("Booking", "WAITLIST_OFFER_EXPIRE"), + /** offer withdrawn (candidate cancelled/rescheduled, or capacity reduced); candidate keeps the waitlist place */ + SeatOfferWithdrawn("Booking", "WAITLIST_OFFER_WITHDRAW"); private final String aggregateType; private final String auditAction; diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/persistence/Rows.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/persistence/Rows.java index 4a44544b..1a97ff9f 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/persistence/Rows.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/persistence/Rows.java @@ -24,9 +24,10 @@ public record Candidate(int id, String number, String firstName, String lastName public record Session(int sessionId, int examId, String examCode, String examTitle, int centerId, String centerCode, String centerName, String roomName, LocalDateTime startsAt, int capacity, int accommodationCapacity, SessionStatus status, int occupied, int accommodationUsed, - int waitlisted) { + int waitlisted, int held, int accommodationHeld) { public SessionCapacity seats() { - return new SessionCapacity(capacity, accommodationCapacity, occupied, accommodationUsed, waitlisted); + return new SessionCapacity(capacity, accommodationCapacity, occupied, accommodationUsed, waitlisted, held, + accommodationHeld); } } @@ -34,11 +35,21 @@ public record Booking(int bookingId, int sessionId, int candidateId, String cand int examId, String examCode, String examTitle, String centerCode, String centerName, LocalDateTime sessionStartsAt, BookingStatus status, String accommodationCode, String channel, String externalRef, LocalDateTime bookedAt, LocalDateTime cancelledAt, String cancelReason, - Integer rescheduledFrom, Integer waitlistPosition) { + Integer rescheduledFrom, Integer waitlistPosition, OfferRef offer) { } + /** offer: the pending seat offer of this entry, null when none (MBA-3829) */ public record WaitlistEntry(int position, int bookingId, String candidateNumber, String candidateName, - String accommodationCode, LocalDateTime addedAt) { + String accommodationCode, LocalDateTime addedAt, OfferRef offer) { + } + + /** Latest seat offer of a booking (MBA-3829). */ + public record OfferRef(int offerId, String status, LocalDateTime offeredAt, LocalDateTime expiresAt) { + } + + public record Offer(int offerId, int sessionId, int bookingId, int candidateId, String candidateNumber, int position, + String status, LocalDateTime offeredAt, LocalDateTime expiresAt, LocalDateTime resolvedAt, + String resolution, String accommodationCode) { } public record CapacityChangeRow(int id, int sessionId, int oldCapacity, int newCapacity, int demotedBookings, diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/persistence/SchedulingRepository.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/persistence/SchedulingRepository.java index 44cd23d0..f45aad08 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/persistence/SchedulingRepository.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/persistence/SchedulingRepository.java @@ -27,7 +27,8 @@ public class SchedulingRepository { private static final String SESSION_SELECT = """ SELECT s.session_id, s.exam_id, e.exam_code, e.title AS exam_title, s.test_center_id, c.center_code, c.name AS center_name, r.room_name, s.starts_at, s.capacity, s.accommodation_capacity, s.status, - ISNULL(x.occupied, 0) AS occupied, ISNULL(x.acc_used, 0) AS acc_used, ISNULL(x.waitlisted, 0) AS waitlisted + ISNULL(x.occupied, 0) AS occupied, ISNULL(x.acc_used, 0) AS acc_used, ISNULL(x.waitlisted, 0) AS waitlisted, + ISNULL(h.held, 0) AS held, ISNULL(h.acc_held, 0) AS acc_held FROM exam_session s JOIN exam_snapshot e ON e.exam_id = s.exam_id JOIN test_center_snapshot c ON c.test_center_id = s.test_center_id @@ -37,19 +38,34 @@ OUTER APPLY (SELECT SUM(CASE WHEN b.status IN ('BOOKED','ATTENDED') THEN 1 ELSE THEN 1 ELSE 0 END) AS acc_used, SUM(CASE WHEN b.status = 'WAITLISTED' THEN 1 ELSE 0 END) AS waitlisted FROM booking b WHERE b.session_id = s.session_id) x + OUTER APPLY (SELECT COUNT(*) AS held, + SUM(CASE WHEN ob.accommodation_code IN ('ET25','ET50') THEN 1 ELSE 0 END) AS acc_held + FROM seat_offer o JOIN booking ob ON ob.booking_id = o.booking_id + WHERE o.session_id = s.session_id AND o.status = 'PENDING') h """; private static final String BOOKING_SELECT = """ SELECT b.booking_id, b.session_id, b.candidate_id, c.candidate_number, c.first_name + N' ' + c.last_name AS candidate_name, s.exam_id, e.exam_code, e.title AS exam_title, t.center_code, t.name AS center_name, s.starts_at, b.status, b.accommodation_code, b.channel, - b.external_ref, b.booked_at, b.cancelled_at, b.cancel_reason, b.rescheduled_from, w.position + b.external_ref, b.booked_at, b.cancelled_at, b.cancel_reason, b.rescheduled_from, w.position, + o.offer_id, o.status AS offer_status, o.offered_at, o.expires_at FROM booking b JOIN candidate_snapshot c ON c.candidate_id = b.candidate_id JOIN exam_session s ON s.session_id = b.session_id JOIN exam_snapshot e ON e.exam_id = s.exam_id JOIN test_center_snapshot t ON t.test_center_id = s.test_center_id LEFT JOIN waitlist_entry w ON w.booking_id = b.booking_id + OUTER APPLY (SELECT TOP 1 so.offer_id, so.status, so.offered_at, so.expires_at FROM seat_offer so + WHERE so.booking_id = b.booking_id ORDER BY so.offer_id DESC) o + """; + + private static final String OFFER_SELECT = """ + SELECT o.offer_id, o.session_id, o.booking_id, o.candidate_id, c.candidate_number, o.position, o.status, + o.offered_at, o.expires_at, o.resolved_at, o.resolution, b.accommodation_code + FROM seat_offer o + JOIN candidate_snapshot c ON c.candidate_id = o.candidate_id + JOIN booking b ON b.booking_id = o.booking_id """; private final JdbcClient db; @@ -73,7 +89,7 @@ static Rows.Session session(ResultSet rs, int i) throws SQLException { rs.getString("exam_title"), rs.getInt("test_center_id"), rs.getString("center_code"), rs.getString("center_name"), rs.getString("room_name"), ldt(rs, "starts_at"), rs.getInt("capacity"), rs.getInt("accommodation_capacity"), SessionStatus.valueOf(rs.getString("status")), rs.getInt("occupied"), - rs.getInt("acc_used"), rs.getInt("waitlisted")); + rs.getInt("acc_used"), rs.getInt("waitlisted"), rs.getInt("held"), rs.getInt("acc_held")); } static Rows.Booking booking(ResultSet rs, int i) throws SQLException { @@ -83,7 +99,16 @@ static Rows.Booking booking(ResultSet rs, int i) throws SQLException { rs.getString("center_name"), ldt(rs, "starts_at"), BookingStatus.valueOf(rs.getString("status")), rs.getString("accommodation_code"), rs.getString("channel"), rs.getString("external_ref"), ldt(rs, "booked_at"), ldt(rs, "cancelled_at"), rs.getString("cancel_reason"), - intOrNull(rs, "rescheduled_from"), intOrNull(rs, "position")); + intOrNull(rs, "rescheduled_from"), intOrNull(rs, "position"), + rs.getObject("offer_id") == null ? null : new Rows.OfferRef(rs.getInt("offer_id"), + rs.getString("offer_status"), ldt(rs, "offered_at"), ldt(rs, "expires_at"))); + } + + static Rows.Offer offer(ResultSet rs, int i) throws SQLException { + return new Rows.Offer(rs.getInt("offer_id"), rs.getInt("session_id"), rs.getInt("booking_id"), + rs.getInt("candidate_id"), rs.getString("candidate_number"), rs.getInt("position"), + rs.getString("status"), ldt(rs, "offered_at"), ldt(rs, "expires_at"), ldt(rs, "resolved_at"), + rs.getString("resolution"), rs.getString("accommodation_code")); } // ------------------------------------------------------------------ reference data @@ -268,14 +293,89 @@ public void deleteWaitlistEntry(int bookingId) { /** Only WAITLISTED bookings are listed (a cancelled one has had its row removed - usp_CancelBooking). */ public List waitlist(int sessionId) { + return db.sql(""" + SELECT w.position, w.booking_id, c.candidate_number, c.first_name + N' ' + c.last_name, b.accommodation_code, w.added_at, + o.offer_id, o.status AS offer_status, o.offered_at, o.expires_at + FROM waitlist_entry w + JOIN booking b ON b.booking_id = w.booking_id + JOIN candidate_snapshot c ON c.candidate_id = w.candidate_id + LEFT JOIN seat_offer o ON o.booking_id = w.booking_id AND o.status = 'PENDING' + WHERE w.session_id = ? AND b.status = 'WAITLISTED' + ORDER BY w.position, w.waitlist_entry_id""").param(sessionId) + .query((rs, i) -> new Rows.WaitlistEntry(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getString(4), + rs.getString(5), ldt(rs, "added_at"), rs.getObject("offer_id") == null ? null + : new Rows.OfferRef(rs.getInt("offer_id"), rs.getString("offer_status"), + ldt(rs, "offered_at"), ldt(rs, "expires_at")))).list(); + } + + /** Remaining waitlist entries after {@code position} move up by one (MBA-3829); returns the moved booking ids. */ + public List shiftWaitlistAfter(int sessionId, int position) { + List moved = db.sql("SELECT booking_id FROM waitlist_entry WHERE session_id = ? AND position > ? ORDER BY position") + .params(sessionId, position).query(Integer.class).list(); + db.sql("UPDATE waitlist_entry SET position = position - 1 WHERE session_id = ? AND position > ?") + .params(sessionId, position).update(); + return moved; + } + + public void markBooked(int bookingId, LocalDateTime now) { + db.sql("UPDATE booking SET status = 'BOOKED', last_modified = ? WHERE booking_id = ? AND status = 'WAITLISTED'") + .params(Timestamp.valueOf(now), bookingId).update(); + } + + // ------------------------------------------------------------------ seat offers (MBA-3829) + + /** WAITLISTED entries without a pending offer, lowest position first (offer candidates). */ + public List unofferedWaitlist(int sessionId) { return db.sql(""" SELECT w.position, w.booking_id, c.candidate_number, c.first_name + N' ' + c.last_name, b.accommodation_code, w.added_at FROM waitlist_entry w JOIN booking b ON b.booking_id = w.booking_id JOIN candidate_snapshot c ON c.candidate_id = w.candidate_id WHERE w.session_id = ? AND b.status = 'WAITLISTED' + AND NOT EXISTS (SELECT 1 FROM seat_offer o WHERE o.booking_id = w.booking_id AND o.status = 'PENDING') ORDER BY w.position, w.waitlist_entry_id""").param(sessionId) .query((rs, i) -> new Rows.WaitlistEntry(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getString(4), - rs.getString(5), ldt(rs, "added_at"))).list(); + rs.getString(5), ldt(rs, "added_at"), null)).list(); + } + + public int insertOffer(int sessionId, int bookingId, int position, LocalDateTime now, LocalDateTime expiresAt) { + return db.sql("INSERT INTO seat_offer (session_id, booking_id, candidate_id, position, status, offered_at, expires_at) " + + "OUTPUT INSERTED.offer_id SELECT session_id, booking_id, candidate_id, ?, 'PENDING', ?, ? FROM booking " + + "WHERE booking_id = ?") + .params(position, Timestamp.valueOf(now), Timestamp.valueOf(expiresAt), bookingId) + .query(Integer.class).single(); + } + + public Optional offer(int offerId) { + return db.sql(OFFER_SELECT + " WHERE o.offer_id = ?").param(offerId).query(SchedulingRepository::offer).optional(); + } + + public Optional pendingOfferForBooking(int bookingId) { + return db.sql(OFFER_SELECT + " WHERE o.booking_id = ? AND o.status = 'PENDING'").param(bookingId) + .query(SchedulingRepository::offer).optional(); + } + + /** Pending offers of a session, newest first (withdrawn first when capacity shrinks). */ + public List pendingOffers(int sessionId) { + return db.sql(OFFER_SELECT + " WHERE o.session_id = ? AND o.status = 'PENDING' ORDER BY o.offer_id DESC") + .param(sessionId).query(SchedulingRepository::offer).list(); + } + + public List offersForSession(int sessionId) { + return db.sql(OFFER_SELECT + " WHERE o.session_id = ? ORDER BY o.offer_id").param(sessionId) + .query(SchedulingRepository::offer).list(); + } + + /** Pending offers whose expiry is at or before {@code now}, oldest first. */ + public List expiredPendingOffers(LocalDateTime now, int limit) { + return db.sql("SELECT TOP (" + Math.max(1, limit) + ") * FROM (" + OFFER_SELECT + + " WHERE o.status = 'PENDING' AND o.expires_at <= ?) q ORDER BY q.expires_at, q.offer_id") + .param(Timestamp.valueOf(now)).query(SchedulingRepository::offer).list(); + } + + /** PENDING -> {@code status}; false when the offer was already resolved (lost a race). */ + public boolean resolveOffer(int offerId, String status, String resolution, LocalDateTime now) { + return db.sql("UPDATE seat_offer SET status = ?, resolution = ?, resolved_at = ? WHERE offer_id = ? AND status = 'PENDING'") + .params(status, resolution, Timestamp.valueOf(now), offerId).update() > 0; } } diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/service/SchedulingService.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/service/SchedulingService.java index e5e55eb7..aa69c0f5 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/service/SchedulingService.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/service/SchedulingService.java @@ -7,6 +7,7 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; +import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Value; @@ -20,6 +21,7 @@ import com.northwind.scheduling.domain.CapacityChange; import com.northwind.scheduling.domain.EligibilityDecision; import com.northwind.scheduling.domain.ErrorCode; +import com.northwind.scheduling.domain.OfferStatus; import com.northwind.scheduling.domain.ReschedulePolicy; import com.northwind.scheduling.domain.RetakeEligibilityPolicy; import com.northwind.scheduling.domain.SchedulingException; @@ -46,11 +48,14 @@ public record CapacityOutcome(CapacityChange.Plan plan, Rows.Session session) { private final Clock clock; private final String actor; private final OutboxRepository outbox; + private final WaitlistOfferPolicy offers; public SchedulingService(SchedulingRepository repo, RetakeEligibilityPolicy retakePolicy, AccommodationFloorPolicy floorPolicy, Clock clock, - @Value("${scheduling.actor:scheduling-service}") String actor, OutboxRepository outbox) { + @Value("${scheduling.actor:scheduling-service}") String actor, OutboxRepository outbox, + WaitlistOfferPolicy offers) { this.repo = repo; + this.offers = offers; this.outbox = outbox; this.retakePolicy = retakePolicy; this.floorPolicy = floorPolicy; @@ -169,22 +174,122 @@ private BookingOutcome book(BookCommand cmd, Integer rescheduledFrom) { return new BookingOutcome(bookingId, status, position, sessionId); } - /** usp_CancelBooking: frees the seat (derived count), drops the waitlist row, no promotion (ODD-09). */ + /** + * usp_CancelBooking: frees the seat (derived count), drops the waitlist row (positions keep their gap, HB-06). + * Unlike legacy (ODD-09) a freed or released held seat is offered to the next eligible waitlist entry + * (MBA-3829, ADR 0004); a pending offer of the cancelled booking is withdrawn. + */ @Transactional public Rows.Booking cancel(int bookingId, String reason) { Rows.Booking b = booking(bookingId); repo.lockSession(b.sessionId()); b = booking(bookingId); BookingRules.checkCancellable(bookingId, b.status()); + boolean seatReleased = withdrawPendingOffer(bookingId, "booking cancelled") || b.status() == BookingStatus.BOOKED; repo.markCancelled(bookingId, reason, now()); if (b.status() == BookingStatus.WAITLISTED) { repo.deleteWaitlistEntry(bookingId); } outbox.append(OutboxEventType.BookingCancelled, bookingId, List.of(bookingId), List.of(b.sessionId()), actor, "reason=" + reason); + if (seatReleased) { + offers.offerFreedSeats(b.sessionId(), "cancel booking=" + bookingId); + } return booking(bookingId); } + private boolean withdrawPendingOffer(int bookingId, String reason) { + return repo.pendingOfferForBooking(bookingId).map(o -> { + offers.withdraw(o, reason); + return true; + }).orElse(false); + } + + // ------------------------------------------------------------------ waitlist offers (MBA-3829, ADR 0004) + + public Rows.Offer offer(int offerId) { + return repo.offer(offerId).orElseThrow( + () -> new SchedulingException(ErrorCode.OFFER_NOT_FOUND, "Offer " + offerId + " not found")); + } + + private static void requirePending(Rows.Offer o, LocalDateTime now) { + if (!OfferStatus.PENDING.name().equals(o.status())) { + throw new SchedulingException(ErrorCode.OFFER_NOT_PENDING, "Offer " + o.offerId() + " is " + o.status()); + } + if (!o.expiresAt().isAfter(now)) { + throw new SchedulingException(ErrorCode.OFFER_NOT_PENDING, + "Offer " + o.offerId() + " expired at " + o.expiresAt()); + } + } + + /** PENDING offer accepted before expiry: the waitlisted booking becomes BOOKED and leaves the waitlist. */ + @Transactional + public Rows.Booking acceptOffer(int offerId) { + Rows.Offer o = offer(offerId); + repo.lockSession(o.sessionId()); + o = offer(offerId); + LocalDateTime now = now(); + requirePending(o, now); + Rows.Booking b = booking(o.bookingId()); + repo.resolveOffer(offerId, OfferStatus.ACCEPTED.name(), "accepted", now); + repo.markBooked(b.bookingId(), now); + List changed = removeFromWaitlist(b); + outbox.append(OutboxEventType.SeatOfferAccepted, b.bookingId(), changed, List.of(o.sessionId()), actor, + "offer=" + offerId); + return booking(b.bookingId()); + } + + /** The candidate turns the seat down: their waitlisted booking is cancelled and the seat goes to the next entry. */ + @Transactional + public Rows.Booking declineOffer(int offerId) { + Rows.Offer o = offer(offerId); + repo.lockSession(o.sessionId()); + o = offer(offerId); + if (!OfferStatus.PENDING.name().equals(o.status())) { + throw new SchedulingException(ErrorCode.OFFER_NOT_PENDING, "Offer " + offerId + " is " + o.status()); + } + closeOffer(o, OfferStatus.DECLINED, OutboxEventType.SeatOfferDeclined, "Waitlist offer declined"); + return booking(o.bookingId()); + } + + /** Ids of PENDING offers whose expiry has passed (scheduled by WaitlistOfferExpiryJob). */ + public List dueOfferIds() { + return repo.expiredPendingOffers(now(), 100).stream().map(Rows.Offer::offerId).toList(); + } + + /** Expires one due offer and offers the seat on; false when it was resolved meanwhile or is not due. */ + @Transactional + public boolean expireOffer(int offerId) { + Rows.Offer o = offer(offerId); + repo.lockSession(o.sessionId()); + o = offer(offerId); + if (!OfferStatus.PENDING.name().equals(o.status()) || o.expiresAt().isAfter(now())) { + return false; + } + closeOffer(o, OfferStatus.EXPIRED, OutboxEventType.SeatOfferExpired, "Waitlist offer expired"); + return true; + } + + private void closeOffer(Rows.Offer o, OfferStatus status, OutboxEventType event, String reason) { + LocalDateTime now = now(); + Rows.Booking b = booking(o.bookingId()); + repo.resolveOffer(o.offerId(), status.name(), reason, now); + repo.markCancelled(b.bookingId(), reason, now); + List changed = removeFromWaitlist(b); + outbox.append(event, b.bookingId(), changed, List.of(o.sessionId()), actor, "offer=" + o.offerId()); + offers.offerFreedSeats(o.sessionId(), status.name().toLowerCase() + " offer=" + o.offerId()); + } + + /** Drops the booking's waitlist row and moves later entries up one; returns the booking plus the moved ones. */ + private List removeFromWaitlist(Rows.Booking b) { + repo.deleteWaitlistEntry(b.bookingId()); + List changed = new ArrayList<>(List.of(b.bookingId())); + if (b.waitlistPosition() != null) { + changed.addAll(repo.shiftWaitlistAfter(b.sessionId(), b.waitlistPosition())); + } + return changed; + } + /** * MBA-3823: results-service reports attendance here instead of updating dbo.Booking. BOOKED becomes ATTENDED * (one AttendanceRecorded event); an already ATTENDED booking is a no-op, so ingestion retries are safe. @@ -225,6 +330,8 @@ public BookingOutcome reschedule(int bookingId, Integer newSessionId) { repo.lockSession(Math.max(old.sessionId(), newSessionId)); old = booking(bookingId); ReschedulePolicy.check(bookingId, old.status(), old.sessionId(), old.examId(), newSessionId, newExam); + boolean seatReleased = withdrawPendingOffer(bookingId, "booking rescheduled") + || old.status() == BookingStatus.BOOKED; repo.markCancelled(bookingId, ReschedulePolicy.CANCEL_REASON, now()); if (old.status() == BookingStatus.WAITLISTED) { repo.deleteWaitlistEntry(bookingId); @@ -233,6 +340,9 @@ public BookingOutcome reschedule(int bookingId, Integer newSessionId) { old.externalRef(), old.channel()), bookingId); outbox.append(OutboxEventType.BookingRescheduled, moved.bookingId(), List.of(bookingId, moved.bookingId()), List.of(old.sessionId(), newSessionId), actor, "from=" + bookingId + " to=" + moved.bookingId()); + if (seatReleased) { + offers.offerFreedSeats(old.sessionId(), "reschedule booking=" + bookingId); + } return moved; } @@ -259,6 +369,8 @@ public CapacityOutcome changeCapacity(int sessionId, Integer newCapacity, String plan.demotions().stream().map(CapacityChange.Demotion::bookingId).toList(), List.of(sessionId), actor, "capacity=" + plan.newCapacity() + " demoted=" + plan.demotions().size() + (reason == null ? "" : " reason=" + reason)); + offers.withdrawExcess(sessionId, "capacity reduced to " + plan.newCapacity()); + offers.offerFreedSeats(sessionId, "capacity=" + plan.newCapacity()); return new CapacityOutcome(plan, session(sessionId)); } } diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferExpiryJob.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferExpiryJob.java new file mode 100644 index 00000000..1a814906 --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferExpiryJob.java @@ -0,0 +1,40 @@ +package com.northwind.scheduling.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; + +/** Expires PENDING seat offers past scheduling.waitlist.offer-ttl and offers the seat on (MBA-3829). */ +@Configuration +@EnableScheduling +@ConditionalOnProperty(name = "scheduling.waitlist.expiry-enabled", havingValue = "true", matchIfMissing = true) +public class WaitlistOfferExpiryJob { + + private static final Logger log = LoggerFactory.getLogger(WaitlistOfferExpiryJob.class); + + private final SchedulingService service; + + public WaitlistOfferExpiryJob(SchedulingService service) { + this.service = service; + } + + @Scheduled(fixedDelayString = "${scheduling.waitlist.expiry-poll:PT1M}", initialDelayString = "${scheduling.waitlist.expiry-poll:PT1M}") + public void expireDueOffers() { + try { + int n = 0; + for (int offerId : service.dueOfferIds()) { + if (service.expireOffer(offerId)) { + n++; + } + } + if (n > 0) { + log.info("waitlist offers expired={}", n); + } + } catch (RuntimeException e) { + log.warn("waitlist offer expiry failed: {}", e.toString()); + } + } +} diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferPolicy.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferPolicy.java new file mode 100644 index 00000000..bc74d2af --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferPolicy.java @@ -0,0 +1,112 @@ +package com.northwind.scheduling.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import com.northwind.scheduling.domain.ErrorCode; +import com.northwind.scheduling.domain.OfferStatus; +import com.northwind.scheduling.domain.SchedulingException; +import com.northwind.scheduling.domain.SessionCapacity; +import com.northwind.scheduling.domain.WaitlistOfferRules; +import com.northwind.scheduling.domain.WaitlistSlot; +import com.northwind.scheduling.outbox.OutboxEventType; +import com.northwind.scheduling.outbox.OutboxRepository; +import com.northwind.scheduling.persistence.Rows; +import com.northwind.scheduling.persistence.SchedulingRepository; + +/** + * Waitlist auto-offer (MBA-3829, ADR 0004). Callers hold the session lock (SchedulingRepository.lockSession) and + * a transaction, so offers, the change that freed the seat and their outbox events commit together and two + * concurrent seat releases cannot offer the same seat twice. + */ +@Component +public class WaitlistOfferPolicy { + + private final SchedulingRepository repo; + private final OutboxRepository outbox; + private final Clock clock; + private final Duration ttl; + private final String actor; + + public WaitlistOfferPolicy(SchedulingRepository repo, OutboxRepository outbox, Clock clock, + @Value("${scheduling.waitlist.offer-ttl:PT24H}") Duration ttl, + @Value("${scheduling.actor:scheduling-service}") String actor) { + if (ttl.isNegative() || ttl.isZero()) { + throw new IllegalArgumentException("scheduling.waitlist.offer-ttl must be positive"); + } + this.repo = repo; + this.outbox = outbox; + this.clock = clock; + this.ttl = ttl; + this.actor = actor; + } + + public Duration ttl() { + return ttl; + } + + private LocalDateTime now() { + return LocalDateTime.now(clock).truncatedTo(ChronoUnit.SECONDS); + } + + private Rows.Session session(int sessionId) { + return repo.session(sessionId).orElseThrow( + () -> new SchedulingException(ErrorCode.SESSION_NOT_FOUND, "Session " + sessionId + " not found")); + } + + /** Offers every free, unheld seat of the session to the next eligible waitlist entries; returns the offer ids. */ + public List offerFreedSeats(int sessionId, String trigger) { + Rows.Session s = session(sessionId); + List waitlist = repo.unofferedWaitlist(sessionId).stream() + .map(w -> new WaitlistSlot(w.bookingId(), w.position(), w.accommodationCode())).toList(); + List chosen = WaitlistOfferRules.select(s.status(), s.seats(), waitlist); + List offerIds = new ArrayList<>(); + LocalDateTime now = now(); + LocalDateTime expiresAt = now.plus(ttl); + for (WaitlistSlot w : chosen) { + int offerId = repo.insertOffer(sessionId, w.bookingId(), w.position(), now, expiresAt); + outbox.append(OutboxEventType.SeatOffered, w.bookingId(), List.of(w.bookingId()), List.of(sessionId), actor, + "offer=" + offerId + " position=" + w.position() + " expires=" + expiresAt + " trigger=" + trigger); + offerIds.add(offerId); + } + return offerIds; + } + + /** + * After a capacity reduction: withdraws the newest pending offers until the held seats fit again (seats and + * accommodation seats). The candidates keep their waitlist place. + */ + public List withdrawExcess(int sessionId, String reason) { + List withdrawn = new ArrayList<>(); + while (true) { + SessionCapacity c = session(sessionId).seats(); + boolean seatExcess = c.heldSeats() > 0 && c.occupiedSeats() + c.heldSeats() > c.capacity(); + boolean accommodationExcess = c.accommodationHeld() > 0 + && c.accommodationUsed() + c.accommodationHeld() > c.accommodationCapacity(); + if (!seatExcess && !accommodationExcess) { + return withdrawn; + } + Rows.Offer victim = repo.pendingOffers(sessionId).stream() + .filter(o -> seatExcess || new WaitlistSlot(o.bookingId(), o.position(), o.accommodationCode()) + .needsAccommodationSeat()) + .findFirst().orElseThrow(); + withdraw(victim, reason); + withdrawn.add(victim.offerId()); + } + } + + /** PENDING -> WITHDRAWN; the booking keeps its WAITLISTED state and position. */ + public void withdraw(Rows.Offer offer, String reason) { + if (repo.resolveOffer(offer.offerId(), OfferStatus.WITHDRAWN.name(), reason, now())) { + outbox.append(OutboxEventType.SeatOfferWithdrawn, offer.bookingId(), List.of(offer.bookingId()), + List.of(offer.sessionId()), actor, "offer=" + offer.offerId() + " reason=" + reason); + } + } +} diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/Dtos.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/Dtos.java index 2139c464..6c6b0d14 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/Dtos.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/Dtos.java @@ -27,11 +27,12 @@ static ExamDto of(Rows.Exam e) { public record SessionDto(int sessionId, String examCode, String examTitle, String centerCode, String centerName, String roomName, LocalDateTime startsAt, String status, int capacity, int accommodationCapacity, int bookedSeats, int seatsAvailable, int accommodationUsed, - int accommodationAvailable, int waitlistCount) { + int accommodationAvailable, int waitlistCount, int heldSeats) { static SessionDto of(Rows.Session s) { return new SessionDto(s.sessionId(), s.examCode(), s.examTitle(), s.centerCode(), s.centerName(), s.roomName(), s.startsAt(), s.status().name(), s.capacity(), s.accommodationCapacity(), s.occupied(), - s.seats().seatsAvailable(), s.accommodationUsed(), s.seats().accommodationAvailable(), s.waitlisted()); + s.seats().seatsAvailable(), s.accommodationUsed(), s.seats().accommodationAvailable(), s.waitlisted(), + s.held()); } } @@ -39,15 +40,31 @@ public record BookingDto(int bookingId, int sessionId, String candidateNumber, S String examTitle, String centerCode, String centerName, LocalDateTime sessionStartsAt, String status, String accommodationCode, String channel, String externalRef, LocalDateTime bookedAt, LocalDateTime cancelledAt, String cancelReason, - Integer waitlistPosition, Integer rescheduledFrom) { + Integer waitlistPosition, Integer rescheduledFrom, Integer offerId, String offerStatus, + LocalDateTime offerExpiresAt) { static BookingDto of(Rows.Booking b) { + Rows.OfferRef o = b.offer(); return new BookingDto(b.bookingId(), b.sessionId(), b.candidateNumber(), b.candidateName(), b.examCode(), b.examTitle(), b.centerCode(), b.centerName(), b.sessionStartsAt(), b.status().name(), b.accommodationCode(), b.channel(), b.externalRef(), b.bookedAt(), b.cancelledAt(), b.cancelReason(), - b.waitlistPosition(), b.rescheduledFrom()); + b.waitlistPosition(), b.rescheduledFrom(), o == null ? null : o.offerId(), + o == null ? null : o.status(), o == null ? null : o.expiresAt()); } } + /** MBA-3829: a seat offered to a waitlisted booking (ADR 0004). */ + public record OfferDto(int offerId, int sessionId, int bookingId, String candidateNumber, int position, String status, + LocalDateTime offeredAt, LocalDateTime expiresAt, LocalDateTime resolvedAt) { + static OfferDto of(Rows.Offer o) { + return new OfferDto(o.offerId(), o.sessionId(), o.bookingId(), o.candidateNumber(), o.position(), o.status(), + o.offeredAt(), o.expiresAt(), o.resolvedAt()); + } + } + + /** POST /offers/{offerId}/accept|decline: the resolved offer plus the live booking and session. */ + public record OfferResultDto(OfferDto offer, BookingDto booking, SessionDto session) { + } + /** POST /bookings and /reschedule: legacy {bookingId, status} plus the live session and booking. */ public record BookingResultDto(int bookingId, String status, Integer waitlistPosition, BookingDto booking, SessionDto session) { @@ -69,10 +86,13 @@ static EligibilityDto of(String cand, String exam, LocalDate date, EligibilityDe } public record WaitlistEntryDto(int position, int bookingId, String candidateNumber, String candidateName, - String accommodationCode, LocalDateTime addedAt) { + String accommodationCode, LocalDateTime addedAt, Integer offerId, String offerStatus, + LocalDateTime offerExpiresAt) { static WaitlistEntryDto of(Rows.WaitlistEntry w) { + Rows.OfferRef o = w.offer(); return new WaitlistEntryDto(w.position(), w.bookingId(), w.candidateNumber(), w.candidateName(), - w.accommodationCode(), w.addedAt()); + w.accommodationCode(), w.addedAt(), o == null ? null : o.offerId(), o == null ? null : o.status(), + o == null ? null : o.expiresAt()); } } diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/OpenApiConfig.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/OpenApiConfig.java index 30204577..6a18136a 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/OpenApiConfig.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/OpenApiConfig.java @@ -48,6 +48,9 @@ public class OpenApiConfig { static final String ERROR_SCHEMA = "ApiError"; /** 401 body of service-token operations; kept out of ApiError so its enum stays compatible with published baselines. */ static final String SERVICE_TOKEN_ERROR_SCHEMA = "ServiceTokenError"; + /** 4xx body of the MBA-3829 offer operations; kept out of ApiError for the same reason. */ + static final String OFFER_ERROR_SCHEMA = "OfferError"; + static final Set OFFER_ERRORS = Set.of(ErrorCode.OFFER_NOT_FOUND, ErrorCode.OFFER_NOT_PENDING); static final Set SESSION_TIMES = Set.of("startsAt", "sessionStartsAt"); static final String LOCAL_DATE_TIME_PATTERN = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$"; @@ -73,7 +76,10 @@ public class OpenApiConfig { Map.entry("candidate", List.of(ErrorCode.CANDIDATE_NOT_FOUND)), Map.entry("candidateBookings", List.of(ErrorCode.CANDIDATE_NOT_FOUND)), Map.entry("eligibility", List.of(ErrorCode.VALIDATION, ErrorCode.CANDIDATE_NOT_FOUND, - ErrorCode.EXAM_NOT_FOUND))); + ErrorCode.EXAM_NOT_FOUND)), + Map.entry("offer", List.of(ErrorCode.BAD_REQUEST, ErrorCode.OFFER_NOT_FOUND)), + Map.entry("acceptOffer", List.of(ErrorCode.BAD_REQUEST, ErrorCode.OFFER_NOT_FOUND, ErrorCode.OFFER_NOT_PENDING)), + Map.entry("declineOffer", List.of(ErrorCode.BAD_REQUEST, ErrorCode.OFFER_NOT_FOUND, ErrorCode.OFFER_NOT_PENDING))); /** operationId -> tag, summary. */ static final Map OPERATIONS = Map.ofEntries( @@ -88,7 +94,13 @@ public class OpenApiConfig { Map.entry("book", new String[] {"Bookings", "Book a seat (WAITLISTED when the session is full); returns the legacy {bookingId, status} plus the live booking and session"}), Map.entry("booking", new String[] {"Bookings", "Get a booking"}), - Map.entry("cancel", new String[] {"Bookings", "Cancel a booking (frees the seat, nobody is promoted, ODD-09)"}), + Map.entry("cancel", new String[] {"Bookings", + "Cancel a booking (frees the seat; it is offered to the next eligible waitlist entry, MBA-3829 / ADR 0004)"}), + Map.entry("offer", new String[] {"Offers", "Get a waitlist seat offer"}), + Map.entry("acceptOffer", new String[] {"Offers", + "Accept a pending seat offer (the waitlisted booking becomes BOOKED, later waitlist positions move up)"}), + Map.entry("declineOffer", new String[] {"Offers", + "Decline a pending seat offer (the waitlisted booking is cancelled, the seat is offered to the next entry)"}), Map.entry("attendance", new String[] {"Bookings", "Record attendance (BOOKED -> ATTENDED; already ATTENDED is a no-op). Called by results-service on result ingestion"}), Map.entry("reschedule", new String[] {"Bookings", @@ -109,11 +121,12 @@ public class OpenApiConfig { /** Response properties that can be JSON null (nullable columns of V1__scheduling_schema.sql). */ static final Map> NULLABLE = Map.of( "BookingDto", Set.of("accommodationCode", "externalRef", "cancelledAt", "cancelReason", "waitlistPosition", - "rescheduledFrom"), + "rescheduledFrom", "offerId", "offerStatus", "offerExpiresAt"), "BookingResultDto", Set.of("waitlistPosition"), "CandidateDto", Set.of("defaultAccommodationCode"), "EligibilityDto", Set.of("earliestRetakeDate"), - "WaitlistEntryDto", Set.of("accommodationCode"), + "WaitlistEntryDto", Set.of("accommodationCode", "offerId", "offerStatus", "offerExpiresAt"), + "OfferDto", Set.of("resolvedAt"), "CapacityChangeDto", Set.of("reason")); /** Request properties the service rejects with VALIDATION when missing. */ @@ -138,7 +151,10 @@ public class OpenApiConfig { Map.entry("defaultAccommodationCode", "ET25"), Map.entry("externalRef", "PX-3008"), Map.entry("date", "2026-11-20"), Map.entry("earliestRetakeDate", "2026-12-07"), Map.entry("dayCounting", "calendar"), Map.entry("durationMinutes", 120), Map.entry("retakeWaitDays", 30), - Map.entry("changedBy", "scheduling-service"), Map.entry("reason", "Room maintenance")); + Map.entry("changedBy", "scheduling-service"), Map.entry("reason", "Room maintenance"), + Map.entry("offerId", 7), Map.entry("offeredAt", "2026-11-10T09:15:00"), + Map.entry("expiresAt", "2026-11-11T09:15:00"), Map.entry("offerExpiresAt", "2026-11-11T09:15:00"), + Map.entry("resolvedAt", "2026-11-10T10:00:00"), Map.entry("position", 1), Map.entry("heldSeats", 1)); static final Map ERROR_EXAMPLES = errorExamples(); @@ -161,6 +177,8 @@ private static Map errorExamples() { msg.put(ErrorCode.SAME_SESSION, "Booking 1201 is already on session 154"); msg.put(ErrorCode.NOT_ELIGIBLE, "Candidate NW00000939 is not eligible to book MHL-RN1 (RETAKE_WAIT_NOT_ELAPSED), " + "earliest retake date 2026-12-07"); + msg.put(ErrorCode.OFFER_NOT_FOUND, "Offer 99999 not found"); + msg.put(ErrorCode.OFFER_NOT_PENDING, "Offer 7 is EXPIRED"); Map out = new LinkedHashMap<>(); msg.forEach((code, text) -> { Map body = new LinkedHashMap<>(); @@ -195,21 +213,23 @@ OpenAPI schedulingOpenApi() { Every 4xx is an `ApiError`: `error` is the symbolic code, `message` is human readable, and `legacyCode` is `50000 + RAISERROR state` of the legacy procs (ODD-11, HB-14), e.g. `NO_ACCOMMODATION_SEAT` = 50003, or null when the rule never existed as a proc error. Malformed input (unreadable JSON, wrong path/param type) - answers `BAD_REQUEST` without `legacyCode`. + answers `BAD_REQUEST` without `legacyCode`. The offer operations (MBA-3829) answer `OFFER_NOT_FOUND` and + `OFFER_NOT_PENDING` as an `OfferError` (same shape). """ + errorTable(); return new OpenAPI() .info(new Info().title("Northwind Scheduling API").version(API_VERSION).description(description)) .servers(List.of(new Server().url("/").description("scheduling-service (default :8090)"))) .tags(List.of(new Tag().name("Bookings"), new Tag().name("Candidates"), new Tag().name("Capacity"), - new Tag().name("Reference data"), new Tag().name("Sessions"))) + new Tag().name("Offers"), new Tag().name("Reference data"), new Tag().name("Sessions"))) .components(new Components().addSecuritySchemes(SERVICE_TOKEN, new SecurityScheme() .type(SecurityScheme.Type.APIKEY).in(SecurityScheme.In.HEADER).name(AttendanceTokenGuard.HEADER) .description("Service credential (scheduling.attendance.service-token); results-service only"))); } static Schema errorSchema() { - return errorSchema(Arrays.stream(ErrorCode.values()).filter(c -> c != ErrorCode.UNAUTHORIZED).toList(), + return errorSchema(Arrays.stream(ErrorCode.values()) + .filter(c -> c != ErrorCode.UNAUTHORIZED && !OFFER_ERRORS.contains(c)).toList(), "Error body of every 4xx answer (ApiExceptionHandler)", "No accommodation seat available on session 155"); } @@ -218,6 +238,11 @@ static Schema serviceTokenErrorSchema() { "X-Service-Token missing or invalid"); } + static Schema offerErrorSchema() { + return errorSchema(Arrays.stream(ErrorCode.values()).filter(OFFER_ERRORS::contains).toList(), + "404/409 body of the waitlist offer operations (MBA-3829)", "Offer 7 is EXPIRED"); + } + static Schema errorSchema(List errorCodes, String description, String exampleMessage) { List codes = errorCodes.stream().map(Enum::name).toList(); IntegerSchema legacy = new IntegerSchema(); @@ -253,6 +278,7 @@ void document(OpenAPI api) { } api.getComponents().addSchemas(ERROR_SCHEMA, errorSchema()); api.getComponents().addSchemas(SERVICE_TOKEN_ERROR_SCHEMA, serviceTokenErrorSchema()); + api.getComponents().addSchemas(OFFER_ERROR_SCHEMA, offerErrorSchema()); if (api.getPaths() == null) { return; } @@ -261,7 +287,8 @@ void document(OpenAPI api) { @SuppressWarnings({"rawtypes", "unchecked"}) void documentSchema(String name, Schema schema) { - if (ERROR_SCHEMA.equals(name) || SERVICE_TOKEN_ERROR_SCHEMA.equals(name) || schema.getProperties() == null) { + if (ERROR_SCHEMA.equals(name) || SERVICE_TOKEN_ERROR_SCHEMA.equals(name) || OFFER_ERROR_SCHEMA.equals(name) + || schema.getProperties() == null) { return; } Map props = schema.getProperties(); @@ -303,6 +330,9 @@ void documentSchema(String name, Schema schema) { if (name.equals("SessionDto")) { status.setEnum(Arrays.stream(SessionStatus.values()).map(Enum::name).toList()); status.setExample(SessionStatus.OPEN.name()); + } else if (name.equals("OfferDto")) { + status.setEnum(Arrays.stream(com.northwind.scheduling.domain.OfferStatus.values()).map(Enum::name).toList()); + status.setExample("PENDING"); } else if (name.startsWith("Booking")) { status.setEnum(Arrays.stream(BookingStatus.values()).map(Enum::name).toList()); status.setExample(BookingStatus.BOOKED.name()); @@ -358,7 +388,8 @@ void documentOperation(Operation op) { } byStatus.forEach((status, codes) -> { MediaType mt = new MediaType().schema(new Schema<>().$ref("#/components/schemas/" - + (status == 401 ? SERVICE_TOKEN_ERROR_SCHEMA : ERROR_SCHEMA))); + + (status == 401 ? SERVICE_TOKEN_ERROR_SCHEMA + : OFFER_ERRORS.containsAll(codes) ? OFFER_ERROR_SCHEMA : ERROR_SCHEMA))); for (ErrorCode c : codes) { mt.addExamples(c.name(), new Example().summary(c.name() + (c.legacyCode() == null ? "" : " (legacy " + c.legacyCode() + ")")).value(ERROR_EXAMPLES.get(c.name()))); diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/SchedulingApiController.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/SchedulingApiController.java index 23c9e697..a15933bc 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/SchedulingApiController.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/SchedulingApiController.java @@ -122,6 +122,28 @@ public BookingDto booking(@PathVariable int bookingId) { return BookingDto.of(service.booking(bookingId)); } + @GetMapping("/offers/{offerId}") + public OfferDto offer(@PathVariable int offerId) { + return OfferDto.of(service.offer(offerId)); + } + + /** MBA-3829: the waitlisted candidate takes the held seat (booking becomes BOOKED, waitlist shifts up). */ + @PostMapping("/offers/{offerId}/accept") + public OfferResultDto acceptOffer(@PathVariable int offerId) { + return offerResult(offerId, service.acceptOffer(offerId)); + } + + /** MBA-3829: the candidate turns the seat down (booking CANCELLED); the seat is offered to the next entry. */ + @PostMapping("/offers/{offerId}/decline") + public OfferResultDto declineOffer(@PathVariable int offerId) { + return offerResult(offerId, service.declineOffer(offerId)); + } + + private OfferResultDto offerResult(int offerId, com.northwind.scheduling.persistence.Rows.Booking b) { + return new OfferResultDto(OfferDto.of(service.offer(offerId)), BookingDto.of(b), + SessionDto.of(service.session(b.sessionId()))); + } + @DeleteMapping("/bookings/{bookingId}") public BookingDto cancel(@PathVariable int bookingId, @RequestParam(required = false) String reason) { return BookingDto.of(service.cancel(bookingId, reason == null || reason.isBlank() ? "Cancelled by candidate" : reason)); diff --git a/services/scheduling-service/src/main/resources/application.yml b/services/scheduling-service/src/main/resources/application.yml index cee608c5..4a1ff999 100644 --- a/services/scheduling-service/src/main/resources/application.yml +++ b/services/scheduling-service/src/main/resources/application.yml @@ -85,6 +85,12 @@ scheduling: password: ${SCHEDULING_RELAY_DB_PASSWORD:Sch3dRelay!Dev2026} poll-ms: ${SCHEDULING_RELAY_POLL_MS:250} batch-size: ${SCHEDULING_RELAY_BATCH_SIZE:200} + # MBA-3829 waitlist auto-offer (ADR 0004): a freed seat is held for the next eligible waitlisted candidate for + # offer-ttl (ISO-8601 duration); the expiry job checks every expiry-poll and moves expired offers on. + waitlist: + offer-ttl: ${SCHEDULING_WAITLIST_OFFER_TTL:PT24H} + expiry-enabled: ${SCHEDULING_WAITLIST_EXPIRY_ENABLED:true} + expiry-poll: ${SCHEDULING_WAITLIST_EXPIRY_POLL:PT1M} # GET /internal/reconciliation and the `reconcile` CLI write reports/reconciliation-.md reconciliation: report-dir: ${SCHEDULING_RECONCILIATION_REPORT_DIR:reports} diff --git a/services/scheduling-service/src/main/resources/db/migration/V3__waitlist_offers.sql b/services/scheduling-service/src/main/resources/db/migration/V3__waitlist_offers.sql new file mode 100644 index 00000000..e578f96d --- /dev/null +++ b/services/scheduling-service/src/main/resources/db/migration/V3__waitlist_offers.sql @@ -0,0 +1,29 @@ +-- MBA-3829 waitlist auto-offer (ADR 0004). A freed seat in an OPEN session is offered to the lowest-position waitlist +-- entry whose accommodation needs fit (service/WaitlistOfferPolicy). While an offer is PENDING the seat is held: +-- SessionCapacity subtracts held seats from availability, so nobody else can book it. +-- The hold lives only here. Legacy dbo.ExamSession.SeatsAvailable keeps Capacity - (BOOKED + ATTENDED) (seat-drift.sql, +-- ADR 0003), the offered booking stays WAITLISTED in legacy until the relay projects SeatOfferAccepted as BOOKED. +CREATE TABLE seat_offer ( + offer_id INT IDENTITY(1,1) NOT NULL CONSTRAINT pk_seat_offer PRIMARY KEY, + session_id INT NOT NULL CONSTRAINT fk_seat_offer_session REFERENCES exam_session(session_id), + booking_id INT NOT NULL CONSTRAINT fk_seat_offer_booking REFERENCES booking(booking_id), + candidate_id INT NOT NULL CONSTRAINT fk_seat_offer_candidate REFERENCES candidate_snapshot(candidate_id), + position INT NOT NULL, + status VARCHAR(10) NOT NULL CONSTRAINT ck_seat_offer_status CHECK (status IN + ('PENDING', 'ACCEPTED', 'DECLINED', 'EXPIRED', 'WITHDRAWN')), + offered_at DATETIME2(0) NOT NULL, + expires_at DATETIME2(0) NOT NULL, + resolved_at DATETIME2(0) NULL, + resolution NVARCHAR(200) NULL +); +GO +-- at most one live offer per waitlisted booking (no double offers, even under concurrent triggers) +CREATE UNIQUE INDEX uq_seat_offer_pending_booking ON seat_offer (booking_id) WHERE status = 'PENDING'; +CREATE INDEX ix_seat_offer_session_status ON seat_offer (session_id, status); +CREATE INDEX ix_seat_offer_pending_expiry ON seat_offer (expires_at) WHERE status = 'PENDING'; + +ALTER TABLE outbox_event DROP CONSTRAINT ck_outbox_event_type; +ALTER TABLE outbox_event ADD CONSTRAINT ck_outbox_event_type CHECK (event_type IN ( + 'BookingCreated', 'BookingCancelled', 'BookingRescheduled', 'BookingWaitlisted', + 'AttendanceRecorded', 'CapacityChanged', 'InventoryBaselined', + 'SeatOffered', 'SeatOfferAccepted', 'SeatOfferDeclined', 'SeatOfferExpired', 'SeatOfferWithdrawn')); diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/domain/WaitlistOfferRulesTest.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/domain/WaitlistOfferRulesTest.java new file mode 100644 index 00000000..1cc1967f --- /dev/null +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/domain/WaitlistOfferRulesTest.java @@ -0,0 +1,76 @@ +package com.northwind.scheduling.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +/** MBA-3829 / ADR 0004: who gets a freed seat. */ +class WaitlistOfferRulesTest { + + static final List THREE = List.of(new WaitlistSlot(13, 1, null), new WaitlistSlot(14, 2, null), + new WaitlistSlot(15, 3, "SR")); + + @Test + void oneFreedSeatGoesToPositionOne() { + assertThat(WaitlistOfferRules.select(SessionStatus.OPEN, new SessionCapacity(3, 1, 2, 1, 3), THREE)) + .extracting(WaitlistSlot::bookingId).containsExactly(13); + } + + @Test + void twoFreedSeatsAreOfferedInPositionOrderEvenWhenTheListIsUnsorted() { + List unsorted = List.of(THREE.get(2), THREE.get(1), THREE.get(0)); + assertThat(WaitlistOfferRules.select(SessionStatus.OPEN, new SessionCapacity(5, 1, 3, 0, 3), unsorted)) + .extracting(WaitlistSlot::bookingId).containsExactly(13, 14); + } + + @Test + void heldSeatsAreNotOfferedAgain() { + // capacity 3, 2 occupied, 1 held by a pending offer -> nothing free + assertThat(WaitlistOfferRules.select(SessionStatus.OPEN, new SessionCapacity(3, 1, 2, 0, 3, 1, 0), THREE)).isEmpty(); + } + + @Test + void extraTimeEntryIsSkippedWhileNoAccommodationSeatIsFree() { + List etFirst = List.of(new WaitlistSlot(20, 1, "ET25"), new WaitlistSlot(21, 2, "ET50"), + new WaitlistSlot(22, 3, null)); + // accommodation seat used by a BOOKED ET25 candidate + assertThat(WaitlistOfferRules.select(SessionStatus.OPEN, new SessionCapacity(3, 1, 2, 1, 3), etFirst)) + .extracting(WaitlistSlot::bookingId).containsExactly(22); + // accommodation seat held by a pending ET offer + assertThat(WaitlistOfferRules.select(SessionStatus.OPEN, new SessionCapacity(4, 1, 2, 0, 3, 1, 1), etFirst)) + .extracting(WaitlistSlot::bookingId).containsExactly(22); + } + + @Test + void onlyOneExtraTimeEntryPerFreeAccommodationSeat() { + List etFirst = List.of(new WaitlistSlot(20, 1, "ET25"), new WaitlistSlot(21, 2, "ET50"), + new WaitlistSlot(22, 3, "RB")); + assertThat(WaitlistOfferRules.select(SessionStatus.OPEN, new SessionCapacity(5, 1, 2, 0, 3), etFirst)) + .extracting(WaitlistSlot::bookingId).containsExactly(20, 22); + } + + @Test + void nobodyEligibleLeavesTheSeatFree() { + assertThat(WaitlistOfferRules.select(SessionStatus.OPEN, new SessionCapacity(3, 1, 2, 1, 1), + List.of(new WaitlistSlot(20, 1, "ET25")))).isEmpty(); + assertThat(WaitlistOfferRules.select(SessionStatus.OPEN, new SessionCapacity(3, 1, 2, 0, 0), List.of())).isEmpty(); + } + + @Test + void onlyOpenSessionsMakeOffers() { + for (SessionStatus s : List.of(SessionStatus.CLOSED, SessionStatus.DELIVERED, SessionStatus.CANCELLED)) { + assertThat(WaitlistOfferRules.select(s, new SessionCapacity(3, 1, 0, 0, 3), THREE)).isEmpty(); + } + } + + @Test + void heldSeatsReduceAvailabilityForNewBookings() { + SessionCapacity held = new SessionCapacity(3, 1, 2, 0, 2, 1, 1); + assertThat(held.seatsAvailable()).isZero(); + assertThat(held.isFull()).isTrue(); + assertThat(held.accommodationAvailable()).isZero(); + assertThat(held.hasSeatFor("ET25")).isFalse(); + } +} diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/relay/RelayIT.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/relay/RelayIT.java index bd9a601e..1669d041 100644 --- a/services/scheduling-service/src/test/java/com/northwind/scheduling/relay/RelayIT.java +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/relay/RelayIT.java @@ -129,6 +129,61 @@ void crashAfterLegacyCommitBeforeMarkRelayedReprocessesWithoutDuplicates() throw assertZeroDrift(); } + @Test + @Order(5) + void waitlistOfferCycleReachesLegacyAndReconcilesToZero() throws SQLException { + // MBA-3829: a full OPEN session with three waitlisted candidates; offer -> accept, decline, expire + Integer session = scheduling.queryForObject(""" + SELECT TOP 1 s.session_id FROM exam_session s + WHERE s.status = 'OPEN' AND s.starts_at > '2026-11-15' + AND NOT EXISTS (SELECT 1 FROM booking w WHERE w.session_id = s.session_id AND w.status = 'WAITLISTED') + AND (SELECT COUNT(*) FROM booking b WHERE b.session_id = s.session_id AND b.status = 'BOOKED' + AND b.accommodation_code IS NULL) >= 3 + AND (SELECT COUNT(*) FROM booking b WHERE b.session_id = s.session_id AND b.status IN ('BOOKED','ATTENDED')) + >= CASE WHEN s.accommodation_capacity > 2 THEN s.accommodation_capacity ELSE 2 END + ORDER BY s.session_id""", Integer.class); + int occupied = scheduling.queryForObject("SELECT COUNT(*) FROM booking WHERE session_id = ? AND status IN ('BOOKED','ATTENDED')", + Integer.class, session); + service.changeCapacity(session, occupied, "full for offer test"); + List waitlisted = List.of("NW00000911", "NW00000912", "NW00000913").stream() + .map(c -> service.book(new SchedulingService.BookCommand(session, c, null, null, "PORTAL")).bookingId()).toList(); + assertRelayed(); + List booked = scheduling.queryForList("SELECT booking_id FROM booking WHERE session_id = ? AND status = 'BOOKED' " + + "AND accommodation_code IS NULL ORDER BY booking_id", Integer.class, session); + + service.cancel(booked.get(0), "offer test"); + int offer = scheduling.queryForObject("SELECT offer_id FROM seat_offer WHERE booking_id = ? AND status = 'PENDING'", + Integer.class, waitlisted.get(0)); + assertRelayed(); + assertThat(legacyBooking(waitlisted.get(0))).containsEntry("Status", "WAITLISTED"); + + service.acceptOffer(offer); + assertRelayed(); + assertThat(legacyBooking(waitlisted.get(0))).containsEntry("Status", "BOOKED"); + assertThat(legacyInt("SELECT COUNT(*) FROM dbo.Waitlist WHERE BookingId = " + waitlisted.get(0))).isZero(); + assertThat(legacyInt("SELECT Position FROM dbo.Waitlist WHERE BookingId = " + waitlisted.get(1))).isEqualTo(1); + assertThat(legacyInt("SELECT Position FROM dbo.Waitlist WHERE BookingId = " + waitlisted.get(2))).isEqualTo(2); + + service.cancel(booked.get(1), "offer test"); + service.declineOffer(scheduling.queryForObject("SELECT offer_id FROM seat_offer WHERE booking_id = ? AND status = 'PENDING'", + Integer.class, waitlisted.get(1))); + assertRelayed(); + assertThat(legacyBooking(waitlisted.get(1))).containsEntry("Status", "CANCELLED"); + assertThat(legacyInt("SELECT Position FROM dbo.Waitlist WHERE BookingId = " + waitlisted.get(2))).isEqualTo(1); + + scheduling.update("UPDATE seat_offer SET expires_at = DATEADD(MINUTE, -1, SYSDATETIME()) WHERE status = 'PENDING'"); + for (int id : service.dueOfferIds()) { + service.expireOffer(id); + } + assertRelayed(); + assertThat(legacyBooking(waitlisted.get(2))).containsEntry("Status", "CANCELLED"); + assertThat(legacyInt("SELECT COUNT(*) FROM dbo.Waitlist w JOIN dbo.Booking b ON b.BookingId = w.BookingId " + + "WHERE b.SessionId = " + session)).isZero(); + assertThat(legacyInt("SELECT SeatsAvailable FROM dbo.ExamSession WHERE SessionId = " + session)).isEqualTo(1); + assertThat(scheduling.queryForList("SELECT DISTINCT event_type FROM outbox_event", String.class)) + .contains("SeatOffered", "SeatOfferAccepted", "SeatOfferDeclined", "SeatOfferExpired"); + } + private List allEvents() { scheduling.update("UPDATE outbox_event SET relayed_at = NULL"); try { diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/service/WaitlistOfferIT.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/service/WaitlistOfferIT.java new file mode 100644 index 00000000..966ac88c --- /dev/null +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/service/WaitlistOfferIT.java @@ -0,0 +1,324 @@ +package com.northwind.scheduling.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.annotation.Import; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.jdbc.core.JdbcTemplate; + +import com.northwind.scheduling.SqlServerTestBase; +import com.northwind.scheduling.domain.BookingStatus; +import com.northwind.scheduling.domain.ErrorCode; +import com.northwind.scheduling.domain.SchedulingException; +import com.northwind.scheduling.importer.SnapshotImporter; +import com.northwind.scheduling.persistence.Rows; + +/** + * MBA-3829 waitlist auto-offer on Testcontainers SQL Server. Fixture session 163: capacity 3 (1 accommodation seat), + * BOOKED 10 (ET25), 11, 12; WAITLISTED 13 at position 1. Each test adds NW00000914/915 at positions 2/3. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Import(SqlServerTestBase.FixtureLegacy.class) +class WaitlistOfferIT extends SqlServerTestBase { + + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() { + }; + + @Autowired SchedulingService service; + @Autowired WaitlistOfferPolicy policy; + @Autowired SnapshotImporter importer; + @Autowired JdbcTemplate jdbc; + @Autowired TestRestTemplate http; + + int w14; + int w15; + + @BeforeEach + void reset() { + importer.run(SnapshotImporter.Mode.RESET); + jdbc.update("DELETE FROM outbox_event"); + w14 = waitlist(163, "NW00000914"); + w15 = waitlist(163, "NW00000915"); + } + + int waitlist(int session, String cand) { + var o = service.book(new SchedulingService.BookCommand(session, cand, null, null, "PORTAL")); + assertThat(o.status()).isEqualTo(BookingStatus.WAITLISTED); + return o.bookingId(); + } + + List> offers(int session) { + return jdbc.queryForList("SELECT offer_id, booking_id, position, status, offered_at, expires_at FROM seat_offer " + + "WHERE session_id = ? ORDER BY offer_id", session); + } + + List pendingBookings(int session) { + return jdbc.queryForList("SELECT booking_id FROM seat_offer WHERE session_id = ? AND status = 'PENDING' " + + "ORDER BY position", Integer.class, session); + } + + int pendingOfferId(int bookingId) { + return jdbc.queryForObject("SELECT offer_id FROM seat_offer WHERE booking_id = ? AND status = 'PENDING'", + Integer.class, bookingId); + } + + List waitlistOrder(int session) { + return service.waitlist(session).stream().map(Rows.WaitlistEntry::bookingId).toList(); + } + + List waitlistPositions(int session) { + return service.waitlist(session).stream().map(Rows.WaitlistEntry::position).toList(); + } + + List events() { + return jdbc.queryForList("SELECT event_type + ':' + CONVERT(VARCHAR(12), aggregate_id) FROM outbox_event " + + "ORDER BY event_seq", String.class); + } + + ResponseEntity> post(String url) { + return http.exchange(url, HttpMethod.POST, null, MAP); + } + + @Test + void cancelOffersTheSeatToPositionOneAndHoldsIt() { + LocalDateTime before = LocalDateTime.now().withNano(0); + service.cancel(11, "test"); + + assertThat(pendingBookings(163)).containsExactly(13); + Map offer = offers(163).get(0); + assertThat(offer).containsEntry("position", 1).containsEntry("status", "PENDING"); + LocalDateTime expires = ((java.sql.Timestamp) offer.get("expires_at")).toLocalDateTime(); + assertThat(Duration.between(before, expires)).isBetween(Duration.ofHours(24).minusMinutes(1), + Duration.ofHours(24).plusMinutes(1)); + + Rows.Session s = service.session(163); + assertThat(s.seats().seatsAvailable()).isZero(); + assertThat(s.held()).isEqualTo(1); + // the held seat is not bookable by others + assertThat(service.book(new SchedulingService.BookCommand(163, "NW00000916", null, null, "PORTAL")).status()) + .isEqualTo(BookingStatus.WAITLISTED); + assertThat(events()).containsSubsequence("BookingCancelled:11", "SeatOffered:13"); + + Map booking = http.exchange("/api/v2/bookings/13", HttpMethod.GET, null, MAP).getBody(); + assertThat(booking).containsEntry("status", "WAITLISTED").containsEntry("offerStatus", "PENDING") + .containsEntry("offerId", offer.get("offer_id")); + Map session = http.exchange("/api/v2/sessions/163", HttpMethod.GET, null, MAP).getBody(); + assertThat(session).containsEntry("seatsAvailable", 0).containsEntry("heldSeats", 1); + List> wl = http.exchange("/api/v2/sessions/163/waitlist", HttpMethod.GET, null, + new ParameterizedTypeReference>>() { + }).getBody(); + assertThat(wl.get(0)).containsEntry("bookingId", 13).containsEntry("offerStatus", "PENDING"); + assertThat(wl.get(1)).containsEntry("bookingId", w14).containsEntry("offerStatus", null); + } + + @Test + void acceptBooksTheCandidateAndShiftsTheWaitlist() { + service.cancel(11, "test"); + int offerId = pendingOfferId(13); + + ResponseEntity> r = post("/api/v2/offers/" + offerId + "/accept"); + assertThat(r.getStatusCode()).isEqualTo(HttpStatus.OK); + @SuppressWarnings("unchecked") + Map booking = (Map) r.getBody().get("booking"); + @SuppressWarnings("unchecked") + Map offer = (Map) r.getBody().get("offer"); + assertThat(booking).containsEntry("status", "BOOKED").containsEntry("waitlistPosition", null) + .containsEntry("offerStatus", "ACCEPTED"); + assertThat(offer).containsEntry("status", "ACCEPTED"); + + assertThat(waitlistOrder(163)).containsExactly(w14, w15); + assertThat(waitlistPositions(163)).containsExactly(1, 2); + Rows.Session s = service.session(163); + assertThat(s.occupied()).isEqualTo(3); + assertThat(s.held()).isZero(); + assertThat(pendingBookings(163)).isEmpty(); + assertThat(events()).last().isEqualTo("SeatOfferAccepted:13"); + String payload = jdbc.queryForObject("SELECT TOP 1 payload FROM outbox_event WHERE event_type = 'SeatOfferAccepted'", + String.class); + assertThat(payload).contains("\"bookingId\":13").contains("\"bookingId\":" + w14).contains("\"bookingId\":" + w15); + + ResponseEntity> again = post("/api/v2/offers/" + offerId + "/accept"); + assertThat(again.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(again.getBody()).containsEntry("error", "OFFER_NOT_PENDING"); + assertThat(post("/api/v2/offers/99999/accept").getBody()).containsEntry("error", "OFFER_NOT_FOUND"); + assertThat(http.exchange("/api/v2/offers/" + offerId, HttpMethod.GET, null, MAP).getBody()) + .containsEntry("status", "ACCEPTED").containsEntry("bookingId", 13); + } + + @Test + void declineMovesTheOfferToTheNextCandidate() { + service.cancel(11, "test"); + int offerId = pendingOfferId(13); + + ResponseEntity> r = post("/api/v2/offers/" + offerId + "/decline"); + assertThat(r.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(service.booking(13).status()).isEqualTo(BookingStatus.CANCELLED); + assertThat(service.booking(13).cancelReason()).isEqualTo("Waitlist offer declined"); + assertThat(waitlistOrder(163)).containsExactly(w14, w15); + assertThat(waitlistPositions(163)).containsExactly(1, 2); + assertThat(pendingBookings(163)).containsExactly(w14); + assertThat(service.session(163).seats().seatsAvailable()).isZero(); + assertThat(events()).containsSubsequence("SeatOfferDeclined:13", "SeatOffered:" + w14); + } + + @Test + void expiryMovesOnAndTheLastExpiryReleasesTheSeat() { + service.cancel(11, "test"); + service.cancel(w15, "leaves"); + jdbc.update("UPDATE seat_offer SET expires_at = DATEADD(MINUTE, -1, SYSDATETIME()) WHERE status = 'PENDING'"); + int first = pendingOfferId(13); + assertThat(post("/api/v2/offers/" + first + "/accept").getBody()).containsEntry("error", "OFFER_NOT_PENDING"); + + assertThat(service.dueOfferIds()).containsExactly(first); + assertThat(service.expireOffer(first)).isTrue(); + assertThat(service.expireOffer(first)).isFalse(); + assertThat(service.booking(13).status()).isEqualTo(BookingStatus.CANCELLED); + assertThat(pendingBookings(163)).containsExactly(w14); + assertThat(service.waitlist(163)).extracting(Rows.WaitlistEntry::position).containsExactly(1); + assertThat(events()).containsSubsequence("SeatOfferExpired:13", "SeatOffered:" + w14); + + jdbc.update("UPDATE seat_offer SET expires_at = DATEADD(MINUTE, -1, SYSDATETIME()) WHERE status = 'PENDING'"); + for (int id : service.dueOfferIds()) { + service.expireOffer(id); + } + assertThat(pendingBookings(163)).isEmpty(); + assertThat(service.waitlist(163)).isEmpty(); + Rows.Session s = service.session(163); + assertThat(s.held()).isZero(); + assertThat(s.seats().seatsAvailable()).isEqualTo(1); + assertThat(service.book(new SchedulingService.BookCommand(163, "NW00000916", null, null, "PORTAL")).status()) + .isEqualTo(BookingStatus.BOOKED); + } + + @Test + void extraTimeCandidateIsSkippedAndKeepsPlaceWhileNoAccommodationSeatIsFree() { + // session 300: capacity 3, 1 accommodation seat; 3 standard bookings, then ET25, ET50, standard waitlisted + service.changeCapacity(300, 3, "test"); + for (String c : List.of("NW00000921", "NW00000922", "NW00000923")) { + service.book(new SchedulingService.BookCommand(300, c, null, null, "PORTAL")); + } + int et25 = service.book(new SchedulingService.BookCommand(300, "NW00000940", "ET25", null, "PORTAL")).bookingId(); + int et50 = service.book(new SchedulingService.BookCommand(300, "NW00000926", "ET50", null, "PORTAL")).bookingId(); + int std = waitlist(300, "NW00000925"); + assertThat(service.booking(et25).accommodationCode()).isEqualTo("ET25"); + List booked = jdbc.queryForList("SELECT booking_id FROM booking WHERE session_id = 300 AND status = 'BOOKED' " + + "ORDER BY booking_id", Integer.class); + + service.cancel(booked.get(0), "test"); // ET25 at position 1 takes the seat and the accommodation seat + assertThat(pendingBookings(300)).containsExactly(et25); + service.cancel(booked.get(1), "test"); // no accommodation seat free: ET50 skipped, standard entry offered + assertThat(pendingBookings(300)).containsExactly(et25, std); + assertThat(waitlistOrder(300)).containsExactly(et25, et50, std); + assertThat(waitlistPositions(300)).containsExactly(1, 2, 3); + } + + @Test + void capacityIncreaseOffersInPositionOrderAndDecreaseWithdrawsNewestOffers() { + service.changeCapacity(163, 5, "bigger room"); + assertThat(pendingBookings(163)).containsExactly(13, w14); + assertThat(service.session(163).seats().seatsAvailable()).isZero(); + + service.changeCapacity(163, 4, "smaller again"); + assertThat(pendingBookings(163)).containsExactly(13); + assertThat(waitlistOrder(163)).containsExactly(13, w14, w15); + assertThat(events()).contains("SeatOfferWithdrawn:" + w14); + + service.changeCapacity(163, 3, "original"); + assertThat(pendingBookings(163)).isEmpty(); + assertThat(service.session(163).held()).isZero(); + assertThat(waitlistPositions(163)).containsExactly(1, 2, 3); + } + + @Test + void rescheduleOutOffersTheSeatAndCancellingAnOfferedBookingPassesItOn() { + service.reschedule(11, 154); + assertThat(pendingBookings(163)).containsExactly(13); + List ev = events(); + assertThat(ev).contains("SeatOffered:13"); + assertThat(ev.stream().filter(e -> e.startsWith("BookingRescheduled:")).findFirst()) + .hasValueSatisfying(r -> assertThat(ev.indexOf(r)).isLessThan(ev.indexOf("SeatOffered:13"))); + + service.cancel(13, "changed my mind"); + assertThat(jdbc.queryForObject("SELECT status FROM seat_offer WHERE booking_id = 13", String.class)) + .isEqualTo("WITHDRAWN"); + assertThat(pendingBookings(163)).containsExactly(w14); + assertThat(service.session(163).seats().seatsAvailable()).isZero(); + } + + @Test + void closedSessionsMakeNoOffers() { + jdbc.update("UPDATE exam_session SET status = 'CLOSED' WHERE session_id = 163"); + assertThat(policy.offerFreedSeats(163, "test")).isEmpty(); + } + + @Test + void offerErrorsUseTheOfferVocabulary() { + assertThatThrownBy(() -> service.acceptOffer(424242)).isInstanceOf(SchedulingException.class) + .extracting(e -> ((SchedulingException) e).code()).isEqualTo(ErrorCode.OFFER_NOT_FOUND); + ResponseEntity> r = post("/api/v2/offers/424242/decline"); + assertThat(r.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(r.getBody()).containsEntry("error", "OFFER_NOT_FOUND").containsEntry("legacyCode", null); + } + + @RepeatedTest(3) + void twoSeatsFreedConcurrentlyGiveTwoOffersInPositionOrderAndNoDoubleOffer() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(3); + try { + CountDownLatch go = new CountDownLatch(1); + List> jobs = List.of( + () -> { go.await(); return service.cancel(11, "c1"); }, + () -> { go.await(); return service.cancel(12, "c2"); }, + () -> { go.await(); return policy.ttl(); }); + List> futures = jobs.stream().map(pool::submit).toList(); + go.countDown(); + for (Future f : futures) { + f.get(); + } + } finally { + pool.shutdown(); + } + assertThat(pendingBookings(163)).containsExactly(13, w14); + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM seat_offer", Integer.class)).isEqualTo(2); + Rows.Session s = service.session(163); + assertThat(s.held()).isEqualTo(2); + assertThat(s.seats().seatsAvailable()).isZero(); + } + + @RepeatedTest(3) + void concurrentCancelAndCapacityIncreaseNeverOfferOneBookingTwice() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + CountDownLatch go = new CountDownLatch(1); + Future a = pool.submit(() -> { go.await(); return service.cancel(11, "c1"); }); + Future b = pool.submit(() -> { go.await(); return service.changeCapacity(163, 4, "up"); }); + go.countDown(); + a.get(); + b.get(); + } finally { + pool.shutdown(); + } + assertThat(pendingBookings(163)).containsExactly(13, w14); + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM seat_offer", Integer.class)).isEqualTo(2); + assertThat(service.session(163).seats().seatsAvailable()).isZero(); + } +} diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/web/SchedulingApiIT.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/web/SchedulingApiIT.java index 802c28a1..45f64cf6 100644 --- a/services/scheduling-service/src/test/java/com/northwind/scheduling/web/SchedulingApiIT.java +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/web/SchedulingApiIT.java @@ -72,7 +72,7 @@ HttpResponse attendance(String path, String token) throws Exception { @Test void flywayCreatesSchedulingDbAndImporterLoadsSnapshots() { assertThat(jdbc.queryForObject("SELECT DB_NAME()", String.class)).isEqualTo("Scheduling"); - assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM flyway_schema_history WHERE success = 1", Integer.class)).isEqualTo(2); + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM flyway_schema_history WHERE success = 1", Integer.class)).isEqualTo(3); List> centers = http.exchange("/api/v2/centers", HttpMethod.GET, null, LIST).getBody(); assertThat(centers).extracting(c -> c.get("centerCode")).containsExactly("AMS01", "SFO01"); List> sessions = http.exchange("/api/v2/centers/SFO01/sessions?examCode=MHL-RN1&from=2026-11-12&to=2026-11-20", @@ -154,8 +154,10 @@ void capacityDecreaseBelowActiveBookingsDemotesNewestToWaitlist() { Map raised = http.exchange("/api/v2/sessions/154/capacity", HttpMethod.PUT, new HttpEntity<>(Map.of("capacity", 12)), MAP).getBody(); - assertThat(((Map) raised.get("session")).get("seatsAvailable")).isEqualTo(6); - assertThat(get("/api/v2/sessions/154")).containsEntry("waitlistCount", 3); // no auto-promotion (ODD-09) + // MBA-3829 / ADR 0004: 6 seats free up, 3 are held by offers to the waitlisted 7, 8, 9 (legacy ODD-09 promoted nobody) + assertThat(((Map) raised.get("session")).get("seatsAvailable")).isEqualTo(3); + assertThat(get("/api/v2/sessions/154")).containsEntry("waitlistCount", 3).containsEntry("heldSeats", 3); + assertThat(get("/api/v2/bookings/7")).containsEntry("status", "WAITLISTED").containsEntry("offerStatus", "PENDING"); ResponseEntity> neg = http.exchange("/api/v2/sessions/154/capacity", HttpMethod.PUT, new HttpEntity<>(Map.of("capacity", -1)), MAP); diff --git a/services/scheduling-service/src/test/resources/application.properties b/services/scheduling-service/src/test/resources/application.properties index 8872a87e..44d7b46c 100644 --- a/services/scheduling-service/src/test/resources/application.properties +++ b/services/scheduling-service/src/test/resources/application.properties @@ -2,3 +2,4 @@ # localhost:1433); RelayIT turns it on explicitly against its own isolated database. scheduling.relay.enabled=false scheduling.attendance.service-token=test-attendance-token +scheduling.waitlist.expiry-enabled=false From 85fa65cb46b988f070d68f5fadaabeb123e62f76 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:28:30 +0000 Subject: [PATCH 2/3] [MBA-3829] Gateway write guard covers offer accept/decline (offer -> session -> centre) Co-Authored-By: Mason --- docs/adr/0004-waitlist-auto-offer.md | 5 ++++ services/routing-gateway/README.md | 5 ++-- .../northwind/routing/route/ApiRoutes.java | 8 +++++-- .../com/northwind/routing/route/Lookup.java | 2 +- .../routing/web/ModernApiWriteGuard.java | 3 ++- .../routing/GatewayIntegrationTest.java | 24 +++++++++++++++++-- .../northwind/routing/RouteDeciderTest.java | 5 ++++ .../scheduling/web/InternalController.java | 10 +++++--- .../scheduling/service/WaitlistOfferIT.java | 5 ++++ 9 files changed, 56 insertions(+), 11 deletions(-) diff --git a/docs/adr/0004-waitlist-auto-offer.md b/docs/adr/0004-waitlist-auto-offer.md index 5ecf8a2a..4f5dbd1e 100644 --- a/docs/adr/0004-waitlist-auto-offer.md +++ b/docs/adr/0004-waitlist-auto-offer.md @@ -52,5 +52,10 @@ every legacy reader. and the session page counts held seats. * Authorisation is the same as for the other `/api/v2` candidate writes (cancel, reschedule): none beyond the gateway. Candidate authentication is out of scope for the scheduling slice. +* Anyone holding an offer id can accept or decline it; this is by design for now, consistent with cancel/reschedule, + because the slice has no candidate login (MR-16 in `docs/as-is/migration-risks.md`). +* The routing gateway's modern write guard covers `POST /api/v2/offers/{id}/accept|decline`: it resolves offer -> + session -> centre (`/api/v2/internal/routing/resolve?offerId=`) and refuses with `403 CENTER_NOT_MODERN` when that + centre is not on `routing.modern-centers` or cannot be resolved (fail closed). * Rolling back a centre to legacy (runbook section 5) leaves pending offers in Scheduling only; the legacy waitlist is intact, so staff promote by hand as before. diff --git a/services/routing-gateway/README.md b/services/routing-gateway/README.md index c5c97a23..0a58f14a 100644 --- a/services/routing-gateway/README.md +++ b/services/routing-gateway/README.md @@ -68,7 +68,7 @@ Requests without a centre key (e.g. `/Booking/MyBookings?candidateNumber=`, `/ap `centerCode`) stay on legacy. Portal pages without a modern equivalent (`/Admin/Centers`, `/Eligibility`, `/Results`, roster CSV, capacity audit) always stay on legacy. -The centre is resolved through scheduling-service `GET /api/v2/internal/routing/resolve?centerCode=|centerId=|sessionId=|bookingId=` +The centre is resolved through scheduling-service `GET /api/v2/internal/routing/resolve?centerCode=|centerId=|sessionId=|bookingId=|offerId=` (reads its snapshots; cached for `routing.resolve-cache-ttl`, 30 s). If the lookup fails the request goes to legacy (writes through the v2 guard below are refused instead). `/api/v2/internal/**` (resolver, snapshot import/reset) is never proxied: the gateway answers `404` for it. With an **empty allow-list no lookups are made and no request bodies are read**: the gateway is a @@ -81,7 +81,8 @@ allow-list says, so rolling a centre back never orphans an in-flight modern book rule above. **Modern write guard.** v2 writes that reach scheduling-service through :8000 (`POST /api/v2/bookings`, -`DELETE /api/v2/bookings/{id}`, `POST /api/v2/bookings/{id}/reschedule`, `PUT /api/v2/sessions/{id}/capacity`) +`DELETE /api/v2/bookings/{id}`, `POST /api/v2/bookings/{id}/reschedule`, `PUT /api/v2/sessions/{id}/capacity`, +`POST /api/v2/offers/{id}/accept|decline` resolved offer -> session -> centre via `resolve?offerId=`) are refused with `403 {"error":"CENTER_NOT_MODERN"}` when the centre is not allow-listed (modern-owned bookings excepted), so the modern UI cannot take seats legacy still owns. The guard fails closed: if a centre cannot be resolved (lookup outage, unknown id) the write is refused with the same 403. A reschedule must also land on an diff --git a/services/routing-gateway/src/main/java/com/northwind/routing/route/ApiRoutes.java b/services/routing-gateway/src/main/java/com/northwind/routing/route/ApiRoutes.java index 8d3f766b..3f1a31ca 100644 --- a/services/routing-gateway/src/main/java/com/northwind/routing/route/ApiRoutes.java +++ b/services/routing-gateway/src/main/java/com/northwind/routing/route/ApiRoutes.java @@ -12,13 +12,13 @@ public final class ApiRoutes { public enum V1Op { SESSIONS, SESSION, BOOK, GET_BOOKING, CANCEL, RESCHEDULE } - public enum V2Op { BOOK, CANCEL, RESCHEDULE, CAPACITY } + public enum V2Op { BOOK, CANCEL, RESCHEDULE, CAPACITY, OFFER } /** {@code needsBody}: the centre key is {@code sessionId} in the JSON body (POST /api/v1/bookings). */ public record V1(V1Op op, Lookup lookup, String id, boolean needsBody) { } - /** {@code id} is the booking or session id from the path, if any. */ + /** {@code id} is the booking, session or offer id from the path, if any. */ public record V2Write(V2Op op, String id) { } @@ -79,6 +79,10 @@ public static Optional matchV2Write(String method, String rawPath) { return Optional.of(new V2Write(V2Op.RESCHEDULE, s[1])); } } + if (s[0].equals("offers") && s.length == 3 && m.equals("POST") && (s[2].equals("accept") || s[2].equals("decline")) + && PortalRoutes.isId(s[1])) { + return Optional.of(new V2Write(V2Op.OFFER, s[1])); + } if (s[0].equals("sessions") && s.length == 3 && s[2].equals("capacity") && m.equals("PUT") && PortalRoutes.isId(s[1])) { return Optional.of(new V2Write(V2Op.CAPACITY, s[1])); } diff --git a/services/routing-gateway/src/main/java/com/northwind/routing/route/Lookup.java b/services/routing-gateway/src/main/java/com/northwind/routing/route/Lookup.java index d94b6c8a..d865229e 100644 --- a/services/routing-gateway/src/main/java/com/northwind/routing/route/Lookup.java +++ b/services/routing-gateway/src/main/java/com/northwind/routing/route/Lookup.java @@ -4,7 +4,7 @@ public record Lookup(Kind kind, String value) { public enum Kind { - CENTER_CODE("centerCode"), CENTER_ID("centerId"), SESSION_ID("sessionId"), BOOKING_ID("bookingId"); + CENTER_CODE("centerCode"), CENTER_ID("centerId"), SESSION_ID("sessionId"), BOOKING_ID("bookingId"), OFFER_ID("offerId"); private final String param; diff --git a/services/routing-gateway/src/main/java/com/northwind/routing/web/ModernApiWriteGuard.java b/services/routing-gateway/src/main/java/com/northwind/routing/web/ModernApiWriteGuard.java index 9a27d86c..198f6bf1 100644 --- a/services/routing-gateway/src/main/java/com/northwind/routing/web/ModernApiWriteGuard.java +++ b/services/routing-gateway/src/main/java/com/northwind/routing/web/ModernApiWriteGuard.java @@ -14,7 +14,7 @@ /** * Keeps the modern side from writing seat inventory it does not own: a v2 write (book, cancel, reschedule, - * capacity change) that reaches scheduling-service through the gateway is refused with + * capacity change, waitlist offer accept/decline) that reaches scheduling-service through the gateway is refused with * {@code 403 CENTER_NOT_MODERN} when its centre is not allow-listed. Bookings at or above the modern id floor * are always the modern side's own. Keys that cannot be resolved * (lookup outage or unknown id) are refused: the guard fails closed. @@ -41,6 +41,7 @@ public Mono> deniedCenter(ApiRoutes.V2Write write, Map denied(Lookup.of(Kind.SESSION_ID, number(body, "sessionId"))); case CANCEL -> denied(Lookup.of(Kind.BOOKING_ID, write.id())); case CAPACITY -> denied(Lookup.of(Kind.SESSION_ID, write.id())); + case OFFER -> denied(Lookup.of(Kind.OFFER_ID, write.id())); case RESCHEDULE -> deniedReschedule(Lookup.of(Kind.BOOKING_ID, write.id()), Lookup.of(Kind.SESSION_ID, number(body, "newSessionId"))); }; diff --git a/services/routing-gateway/src/test/java/com/northwind/routing/GatewayIntegrationTest.java b/services/routing-gateway/src/test/java/com/northwind/routing/GatewayIntegrationTest.java index b092422d..5e4277a8 100644 --- a/services/routing-gateway/src/test/java/com/northwind/routing/GatewayIntegrationTest.java +++ b/services/routing-gateway/src/test/java/com/northwind/routing/GatewayIntegrationTest.java @@ -55,8 +55,9 @@ static Stub.Answer scheduling(Stub.Call c) { String u = c.uri(); if (u.startsWith("/api/v2/internal/routing/resolve")) { String center = u.contains("sessionId=154") || u.contains("bookingId=5000000") || u.contains("centerId=1&") || u.endsWith("centerId=1") - || u.contains("centerCode=BOS01") ? "BOS01" - : u.contains("sessionId=200") || u.contains("bookingId=1200") || u.contains("centerCode=CHI01") ? "CHI01" + || u.contains("centerCode=BOS01") || u.endsWith("offerId=7") ? "BOS01" + : u.contains("sessionId=200") || u.contains("bookingId=1200") || u.contains("centerCode=CHI01") + || u.endsWith("offerId=8") ? "CHI01" : u.contains("centerCode=SEA01") ? "SEA01" : null; return center == null ? Stub.Answer.json(404, "{\"error\":\"SESSION_NOT_FOUND\"}") : Stub.Answer.json(200, "{\"centerCode\":\"" + center + "\",\"target\":\"legacy\",\"reason\":\"x\"}"); @@ -72,6 +73,9 @@ static Stub.Answer scheduling(Stub.Call c) { return Stub.Answer.json(200, "{\"bookingId\":50000001,\"sessionId\":154,\"candidateNumber\":\"NW00000901\"," + "\"candidateName\":\"A\",\"status\":\"CANCELLED\",\"channel\":\"PARTNER\",\"bookedAt\":\"2026-11-10T08:00:00\"}"); } + if (c.method().equals("POST") && u.startsWith("/api/v2/offers/")) { + return Stub.Answer.json(200, "{\"offer\":{\"offerId\":7,\"status\":\"ACCEPTED\"}}"); + } if (u.startsWith("/api/v2/centers/BOS01/sessions")) { return Stub.Answer.json(200, "[{\"sessionId\":154,\"centerCode\":\"BOS01\",\"startsAt\":\"2026-11-12T09:00:00\",\"waitlistCount\":0}]"); } @@ -208,6 +212,22 @@ void v2WritesOnNonAllowListedCentresAreRefused() { .bodyValue(Map.of("capacity", 5)).exchange().expectStatus().isForbidden(); } + @Test + void offerAcceptAndDeclineAreGuardedByTheOffersCentre() { + web.post().uri("/api/v2/offers/7/accept").exchange() + .expectStatus().isOk().expectHeader().valueEquals("X-Route", "modern") + .expectBody().jsonPath("$.offer.status").isEqualTo("ACCEPTED"); + web.post().uri("/api/v2/offers/8/accept").exchange() + .expectStatus().isForbidden().expectBody().jsonPath("$.error").isEqualTo("CENTER_NOT_MODERN"); + web.post().uri("/api/v2/offers/8/decline").exchange() + .expectStatus().isForbidden().expectBody().jsonPath("$.error").isEqualTo("CENTER_NOT_MODERN"); + web.post().uri("/api/v2/offers/999/decline").exchange() + .expectStatus().isForbidden().expectBody().jsonPath("$.error").isEqualTo("CENTER_NOT_MODERN") + .jsonPath("$.message").value(m -> assertThat((String) m).contains("could not be resolved")); + assertThat(SCHEDULING.calls("POST", "/api/v2/offers/8")).isEmpty(); + assertThat(SCHEDULING.calls("POST", "/api/v2/offers/999")).isEmpty(); + } + @Test void internalSchedulingEndpointsAreNotExposed() { web.post().uri("/api/v2/internal/import/sessions?mode=reset").exchange() diff --git a/services/routing-gateway/src/test/java/com/northwind/routing/RouteDeciderTest.java b/services/routing-gateway/src/test/java/com/northwind/routing/RouteDeciderTest.java index 6a9505ad..d2f71fe2 100644 --- a/services/routing-gateway/src/test/java/com/northwind/routing/RouteDeciderTest.java +++ b/services/routing-gateway/src/test/java/com/northwind/routing/RouteDeciderTest.java @@ -90,5 +90,10 @@ void bookingApiRoutes() { assertThat(ApiRoutes.matchV2Write("POST", "/api/v2/bookings").orElseThrow().op()).isEqualTo(ApiRoutes.V2Op.BOOK); assertThat(ApiRoutes.matchV2Write("PUT", "/api/v2/sessions/154/capacity").orElseThrow().id()).isEqualTo("154"); assertThat(ApiRoutes.matchV2Write("GET", "/api/v2/bookings/9")).isEmpty(); + assertThat(ApiRoutes.matchV2Write("POST", "/api/v2/offers/7/accept").orElseThrow()) + .isEqualTo(new ApiRoutes.V2Write(ApiRoutes.V2Op.OFFER, "7")); + assertThat(ApiRoutes.matchV2Write("POST", "/api/v2/offers/7/decline").orElseThrow().op()).isEqualTo(ApiRoutes.V2Op.OFFER); + assertThat(ApiRoutes.matchV2Write("POST", "/api/v2/Offers/7/Accept/").orElseThrow().id()).isEqualTo("7"); + assertThat(ApiRoutes.matchV2Write("GET", "/api/v2/offers/7")).isEmpty(); } } diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/InternalController.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/InternalController.java index 2551fdaa..eb31114a 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/InternalController.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/InternalController.java @@ -54,14 +54,15 @@ public ImportReport importSessions(@RequestParam(required = false) String mode) /** * Stub for the M3 per-test-center routing gateway: which backend serves a centre. Centres listed in * SCHEDULING_ROUTING_MODERN_CENTERS ("*" = all) resolve to "modern", the rest to the default target. - * The centre can be given directly (code or id) or via a session/booking id; the M3 routing-gateway + * The centre can be given directly (code or id) or via a session/booking/offer id; the M3 routing-gateway * (services/routing-gateway) only uses the resolved centerCode and applies its own allow-list. */ @GetMapping("/routing/resolve") public RoutingDto resolve(@RequestParam(required = false) String centerCode, @RequestParam(required = false) Integer sessionId, @RequestParam(required = false) Integer bookingId, - @RequestParam(required = false) Integer centerId) { + @RequestParam(required = false) Integer centerId, + @RequestParam(required = false) Integer offerId) { String code = centerCode; if ((code == null || code.isBlank()) && centerId != null) { code = service.centers().stream().filter(c -> c.id() == centerId).map(Rows.Center::code).findFirst() @@ -73,8 +74,11 @@ public RoutingDto resolve(@RequestParam(required = false) String centerCode, if ((code == null || code.isBlank()) && bookingId != null) { code = service.booking(bookingId).centerCode(); } + if ((code == null || code.isBlank()) && offerId != null) { + code = service.session(service.offer(offerId).sessionId()).centerCode(); + } if (code == null || code.isBlank()) { - throw new SchedulingException(ErrorCode.VALIDATION, "centerCode, centerId, sessionId or bookingId is required"); + throw new SchedulingException(ErrorCode.VALIDATION, "centerCode, centerId, sessionId, bookingId or offerId is required"); } String c = service.center(code.trim()).code(); if (modernCenters.contains("*") || modernCenters.contains(c.toUpperCase())) { diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/service/WaitlistOfferIT.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/service/WaitlistOfferIT.java index 966ac88c..b4007eb1 100644 --- a/services/scheduling-service/src/test/java/com/northwind/scheduling/service/WaitlistOfferIT.java +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/service/WaitlistOfferIT.java @@ -163,6 +163,11 @@ void acceptBooksTheCandidateAndShiftsTheWaitlist() { assertThat(post("/api/v2/offers/99999/accept").getBody()).containsEntry("error", "OFFER_NOT_FOUND"); assertThat(http.exchange("/api/v2/offers/" + offerId, HttpMethod.GET, null, MAP).getBody()) .containsEntry("status", "ACCEPTED").containsEntry("bookingId", 13); + Object center = http.exchange("/api/v2/sessions/163", HttpMethod.GET, null, MAP).getBody().get("centerCode"); + assertThat(http.exchange("/api/v2/internal/routing/resolve?offerId=" + offerId, HttpMethod.GET, null, MAP).getBody()) + .containsEntry("centerCode", center); + assertThat(http.exchange("/api/v2/internal/routing/resolve?offerId=99999", HttpMethod.GET, null, MAP).getStatusCode()) + .isEqualTo(HttpStatus.NOT_FOUND); } @Test From 6bf17782ae0898d0120efd49e35be7e2fd77d97e Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:32:03 +0000 Subject: [PATCH 3/3] [MBA-3829] feature: renumber waitlist auto-offer ADR to 0005 (M5 took 0004) Co-Authored-By: Mason --- docs/adr/0002-ported-rule-decisions.md | 2 +- ...004-waitlist-auto-offer.md => 0005-waitlist-auto-offer.md} | 2 +- docs/runbooks/scheduling-service.md | 2 +- services/scheduling-service/api/openapi.yaml | 2 +- .../java/com/northwind/scheduling/domain/OfferStatus.java | 2 +- .../java/com/northwind/scheduling/domain/SeatFormula.java | 2 +- .../java/com/northwind/scheduling/domain/SessionCapacity.java | 2 +- .../com/northwind/scheduling/domain/WaitlistOfferRules.java | 2 +- .../java/com/northwind/scheduling/outbox/OutboxEventType.java | 2 +- .../com/northwind/scheduling/service/SchedulingService.java | 4 ++-- .../com/northwind/scheduling/service/WaitlistOfferPolicy.java | 2 +- .../src/main/java/com/northwind/scheduling/web/Dtos.java | 2 +- .../main/java/com/northwind/scheduling/web/OpenApiConfig.java | 2 +- .../scheduling-service/src/main/resources/application.yml | 2 +- .../src/main/resources/db/migration/V3__waitlist_offers.sql | 2 +- .../northwind/scheduling/domain/WaitlistOfferRulesTest.java | 2 +- .../java/com/northwind/scheduling/web/SchedulingApiIT.java | 2 +- 17 files changed, 18 insertions(+), 18 deletions(-) rename docs/adr/{0004-waitlist-auto-offer.md => 0005-waitlist-auto-offer.md} (98%) diff --git a/docs/adr/0002-ported-rule-decisions.md b/docs/adr/0002-ported-rule-decisions.md index 9255308e..d7ec22c6 100644 --- a/docs/adr/0002-ported-rule-decisions.md +++ b/docs/adr/0002-ported-rule-decisions.md @@ -32,7 +32,7 @@ drift, which is what settles ODD-01, ODD-05, ODD-10 (seat part) and ODD-13. | ODD-06 | 6. accommodation floor on capacity reductions | **Keep** (`scheduling.rules.accommodation-floor: allocated`) | Capacity below `AccommodationCapacity` (or negative) is rejected with `INVALID_CAPACITY` (HTTP 409, legacy code 50005 = state 5), and nothing changes. `booked` (floor = extra-time seats in use) is opt-in and not legacy behaviour. Equal to the allocation is allowed (`CP-08`). | portal `CP-05`, `CP-08`; db `CP-06` | `022_usp_ChangeCapacity.sql` (state 5; PR 51 not in `legacy-baseline`), HB-14 | `AccommodationFloorPolicy`, `CapacityChange` | | ODD-07 | 6a. blank accommodation code | **Keep API meaning** | Blank / missing code = no accommodation (stored NULL, no accommodation seat used), as in booking-api. The portal's silent fallback to the profile default moves into the UI, which shows the code explicitly. Unknown codes -> `VALIDATION` 400. `ET25`/`ET50` consume accommodation seats, `SR`/`RB` never do (`AC-01..AC-04`, `AC-07`, `AC-08`). | portal `AC-05`; api `AC-06` | booking-api `StringUtils.trimToNull`, portal `AccommodationCodes.cs` / `BookingService.cs` (HB-09) | `AccommodationCodes` | | ODD-08 | 6b. reschedule onto the same session | **Keep API rule** | Refused on every channel with `SAME_SESSION` (409). The portal's cancel + re-book on the same session (new id, seat released and re-taken) is not reproduced. | portal `RS-05`; api `RS-06` | booking-api `BookingService.reschedule`, `023_usp_RescheduleBooking.sql` (HB-10, HB-11) | `ReschedulePolicy` | -| ODD-09 | - | **Keep** | Cancelling a BOOKED seat frees it but promotes nobody. Cancelling a WAITLISTED booking deletes its waitlist entry, and the other positions are not renumbered. A second cancel -> `NOT_CANCELLABLE` (409 / 50004). Automatic promotion is a product decision for a later story: superseded for BOOKED cancels by [ADR 0004](0004-waitlist-auto-offer.md) (MBA-3829, the freed seat is offered to the waitlist; legacy unchanged). | portal `CN-05`, `CN-03`, `CN-07`; api `CN-06`, `CN-04`, `CN-08` | `021_usp_CancelBooking.sql` (HB-06) | `BookingRules.checkCancellable`, `SchedulingService.cancel` | +| ODD-09 | - | **Keep** | Cancelling a BOOKED seat frees it but promotes nobody. Cancelling a WAITLISTED booking deletes its waitlist entry, and the other positions are not renumbered. A second cancel -> `NOT_CANCELLABLE` (409 / 50004). Automatic promotion is a product decision for a later story: superseded for BOOKED cancels by [ADR 0005](0005-waitlist-auto-offer.md) (MBA-3829, the freed seat is offered to the waitlist; legacy unchanged). | portal `CN-05`, `CN-03`, `CN-07`; api `CN-06`, `CN-04`, `CN-08` | `021_usp_CancelBooking.sql` (HB-06) | `BookingRules.checkCancellable`, `SchedulingService.cancel` | | ODD-10 | - | **Change** | A rescheduled booking keeps the original `channel`, `external_ref` and accommodation code, so partner references (PX-3008) survive. | portal `RS-08` | `023_usp_RescheduleBooking.sql` (HB-10) | `ReschedulePolicy`, `SchedulingService.reschedule` | | ODD-11 | - | **Change (mapping)** | Errors carry a symbolic `error` and `legacyCode = 50000 + proc state`: `SESSION_NOT_OPEN` 50001, `DUPLICATE_BOOKING` 50002, `NO_ACCOMMODATION_SEAT` 50003, `NOT_CANCELLABLE` 50004, `INVALID_CAPACITY` 50005, `DIFFERENT_EXAM` 50006. This is the documented 5000x table the procs never raised. | db `BK-07`, `CP-06`, `RS-07` | `db/procs/020..023` (HB-14) | `ErrorCode`, `web/ApiExceptionHandler` | | ODD-12 | - | **Change** | Every channel gets booking-api's shape: HTTP 409 `{error, message, legacyCode}` (404 / 400 for not found / validation), never an HTTP 200 page with an alert. The UI shows these as toasts and inline errors. | portal `BK-05`, `BK-08`, `BK-10`, `CP-05`, `RS-03`; api `BK-06`, `BK-09`, `BK-11`, `RS-04` | portal controllers vs booking-api (HB-14) | `web/ApiExceptionHandler` | diff --git a/docs/adr/0004-waitlist-auto-offer.md b/docs/adr/0005-waitlist-auto-offer.md similarity index 98% rename from docs/adr/0004-waitlist-auto-offer.md rename to docs/adr/0005-waitlist-auto-offer.md index 4f5dbd1e..168139f1 100644 --- a/docs/adr/0004-waitlist-auto-offer.md +++ b/docs/adr/0005-waitlist-auto-offer.md @@ -1,4 +1,4 @@ -# ADR 0004: freed seats are offered to the waitlist (MBA-3829, A4) +# ADR 0005: freed seats are offered to the waitlist (MBA-3829, A4) Status: accepted. Deliberate behaviour change to [ADR 0002](0002-ported-rule-decisions.md) ODD-09, built on the single writer and outbox of [ADR 0003](0003-single-writer-outbox-relay.md). diff --git a/docs/runbooks/scheduling-service.md b/docs/runbooks/scheduling-service.md index e8a0ee5b..21bb0469 100644 --- a/docs/runbooks/scheduling-service.md +++ b/docs/runbooks/scheduling-service.md @@ -148,7 +148,7 @@ event id in `dbo.RelayCheckpoint` ([ADR 0003](../adr/0003-single-writer-outbox-r ### Waitlist offers stuck or not made (MBA-3829) A seat freed in an `OPEN` session is offered to the next eligible waitlist entry and held while the offer is -`PENDING` ([ADR 0004](../adr/0004-waitlist-auto-offer.md)). Config: `scheduling.waitlist.offer-ttl` +`PENDING` ([ADR 0005](../adr/0005-waitlist-auto-offer.md)). Config: `scheduling.waitlist.offer-ttl` (`SCHEDULING_WAITLIST_OFFER_TTL`, default `PT24H`), `scheduling.waitlist.expiry-enabled` (`..._EXPIRY_ENABLED`, default `true`), `scheduling.waitlist.expiry-poll` (`..._EXPIRY_POLL`, default `PT1M`). diff --git a/services/scheduling-service/api/openapi.yaml b/services/scheduling-service/api/openapi.yaml index 6aeceb54..e405f87c 100644 --- a/services/scheduling-service/api/openapi.yaml +++ b/services/scheduling-service/api/openapi.yaml @@ -193,7 +193,7 @@ paths: $ref: "#/components/schemas/ApiError" description: "Rule violation: NOT_CANCELLABLE" summary: "Cancel a booking (frees the seat; it is offered to the next eligible\ - \ waitlist entry, MBA-3829 / ADR 0004)" + \ waitlist entry, MBA-3829 / ADR 0005)" tags: - Bookings get: diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/OfferStatus.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/OfferStatus.java index db074688..3750ac11 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/OfferStatus.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/OfferStatus.java @@ -1,6 +1,6 @@ package com.northwind.scheduling.domain; -/** seat_offer.status (V3__waitlist_offers.sql, ADR 0004). Only PENDING holds a seat. */ +/** seat_offer.status (V3__waitlist_offers.sql, ADR 0005). Only PENDING holds a seat. */ public enum OfferStatus { PENDING, ACCEPTED, DECLINED, EXPIRED, WITHDRAWN } diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SeatFormula.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SeatFormula.java index 76e6372b..60c3c467 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SeatFormula.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SeatFormula.java @@ -7,7 +7,7 @@ *
    *
  • {@link #STANDARD}: Capacity - (BOOKED + ATTENDED), the formula of db/procs/024 seat-drift, * booking-api SeatCounter and SeatCounter.cs. Chosen by ADR 0002. Seats held by pending waitlist offers are not - * available either (MBA-3829, ADR 0004); legacy SeatsAvailable still excludes them (OutboxRepository).
  • + * available either (MBA-3829, ADR 0005); legacy SeatsAvailable still excludes them (OutboxRepository). *
  • {@link #CAPACITY_SYNC}: Capacity - AccommodationCapacity - active standard (non ET) bookings, * floored at 0, from services/capacity-sync CapacitySyncService. Kept only for comparison.
  • *
diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SessionCapacity.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SessionCapacity.java index 401bfd66..e1414bd1 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SessionCapacity.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/SessionCapacity.java @@ -10,7 +10,7 @@ * @param accommodationUsed BOOKED + ATTENDED bookings with ET25/ET50 (booking-api * BookingDao.countAccommodationSeatsUsed, usp_BookSeat) * @param waitlisted WAITLISTED bookings - * @param heldSeats seats held by PENDING waitlist offers (MBA-3829, ADR 0004) + * @param heldSeats seats held by PENDING waitlist offers (MBA-3829, ADR 0005) * @param accommodationHeld held seats whose offered booking is ET25/ET50 (holds an accommodation seat too) */ public record SessionCapacity(int capacity, int accommodationCapacity, int occupiedSeats, int accommodationUsed, diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistOfferRules.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistOfferRules.java index 85cf871f..6ce8ce17 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistOfferRules.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/WaitlistOfferRules.java @@ -5,7 +5,7 @@ import java.util.List; /** - * Who gets a freed seat (MBA-3829, ADR 0004). Deliberate change from legacy, where usp_CancelBooking promotes + * Who gets a freed seat (MBA-3829, ADR 0005). Deliberate change from legacy, where usp_CancelBooking promotes * nobody (HB-06, MR-12, ODD-09): every seat that is free and not held is offered, in waitlist position order, * to the first entry whose accommodation needs fit. An ET25/ET50 entry is skipped (and keeps its place) while no * accommodation seat is free; SR/RB/none only need a seat. Only OPEN sessions make offers. diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxEventType.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxEventType.java index 9b83bdf5..b05773cb 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxEventType.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxEventType.java @@ -10,7 +10,7 @@ public enum OutboxEventType { CapacityChanged("ExamSession", "CAPACITY_CHANGE"), /** after a snapshot import: SeatsAvailable for every session (scheduling-service is the single seat writer) */ InventoryBaselined("ExamSession", "SEAT_BASELINE"), - /** MBA-3829 (ADR 0004): a held seat offered to a waitlisted booking; legacy rows unchanged (still WAITLISTED) */ + /** MBA-3829 (ADR 0005): a held seat offered to a waitlisted booking; legacy rows unchanged (still WAITLISTED) */ SeatOffered("Booking", "WAITLIST_OFFER"), /** offer accepted: booking BOOKED, waitlist row removed, later positions shifted up */ SeatOfferAccepted("Booking", "WAITLIST_OFFER_ACCEPT"), diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/service/SchedulingService.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/service/SchedulingService.java index aa69c0f5..3a308f4c 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/service/SchedulingService.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/service/SchedulingService.java @@ -177,7 +177,7 @@ private BookingOutcome book(BookCommand cmd, Integer rescheduledFrom) { /** * usp_CancelBooking: frees the seat (derived count), drops the waitlist row (positions keep their gap, HB-06). * Unlike legacy (ODD-09) a freed or released held seat is offered to the next eligible waitlist entry - * (MBA-3829, ADR 0004); a pending offer of the cancelled booking is withdrawn. + * (MBA-3829, ADR 0005); a pending offer of the cancelled booking is withdrawn. */ @Transactional public Rows.Booking cancel(int bookingId, String reason) { @@ -205,7 +205,7 @@ private boolean withdrawPendingOffer(int bookingId, String reason) { }).orElse(false); } - // ------------------------------------------------------------------ waitlist offers (MBA-3829, ADR 0004) + // ------------------------------------------------------------------ waitlist offers (MBA-3829, ADR 0005) public Rows.Offer offer(int offerId) { return repo.offer(offerId).orElseThrow( diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferPolicy.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferPolicy.java index bc74d2af..5112008a 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferPolicy.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/service/WaitlistOfferPolicy.java @@ -22,7 +22,7 @@ import com.northwind.scheduling.persistence.SchedulingRepository; /** - * Waitlist auto-offer (MBA-3829, ADR 0004). Callers hold the session lock (SchedulingRepository.lockSession) and + * Waitlist auto-offer (MBA-3829, ADR 0005). Callers hold the session lock (SchedulingRepository.lockSession) and * a transaction, so offers, the change that freed the seat and their outbox events commit together and two * concurrent seat releases cannot offer the same seat twice. */ diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/Dtos.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/Dtos.java index 6c6b0d14..387ae350 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/Dtos.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/Dtos.java @@ -52,7 +52,7 @@ static BookingDto of(Rows.Booking b) { } } - /** MBA-3829: a seat offered to a waitlisted booking (ADR 0004). */ + /** MBA-3829: a seat offered to a waitlisted booking (ADR 0005). */ public record OfferDto(int offerId, int sessionId, int bookingId, String candidateNumber, int position, String status, LocalDateTime offeredAt, LocalDateTime expiresAt, LocalDateTime resolvedAt) { static OfferDto of(Rows.Offer o) { diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/OpenApiConfig.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/OpenApiConfig.java index 6a18136a..7edd41b3 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/web/OpenApiConfig.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/web/OpenApiConfig.java @@ -95,7 +95,7 @@ public class OpenApiConfig { "Book a seat (WAITLISTED when the session is full); returns the legacy {bookingId, status} plus the live booking and session"}), Map.entry("booking", new String[] {"Bookings", "Get a booking"}), Map.entry("cancel", new String[] {"Bookings", - "Cancel a booking (frees the seat; it is offered to the next eligible waitlist entry, MBA-3829 / ADR 0004)"}), + "Cancel a booking (frees the seat; it is offered to the next eligible waitlist entry, MBA-3829 / ADR 0005)"}), Map.entry("offer", new String[] {"Offers", "Get a waitlist seat offer"}), Map.entry("acceptOffer", new String[] {"Offers", "Accept a pending seat offer (the waitlisted booking becomes BOOKED, later waitlist positions move up)"}), diff --git a/services/scheduling-service/src/main/resources/application.yml b/services/scheduling-service/src/main/resources/application.yml index 4a1ff999..ef7eb277 100644 --- a/services/scheduling-service/src/main/resources/application.yml +++ b/services/scheduling-service/src/main/resources/application.yml @@ -85,7 +85,7 @@ scheduling: password: ${SCHEDULING_RELAY_DB_PASSWORD:Sch3dRelay!Dev2026} poll-ms: ${SCHEDULING_RELAY_POLL_MS:250} batch-size: ${SCHEDULING_RELAY_BATCH_SIZE:200} - # MBA-3829 waitlist auto-offer (ADR 0004): a freed seat is held for the next eligible waitlisted candidate for + # MBA-3829 waitlist auto-offer (ADR 0005): a freed seat is held for the next eligible waitlisted candidate for # offer-ttl (ISO-8601 duration); the expiry job checks every expiry-poll and moves expired offers on. waitlist: offer-ttl: ${SCHEDULING_WAITLIST_OFFER_TTL:PT24H} diff --git a/services/scheduling-service/src/main/resources/db/migration/V3__waitlist_offers.sql b/services/scheduling-service/src/main/resources/db/migration/V3__waitlist_offers.sql index e578f96d..e2004932 100644 --- a/services/scheduling-service/src/main/resources/db/migration/V3__waitlist_offers.sql +++ b/services/scheduling-service/src/main/resources/db/migration/V3__waitlist_offers.sql @@ -1,4 +1,4 @@ --- MBA-3829 waitlist auto-offer (ADR 0004). A freed seat in an OPEN session is offered to the lowest-position waitlist +-- MBA-3829 waitlist auto-offer (ADR 0005). A freed seat in an OPEN session is offered to the lowest-position waitlist -- entry whose accommodation needs fit (service/WaitlistOfferPolicy). While an offer is PENDING the seat is held: -- SessionCapacity subtracts held seats from availability, so nobody else can book it. -- The hold lives only here. Legacy dbo.ExamSession.SeatsAvailable keeps Capacity - (BOOKED + ATTENDED) (seat-drift.sql, diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/domain/WaitlistOfferRulesTest.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/domain/WaitlistOfferRulesTest.java index 1cc1967f..08d6edd0 100644 --- a/services/scheduling-service/src/test/java/com/northwind/scheduling/domain/WaitlistOfferRulesTest.java +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/domain/WaitlistOfferRulesTest.java @@ -6,7 +6,7 @@ import org.junit.jupiter.api.Test; -/** MBA-3829 / ADR 0004: who gets a freed seat. */ +/** MBA-3829 / ADR 0005: who gets a freed seat. */ class WaitlistOfferRulesTest { static final List THREE = List.of(new WaitlistSlot(13, 1, null), new WaitlistSlot(14, 2, null), diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/web/SchedulingApiIT.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/web/SchedulingApiIT.java index 45f64cf6..3fb379bc 100644 --- a/services/scheduling-service/src/test/java/com/northwind/scheduling/web/SchedulingApiIT.java +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/web/SchedulingApiIT.java @@ -154,7 +154,7 @@ void capacityDecreaseBelowActiveBookingsDemotesNewestToWaitlist() { Map raised = http.exchange("/api/v2/sessions/154/capacity", HttpMethod.PUT, new HttpEntity<>(Map.of("capacity", 12)), MAP).getBody(); - // MBA-3829 / ADR 0004: 6 seats free up, 3 are held by offers to the waitlisted 7, 8, 9 (legacy ODD-09 promoted nobody) + // MBA-3829 / ADR 0005: 6 seats free up, 3 are held by offers to the waitlisted 7, 8, 9 (legacy ODD-09 promoted nobody) assertThat(((Map) raised.get("session")).get("seatsAvailable")).isEqualTo(3); assertThat(get("/api/v2/sessions/154")).containsEntry("waitlistCount", 3).containsEntry("heldSeats", 3); assertThat(get("/api/v2/bookings/7")).containsEntry("status", "WAITLISTED").containsEntry("offerStatus", "PENDING");
#CandidateAdded
#CandidateAddedOffer
{fmtDateTime(w.addedAt)}{fmtDateTime(w.addedAt)} + {w.offerStatus === 'PENDING' + ? Seat offered · until {w.offerExpiresAt ? fmtDateTime(w.offerExpiresAt) : '—'} + : —} +