diff --git a/docs/runbooks/scheduling-service.md b/docs/runbooks/scheduling-service.md index 21bb0469..ebd6e8a1 100644 --- a/docs/runbooks/scheduling-service.md +++ b/docs/runbooks/scheduling-service.md @@ -145,6 +145,16 @@ 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). +### Candidate notifications (MBA-3831) + +Capacity changes emit one `CandidateCapacityImpactNotified` outbox event per affected candidate +(`services/scheduling-service/docs/events.md`). The relay delivers them to the notification stub instead of legacy, in +the same `event_seq` order, so they count towards outbox pending/lag like any other event and never touch +`AssessmentDelivery` or reconciliation. Check what a candidate was told: +`curl -s 'localhost:8090/internal/notifications?candidateNumber=NW00000909'` (direct to :8090; the gateway returns 404), +or search the logs for `"event":"CandidateCapacityImpactNotified"`. The stub keeps them in memory only (lost on restart); +there is no email/SMS yet. + ### 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 diff --git a/reports/reconciliation-20261111-222613.md b/reports/reconciliation-20261111-222613.md new file mode 100644 index 00000000..2af2c813 --- /dev/null +++ b/reports/reconciliation-20261111-222613.md @@ -0,0 +1,26 @@ +# Reconciliation: Scheduling vs AssessmentDelivery + +Generated 2026-11-11T22:26:13 by scheduling-service `reconcile` (MBA-3823). + +| check | result | +|---|---| +| sessions compared | 462 | +| bookings compared | 3587 | +| session field mismatches | 0 | +| booking mismatches | 0 | +| **total mismatches** | **0** | +| `db/checks/seat-drift.sql` rows | 0 | + +Per session: Capacity, SeatsAvailable (Scheduling derives Capacity - (BOOKED + ATTENDED), floored at 0; legacy is the stored counter), BOOKED / ATTENDED / WAITLISTED counts and accommodation seats used (BOOKED + ATTENDED with ET25/ET50). Per booking: session, status and accommodation code, keyed on the legacy BookingId (`booking.legacy_booking_id`). + +## Session mismatches + +None. + +## Booking mismatches + +None. + +## `db/checks/seat-drift.sql` + +Source: `db/checks/seat-drift.sql`. 0 rows (no drift). diff --git a/services/scheduling-service/README.md b/services/scheduling-service/README.md index b8b8c8d6..3e0f0b55 100644 --- a/services/scheduling-service/README.md +++ b/services/scheduling-service/README.md @@ -7,3 +7,5 @@ with `JAVA_HOME= ./mvnw -B verify` (Testcontainers SQL Server needs Dock - Operations: health/readiness probes, Prometheus metrics, JSON logs and on-call scenarios are in the [runbook](../../docs/runbooks/scheduling-service.md). - Ported rule decisions: [ADR 0002](../../docs/adr/0002-ported-rule-decisions.md). +- Outbox events, incl. the `CandidateCapacityImpactNotified` candidate notification and its stub + (`GET /internal/notifications`): [docs/events.md](docs/events.md). diff --git a/services/scheduling-service/api/openapi.yaml b/services/scheduling-service/api/openapi.yaml index e405f87c..a06d8d7f 100644 --- a/services/scheduling-service/api/openapi.yaml +++ b/services/scheduling-service/api/openapi.yaml @@ -1328,6 +1328,9 @@ components: type: integer format: int32 example: 5 + notifiedCandidates: + type: integer + format: int32 oldCapacity: type: integer format: int32 @@ -1337,6 +1340,7 @@ components: required: - demotedBookingIds - newCapacity + - notifiedCandidates - oldCapacity - session CenterDto: diff --git a/services/scheduling-service/docs/events.md b/services/scheduling-service/docs/events.md new file mode 100644 index 00000000..1c5078f2 --- /dev/null +++ b/services/scheduling-service/docs/events.md @@ -0,0 +1,65 @@ +# scheduling-service events + +All events ride the M4 transactional outbox (`outbox_event`, [ADR 0003](../../../docs/adr/0003-single-writer-outbox-relay.md)): +they are written in the same transaction as the change and processed by `RelayWorker` in `event_seq` order. +State-transfer events (`BookingCreated` ... `InventoryBaselined`, `OutboxEventType`) are projected into +`AssessmentDelivery` by `LegacyRelay`. Notification events are not projected into legacy; the relay hands them to +`NotificationPort` instead. + +## CandidateCapacityImpactNotified (MBA-3831) + +Schema: [`schemas/candidate-capacity-impact-notified.schema.json`](schemas/candidate-capacity-impact-notified.schema.json) +(JSON Schema 2020-12, enforced by `CandidateCapacityImpactSchemaTest` and `CapacityImpactNotificationIT`). + +**When.** `PUT /api/v2/sessions/{sessionId}/capacity` (`SchedulingService.changeCapacity`) emits one event per +affected candidate, in the same transaction as the `CapacityChanged` event and the `capacity_change` row +(`domain/CapacityImpact`): + +| impact | who | previousStatus -> newStatus | +|---|---|---| +| `STATUS_CHANGED` | every booking of the session whose status changed with the change: the newest BOOKED bookings demoted to the waitlist when capacity drops below the booked seats ([HB-05](../../../docs/as-is/hidden-behaviours.md), [ODD-02](../../../characterization/ODDITIES.md)) | e.g. `BOOKED` -> `WAITLISTED` | +| `SEAT_OFFERED` | a waitlisted booking that the A4 auto-offer ([ADR 0005](../../../docs/adr/0005-waitlist-auto-offer.md)) offered a freed seat in this transaction, e.g. after a capacity increase; the booking stays `WAITLISTED` until the offer is accepted | `WAITLISTED` -> `WAITLISTED` | +| `OFFER_WITHDRAWN` | a waitlisted booking whose pending offer was withdrawn because capacity dropped (`WaitlistOfferPolicy.withdrawExcess`); it keeps its waitlist place | `WAITLISTED` -> `WAITLISTED` | +| `SEAT_CONFIRMED` | capacity reduced: every booking still `BOOKED` after the change ("capacity reduced, your seat is confirmed") | `BOOKED` -> `BOOKED` | + +A capacity increase never promotes a waitlisted booking directly ([HB-06](../../../docs/as-is/hidden-behaviours.md), +ODD-09); with A4 it may make seat offers (`SEAT_OFFERED`), otherwise it emits no event. Legacy never notified anyone ([MR-04](../../../docs/as-is/migration-risks.md) +"who notifies demoted candidates?"); this event is the modern answer. `ATTENDED`, `CANCELLED` and `WAITLISTED` +bookings whose status does not change are not notified, unless a seat offer was made or withdrawn for them. + +**Payload.** `outbox_event.payload` is the usual `OutboxPayload` (`type`, `detail`, `bookings: []`, +`sessions: []`) plus `notification`, which is the event: + +| field | type | meaning | +|---|---|---| +| `eventId` | uuid | equals `outbox_event.event_id`; idempotency key for `NotificationPort` | +| `sessionId` | int | exam session | +| `centerCode` | string | test centre code, e.g. `SFO01` | +| `examCode` | string | exam code, e.g. `MHL-RN1` | +| `startsAt` | local date-time | session start in the centre's local time (as `ExamSession.StartsAt`), no offset | +| `oldCapacity` / `newCapacity` | int | session capacity before / after the change | +| `candidateNumber` | string | `NW` + 8 digits | +| `bookingId` | int | affected booking | +| `previousStatus` / `newStatus` | `BOOKED`, `WAITLISTED`, `CANCELLED`, `ATTENDED` | booking status before / after the change | +| `impact` | `STATUS_CHANGED`, `SEAT_OFFERED`, `OFFER_WITHDRAWN`, `SEAT_CONFIRMED` | why the candidate is notified (see above) | + +```json +{ + "eventId": "8a7b3c52-5f43-4c0e-9f6e-2f1d0c9b7a11", + "sessionId": 154, "centerCode": "SFO01", "examCode": "MHL-RN1", "startsAt": "2026-11-12T13:30:00", + "oldCapacity": 20, "newCapacity": 8, + "candidateNumber": "NW00000909", "bookingId": 9, + "previousStatus": "BOOKED", "newStatus": "WAITLISTED", "impact": "STATUS_CHANGED" +} +``` + +**Delivery.** `RelayWorker` -> `NotificationDelivery` -> `NotificationPort.notify`. Delivery is at least once (a crash +between delivery and `markRelayed` redelivers the event), so ports deduplicate on `eventId`. Nothing is written to +`AssessmentDelivery` (no `AuditLog`, no `RelayCheckpoint`), so reconciliation is unaffected. + +**Stub.** `LoggingNotificationAdapter` is the only `NotificationPort`: no email/SMS. It writes one JSON log line +(`"event":"CandidateCapacityImpactNotified"` plus every field above; with the `plain-logs` profile the message itself +carries impact, candidateNumber, bookingId, sessionId, previous/new status and eventId as `key=value`) and keeps the newest +`scheduling.notifications.stub.max-records` (default 10000) in memory, readable at +`GET /internal/notifications?candidateNumber=NW...` on :8090 (`candidateNumber` is required, 400 without it, so there +is no bulk listing; not in the public OpenAPI spec; the routing gateway does not route `/internal/**`). The store is per process and empty after a restart. diff --git a/services/scheduling-service/docs/schemas/candidate-capacity-impact-notified.schema.json b/services/scheduling-service/docs/schemas/candidate-capacity-impact-notified.schema.json new file mode 100644 index 00000000..f5f4f105 --- /dev/null +++ b/services/scheduling-service/docs/schemas/candidate-capacity-impact-notified.schema.json @@ -0,0 +1,27 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://northwind.example/scheduling/events/candidate-capacity-impact-notified.schema.json", + "title": "CandidateCapacityImpactNotified", + "description": "One candidate affected by PUT /api/v2/sessions/{sessionId}/capacity (MBA-3831). Carried in outbox_event.payload.notification; see docs/events.md.", + "type": "object", + "additionalProperties": false, + "required": ["eventId", "sessionId", "centerCode", "examCode", "startsAt", "oldCapacity", "newCapacity", + "candidateNumber", "bookingId", "previousStatus", "newStatus", "impact"], + "properties": { + "eventId": { "type": "string", "format": "uuid", "description": "= outbox_event.event_id; idempotency key for NotificationPort" }, + "sessionId": { "type": "integer", "minimum": 1 }, + "centerCode": { "type": "string", "minLength": 1 }, + "examCode": { "type": "string", "minLength": 1 }, + "startsAt": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$", "description": "Session start, ISO-8601 local date-time in the centre's time zone (no offset), as ExamSession.StartsAt" }, + "oldCapacity": { "type": "integer", "minimum": 0 }, + "newCapacity": { "type": "integer", "minimum": 0 }, + "candidateNumber": { "type": "string", "pattern": "^NW\\d{8}$" }, + "bookingId": { "type": "integer", "minimum": 1 }, + "previousStatus": { "$ref": "#/$defs/bookingStatus" }, + "newStatus": { "$ref": "#/$defs/bookingStatus" }, + "impact": { "enum": ["STATUS_CHANGED", "SEAT_OFFERED", "OFFER_WITHDRAWN", "SEAT_CONFIRMED"], "description": "STATUS_CHANGED: previousStatus != newStatus. SEAT_OFFERED / OFFER_WITHDRAWN: waitlisted booking got / lost a pending seat offer (stays WAITLISTED). SEAT_CONFIRMED: capacity reduced, booking stays BOOKED" } + }, + "$defs": { + "bookingStatus": { "enum": ["BOOKED", "WAITLISTED", "CANCELLED", "ATTENDED"] } + } +} diff --git a/services/scheduling-service/frontend/src/api.ts b/services/scheduling-service/frontend/src/api.ts index 03476057..bd3f5e99 100644 --- a/services/scheduling-service/frontend/src/api.ts +++ b/services/scheduling-service/frontend/src/api.ts @@ -30,7 +30,7 @@ export interface Offer { 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[] } +export interface CapacityResult { session: Session; oldCapacity: number; newCapacity: number; demotedBookingIds: number[]; notifiedCandidates: number } export class ApiError extends Error { constructor(public status: number, public code: string, message: string, public legacyCode?: number | null) { diff --git a/services/scheduling-service/frontend/src/components/CapacityEditor.tsx b/services/scheduling-service/frontend/src/components/CapacityEditor.tsx index 833e05a2..958a4c2b 100644 --- a/services/scheduling-service/frontend/src/components/CapacityEditor.tsx +++ b/services/scheduling-service/frontend/src/components/CapacityEditor.tsx @@ -5,7 +5,8 @@ import { useToast } from './Toast'; /** * Inline capacity edit with a confirmation step. Lowering below the booked count demotes the newest - * bookings to the waitlist (ADR 0002, ODD-02); the floor is the accommodation allocation (ODD-08). + * bookings to the waitlist (ADR 0002, ODD-02); the floor is the accommodation allocation (ODD-08). Affected + * candidates get a CandidateCapacityImpactNotified event (MBA-3831, docs/events.md). */ export default function CapacityEditor({ session, onChanged }: { session: Session; onChanged: (r: CapacityResult) => void }) { const toast = useToast(); @@ -25,8 +26,11 @@ export default function CapacityEditor({ session, onChanged }: { session: Sessio try { const r = await api.changeCapacity(session.sessionId, n, 'Changed in admin UI'); onChanged(r); - toast('success', `Session #${session.sessionId}: capacity ${r.oldCapacity} → ${r.newCapacity}`, - r.demotedBookingIds.length ? `${r.demotedBookingIds.length} booking(s) moved to the waitlist` : undefined); + const detail = [ + r.demotedBookingIds.length ? `${r.demotedBookingIds.length} booking(s) moved to the waitlist` : '', + r.notifiedCandidates ? `${r.notifiedCandidates} candidate notification(s) queued (stub, no email/SMS)` : '', + ].filter(Boolean).join('; '); + toast('success', `Session #${session.sessionId}: capacity ${r.oldCapacity} → ${r.newCapacity}`, detail || undefined); setEditing(false); } catch (e) { const ae = e as ApiError; @@ -59,6 +63,7 @@ export default function CapacityEditor({ session, onChanged }: { session: Sessio setConfirming(false)}>

Change session #{session.sessionId} from {session.capacity} to {n} seats?

{demotions > 0 &&

{demotions} active booking(s) exceed the new capacity; the newest will be moved to the waitlist.

} + {n < session.capacity && session.bookedSeats > 0 &&

A notification event is queued for each affected candidate (MBA-3831; stub, no email/SMS yet).

}
diff --git a/services/scheduling-service/pom.xml b/services/scheduling-service/pom.xml index d34c968d..11b2c4c5 100644 --- a/services/scheduling-service/pom.xml +++ b/services/scheduling-service/pom.xml @@ -131,6 +131,13 @@ ${openapi-diff.version} test + + + com.networknt + json-schema-validator + 1.5.9 + test + diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/CapacityImpact.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/CapacityImpact.java new file mode 100644 index 00000000..8e47c54c --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/domain/CapacityImpact.java @@ -0,0 +1,66 @@ +package com.northwind.scheduling.domain; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Candidates affected by a capacity change (MBA-3831, MR-04 "who notifies demoted candidates"): every booking whose + * status changed with the change (e.g. BOOKED -> WAITLISTED demotions, ODD-02), every waitlisted booking that got a + * seat offer or lost its pending offer in the change (A4 auto-offer, ADR 0005; the booking stays WAITLISTED), and, + * when capacity drops, every booking that is still BOOKED. A capacity increase that changes no status and makes no + * offer affects nobody. + */ +public final class CapacityImpact { + + public enum Kind { + STATUS_CHANGED, SEAT_OFFERED, OFFER_WITHDRAWN, SEAT_CONFIRMED + } + + public record BookingState(int bookingId, String candidateNumber, BookingStatus status) { + } + + public record Affected(int bookingId, String candidateNumber, BookingStatus previousStatus, + BookingStatus newStatus, Kind kind) { + } + + private CapacityImpact() { + } + + public static List affected(int oldCapacity, int newCapacity, List before, + List after) { + return affected(oldCapacity, newCapacity, before, after, Set.of(), Set.of()); + } + + /** + * @param before / after the session's bookings before and after the change, in the same transaction + * @param offeredBefore / offeredAfter booking ids with a PENDING seat offer before and after the change + */ + public static List affected(int oldCapacity, int newCapacity, List before, + List after, Set offeredBefore, + Set offeredAfter) { + Map prev = before.stream() + .collect(Collectors.toMap(BookingState::bookingId, Function.identity(), (a, b) -> a)); + List out = new ArrayList<>(); + for (BookingState now : after.stream().sorted(Comparator.comparingInt(BookingState::bookingId)).toList()) { + BookingState was = prev.get(now.bookingId()); + if (was == null) { + continue; + } + if (was.status() != now.status()) { + out.add(new Affected(now.bookingId(), now.candidateNumber(), was.status(), now.status(), Kind.STATUS_CHANGED)); + } else if (offeredAfter.contains(now.bookingId()) && !offeredBefore.contains(now.bookingId())) { + out.add(new Affected(now.bookingId(), now.candidateNumber(), was.status(), now.status(), Kind.SEAT_OFFERED)); + } else if (offeredBefore.contains(now.bookingId()) && !offeredAfter.contains(now.bookingId())) { + out.add(new Affected(now.bookingId(), now.candidateNumber(), was.status(), now.status(), Kind.OFFER_WITHDRAWN)); + } else if (newCapacity < oldCapacity && now.status() == BookingStatus.BOOKED) { + out.add(new Affected(now.bookingId(), now.candidateNumber(), was.status(), now.status(), Kind.SEAT_CONFIRMED)); + } + } + return List.copyOf(out); + } +} diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/CandidateCapacityImpactNotified.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/CandidateCapacityImpactNotified.java new file mode 100644 index 00000000..53c9f49f --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/CandidateCapacityImpactNotified.java @@ -0,0 +1,20 @@ +package com.northwind.scheduling.notification; + +import java.time.LocalDateTime; +import java.util.UUID; + +import com.northwind.scheduling.domain.CapacityImpact; + +/** + * Outbox event CandidateCapacityImpactNotified (MBA-3831): one per candidate affected by + * {@code PUT /api/v2/sessions/{sessionId}/capacity}. Schema and examples: docs/events.md, + * docs/schemas/candidate-capacity-impact-notified.schema.json. + * + * @param impact STATUS_CHANGED (the booking's status changed with the capacity change) or SEAT_CONFIRMED + * (capacity was reduced, the booking stays BOOKED) + */ +public record CandidateCapacityImpactNotified(UUID eventId, int sessionId, String centerCode, String examCode, + LocalDateTime startsAt, int oldCapacity, int newCapacity, + String candidateNumber, int bookingId, String previousStatus, + String newStatus, CapacityImpact.Kind impact) { +} diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/LoggingNotificationAdapter.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/LoggingNotificationAdapter.java new file mode 100644 index 00000000..b3006bc2 --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/LoggingNotificationAdapter.java @@ -0,0 +1,65 @@ +package com.northwind.scheduling.notification; + +import static net.logstash.logback.argument.StructuredArguments.kv; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * Stub {@link NotificationPort} (MBA-3831): no email/SMS. Each notification is written as one structured log line + * and kept in memory (newest {@code scheduling.notifications.stub.max-records}) for + * {@code GET /internal/notifications}. A repeated eventId is ignored. + */ +@Component +public class LoggingNotificationAdapter implements NotificationPort { + + private static final Logger log = LoggerFactory.getLogger(LoggingNotificationAdapter.class); + + private final Map sent; + + public LoggingNotificationAdapter(@Value("${scheduling.notifications.stub.max-records:10000}") int maxRecords) { + this.sent = new LinkedHashMap<>() { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > maxRecords; + } + }; + } + + @Override + public synchronized boolean notify(CandidateCapacityImpactNotified n) { + if (sent.containsKey(n.eventId())) { + log.debug("duplicate notification event {} ignored", n.eventId()); + return false; + } + sent.put(n.eventId(), n); + log.info("candidate notification {} {} {} {} {} {} {}", kv("impact", n.impact()), + kv("candidateNumber", n.candidateNumber()), kv("bookingId", n.bookingId()), + kv("sessionId", n.sessionId()), kv("previousStatus", n.previousStatus()), + kv("newStatus", n.newStatus()), kv("eventId", n.eventId()), + kv("event", "CandidateCapacityImpactNotified"), kv("centerCode", n.centerCode()), + kv("examCode", n.examCode()), kv("startsAt", String.valueOf(n.startsAt())), + kv("oldCapacity", n.oldCapacity()), kv("newCapacity", n.newCapacity())); + return true; + } + + /** Recorded notifications in delivery order; candidateNumber null/blank = all. */ + public synchronized List sent(String candidateNumber) { + List out = new ArrayList<>(); + for (CandidateCapacityImpactNotified n : sent.values()) { + if (candidateNumber == null || candidateNumber.isBlank() + || n.candidateNumber().equalsIgnoreCase(candidateNumber.trim())) { + out.add(n); + } + } + return out; + } +} diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/NotificationController.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/NotificationController.java new file mode 100644 index 00000000..4fc6cd62 --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/NotificationController.java @@ -0,0 +1,32 @@ +package com.northwind.scheduling.notification; + +import java.util.List; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +/** + * MBA-3831 test/operator view of the notification stub, outside /api/v2 and the public OpenAPI spec (like + * /internal/reconciliation); the routing gateway does not route /internal/** to scheduling-service. Lookups are per + * candidate only: there is deliberately no bulk listing of other candidates' notifications. + */ +@RestController +public class NotificationController { + + private final LoggingNotificationAdapter stub; + + public NotificationController(LoggingNotificationAdapter stub) { + this.stub = stub; + } + + @GetMapping("/internal/notifications") + public List notifications(@RequestParam String candidateNumber) { + if (candidateNumber.isBlank()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "candidateNumber is required"); + } + return stub.sent(candidateNumber); + } +} diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/NotificationDelivery.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/NotificationDelivery.java new file mode 100644 index 00000000..35967e4f --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/NotificationDelivery.java @@ -0,0 +1,31 @@ +package com.northwind.scheduling.notification; + +import org.springframework.stereotype.Component; + +import com.northwind.scheduling.outbox.OutboxEvent; + +/** + * Hands CandidateCapacityImpactNotified outbox events to the {@link NotificationPort} (MBA-3831). Called by the + * outbox relay; a redelivered event (relay retry after a crash) is deduplicated by the port on the event id. + */ +@Component +public class NotificationDelivery { + + private final NotificationPort port; + + public NotificationDelivery(NotificationPort port) { + this.port = port; + } + + /** @return true if delivered now, false if the port had already handled this eventId */ + public boolean deliver(OutboxEvent e) { + CandidateCapacityImpactNotified n = e.payload().notification(); + if (e.type().projectsToLegacy() || n == null) { + throw new IllegalStateException(e.type() + " seq=" + e.seq() + " is not a notification event"); + } + if (!n.eventId().equals(e.eventId())) { + throw new IllegalStateException("notification eventId " + n.eventId() + " != outbox event_id " + e.eventId()); + } + return port.notify(n); + } +} diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/NotificationPort.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/NotificationPort.java new file mode 100644 index 00000000..47d4734f --- /dev/null +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/notification/NotificationPort.java @@ -0,0 +1,12 @@ +package com.northwind.scheduling.notification; + +/** + * Outbound candidate notifications (MBA-3831). The outbox relay calls it once per CandidateCapacityImpactNotified + * event and may call it again for the same event after a retry, so implementations must be idempotent on + * {@link CandidateCapacityImpactNotified#eventId()}. + */ +public interface NotificationPort { + + /** @return true if the notification was sent now, false if this eventId was already handled */ + boolean notify(CandidateCapacityImpactNotified notification); +} 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 b05773cb..3283f29f 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 (V2__outbox.sql, V3__waitlist_offers.sql) lists the same names. */ +/** Outbox event types (MBA-3823); ck_outbox_event_type (V2__outbox.sql, V3__waitlist_offers.sql, V4) lists the same names. */ public enum OutboxEventType { BookingCreated("Booking", "BOOK"), BookingCancelled("Booking", "CANCEL"), @@ -19,7 +19,9 @@ public enum OutboxEventType { /** 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"); + SeatOfferWithdrawn("Booking", "WAITLIST_OFFER_WITHDRAW"), + /** MBA-3831: one per affected candidate of a capacity change; delivered to NotificationPort, not to legacy */ + CandidateCapacityImpactNotified("Booking", "CAPACITY_NOTIFY"); private final String aggregateType; private final String auditAction; @@ -33,6 +35,11 @@ public String aggregateType() { return aggregateType; } + /** False for notification events: the relay delivers them to NotificationPort and writes nothing to legacy. */ + public boolean projectsToLegacy() { + return this != CandidateCapacityImpactNotified; + } + /** dbo.AuditLog.Action the relay writes for this event */ public String auditAction() { return auditAction; diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxPayload.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxPayload.java index 567ecb21..3f16feab 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxPayload.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxPayload.java @@ -2,14 +2,24 @@ import java.util.List; -/** JSON body of outbox_event.payload: resulting state, not a delta (timestamps are ISO local date-times). */ -public record OutboxPayload(String type, String detail, List bookings, List sessions) { +import com.northwind.scheduling.notification.CandidateCapacityImpactNotified; + +/** + * JSON body of outbox_event.payload: resulting state, not a delta (timestamps are ISO local date-times). + * {@code notification} is only set on CandidateCapacityImpactNotified events (MBA-3831, docs/events.md). + */ +public record OutboxPayload(String type, String detail, List bookings, List sessions, + CandidateCapacityImpactNotified notification) { public OutboxPayload { bookings = bookings == null ? List.of() : List.copyOf(bookings); sessions = sessions == null ? List.of() : List.copyOf(sessions); } + public OutboxPayload(String type, String detail, List bookings, List sessions) { + this(type, detail, bookings, sessions, null); + } + /** waitlistPosition null = no waitlist row for this booking */ public record BookingState(int bookingId, int sessionId, int candidateId, String status, String accommodationCode, String channel, String externalRef, String bookedAt, String cancelledAt, diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxRepository.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxRepository.java index 735b34dd..34f96f90 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxRepository.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/outbox/OutboxRepository.java @@ -16,6 +16,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.northwind.scheduling.notification.CandidateCapacityImpactNotified; /** * Transactional outbox (MBA-3823, V2__outbox.sql). {@link #append} runs inside the caller's transaction on the @@ -52,6 +53,26 @@ public long append(OutboxEventType type, int aggregateId, Collection bo return seq == null ? -1 : seq; } + /** + * MBA-3831: one CandidateCapacityImpactNotified event; the outbox event_id is the notification's eventId, so the + * NotificationPort can deduplicate relay retries on it. + */ + public long appendNotification(CandidateCapacityImpactNotified n, String actor) { + OutboxEventType type = OutboxEventType.CandidateCapacityImpactNotified; + OutboxPayload payload = new OutboxPayload(type.name(), n.impact() + " " + n.previousStatus() + "->" + n.newStatus(), + List.of(), List.of(), n); + String body; + try { + body = json.writeValueAsString(payload); + } catch (JsonProcessingException e) { + throw new IllegalStateException("outbox payload for " + type, e); + } + Long seq = jdbc.queryForObject("SET NOCOUNT ON; INSERT INTO outbox_event (event_id, event_type, aggregate_type, " + + "aggregate_id, payload, actor) VALUES (?, ?, ?, ?, ?, ?); SELECT CAST(SCOPE_IDENTITY() AS BIGINT);", + Long.class, n.eventId().toString(), type.name(), type.aggregateType(), n.bookingId(), body, actor); + return seq == null ? -1 : seq; + } + /** All sessions in one event: SeatsAvailable for every session as scheduling-service derives it. */ public long appendInventoryBaseline(String actor) { List ids = jdbc.queryForList("SELECT session_id FROM exam_session ORDER BY session_id", Integer.class); 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 f45aad08..582f2cfa 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 @@ -13,6 +13,7 @@ import com.northwind.scheduling.domain.BookingStatus; import com.northwind.scheduling.domain.CapacityChange; +import com.northwind.scheduling.domain.CapacityImpact; import com.northwind.scheduling.domain.ExamAttempt; import com.northwind.scheduling.domain.SessionStatus; @@ -215,6 +216,16 @@ public List bookedSeats(int sessionId) { .list(); } + /** MBA-3831: every booking of the session with its candidate and status (CapacityImpact before/after). */ + public List bookingStates(int sessionId) { + return db.sql("SELECT b.booking_id, c.candidate_number, b.status FROM booking b " + + "JOIN candidate_snapshot c ON c.candidate_id = b.candidate_id WHERE b.session_id = ?") + .param(sessionId) + .query((rs, i) -> new CapacityImpact.BookingState(rs.getInt(1), rs.getString(2), + BookingStatus.valueOf(rs.getString(3)))) + .list(); + } + public int insertCapacityChange(CapacityChange.Plan plan, String reason, String actor, LocalDateTime now) { return db.sql("INSERT INTO capacity_change (session_id, old_capacity, new_capacity, old_accommodation_capacity, " + "new_accommodation_capacity, demoted_bookings, reason, changed_by, changed_at) " diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/relay/LegacyRelay.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/relay/LegacyRelay.java index c3bf3669..fa220ed2 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/relay/LegacyRelay.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/relay/LegacyRelay.java @@ -36,8 +36,11 @@ public LegacyRelay(JdbcTemplate legacyJdbc) { this.tx = new TransactionTemplate(new DataSourceTransactionManager(legacyJdbc.getDataSource())); } - /** @return true if applied now, false if the checkpoint shows it was applied before */ + /** @return true if applied now, false if the checkpoint shows it was applied before or it has no legacy projection */ public boolean apply(OutboxEvent e) { + if (!e.type().projectsToLegacy()) { + return false; + } Boolean applied = tx.execute(status -> { jdbc.execute("EXEC sp_set_session_context @key = N'writer', @value = N'" + WRITER + "'"); Integer done = jdbc.queryForObject("SELECT COUNT(*) FROM dbo.RelayCheckpoint WITH (UPDLOCK, HOLDLOCK) " diff --git a/services/scheduling-service/src/main/java/com/northwind/scheduling/relay/RelayWorker.java b/services/scheduling-service/src/main/java/com/northwind/scheduling/relay/RelayWorker.java index 692f149c..d7309761 100644 --- a/services/scheduling-service/src/main/java/com/northwind/scheduling/relay/RelayWorker.java +++ b/services/scheduling-service/src/main/java/com/northwind/scheduling/relay/RelayWorker.java @@ -17,13 +17,16 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; +import com.northwind.scheduling.notification.NotificationDelivery; import com.northwind.scheduling.outbox.OutboxEvent; import com.northwind.scheduling.outbox.OutboxRepository; /** * Polls outbox_event in event_seq order and hands each pending event to {@link LegacyRelay} (MBA-3823). An event is * marked relayed in Scheduling only after its legacy transaction committed; a crash in between leaves it pending and - * the replay is a checkpointed no-op. A failing event stops the batch so later events never overtake it. + * the replay is a checkpointed no-op. CandidateCapacityImpactNotified events are delivered to the + * NotificationPort instead (MBA-3831); a retried delivery is deduplicated there on the event id. + * A failing event stops the batch so later events never overtake it. */ @Component @ConditionalOnProperty(name = "scheduling.relay.enabled", havingValue = "true") @@ -33,17 +36,19 @@ public class RelayWorker { private final OutboxRepository outbox; private final LegacyRelay relay; + private final NotificationDelivery notifications; private final int batchSize; private final AtomicLong applied = new AtomicLong(); private final AtomicLong skipped = new AtomicLong(); private final AtomicLong pending = new AtomicLong(); private final AtomicLong lagMillis = new AtomicLong(); - public RelayWorker(OutboxRepository outbox, LegacyRelay relay, + public RelayWorker(OutboxRepository outbox, LegacyRelay relay, NotificationDelivery notifications, @Value("${scheduling.relay.batch-size:200}") int batchSize, ObjectProvider meters) { this.outbox = outbox; this.relay = relay; + this.notifications = notifications; this.batchSize = batchSize; meters.ifAvailable(r -> { Gauge.builder("scheduling.outbox.pending", pending, AtomicLong::get) @@ -68,7 +73,7 @@ public synchronized int relayPending() { int processed = 0; for (OutboxEvent e : outbox.pending(batchSize)) { try { - if (relay.apply(e)) { + if (e.type().projectsToLegacy() ? relay.apply(e) : notifications.deliver(e)) { applied.incrementAndGet(); } else { skipped.incrementAndGet(); 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 3a308f4c..04e2ecb0 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 @@ -9,6 +9,9 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @@ -19,12 +22,14 @@ import com.northwind.scheduling.domain.BookingRules; import com.northwind.scheduling.domain.BookingStatus; import com.northwind.scheduling.domain.CapacityChange; +import com.northwind.scheduling.domain.CapacityImpact; 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; +import com.northwind.scheduling.notification.CandidateCapacityImpactNotified; import com.northwind.scheduling.persistence.Rows; import com.northwind.scheduling.persistence.SchedulingRepository; @@ -39,7 +44,9 @@ public record BookCommand(Integer sessionId, String candidateNumber, String acco public record BookingOutcome(int bookingId, BookingStatus status, Integer waitlistPosition, int sessionId) { } - public record CapacityOutcome(CapacityChange.Plan plan, Rows.Session session) { + /** notified = CandidateCapacityImpactNotified events written for this change (MBA-3831) */ + public record CapacityOutcome(CapacityChange.Plan plan, Rows.Session session, + List notified) { } private final SchedulingRepository repo; @@ -90,6 +97,10 @@ public List sessions(String centerCode, String examCode, LocalDate return repo.sessions(centerCode, examCode, from, to); } + private Set pendingOfferBookings(int sessionId) { + return repo.pendingOffers(sessionId).stream().map(Rows.Offer::bookingId).collect(Collectors.toUnmodifiableSet()); + } + public Rows.Session session(int sessionId) { return repo.session(sessionId).orElseThrow( () -> new SchedulingException(ErrorCode.SESSION_NOT_FOUND, "Session " + sessionId + " not found")); @@ -356,6 +367,8 @@ public CapacityOutcome changeCapacity(int sessionId, Integer newCapacity, String throw new SchedulingException(ErrorCode.SESSION_NOT_FOUND, "Session " + sessionId + " not found"); } Rows.Session s = session(sessionId); + List before = repo.bookingStates(sessionId); + Set offeredBefore = pendingOfferBookings(sessionId); CapacityChange.Plan plan = CapacityChange.plan(sessionId, newCapacity, s.seats(), repo.bookedSeats(sessionId), repo.maxWaitlistPosition(sessionId), floorPolicy); LocalDateTime now = now(); @@ -371,6 +384,13 @@ public CapacityOutcome changeCapacity(int sessionId, Integer newCapacity, String + (reason == null ? "" : " reason=" + reason)); offers.withdrawExcess(sessionId, "capacity reduced to " + plan.newCapacity()); offers.offerFreedSeats(sessionId, "capacity=" + plan.newCapacity()); - return new CapacityOutcome(plan, session(sessionId)); + List affected = CapacityImpact.affected(plan.oldCapacity(), plan.newCapacity(), before, + repo.bookingStates(sessionId), offeredBefore, pendingOfferBookings(sessionId)); + for (CapacityImpact.Affected a : affected) { + outbox.appendNotification(new CandidateCapacityImpactNotified(UUID.randomUUID(), sessionId, s.centerCode(), + s.examCode(), s.startsAt(), plan.oldCapacity(), plan.newCapacity(), a.candidateNumber(), + a.bookingId(), a.previousStatus().name(), a.newStatus().name(), a.kind()), actor); + } + return new CapacityOutcome(plan, session(sessionId), affected); } } 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 387ae350..6ee021f8 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 @@ -96,7 +96,9 @@ static WaitlistEntryDto of(Rows.WaitlistEntry w) { } } - public record CapacityResultDto(SessionDto session, int oldCapacity, int newCapacity, List demotedBookingIds) { + /** notifiedCandidates: CandidateCapacityImpactNotified events emitted for this change (MBA-3831) */ + public record CapacityResultDto(SessionDto session, int oldCapacity, int newCapacity, List demotedBookingIds, + int notifiedCandidates) { } public record CapacityChangeDto(int id, int oldCapacity, int newCapacity, int demotedBookings, String reason, 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 a15933bc..d1912933 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 @@ -96,7 +96,7 @@ public CapacityResultDto changeCapacity(@PathVariable int sessionId, @RequestBod SchedulingService.CapacityOutcome out = service.changeCapacity(sessionId, req == null ? null : req.capacity(), req == null ? null : req.reason()); return new CapacityResultDto(SessionDto.of(out.session()), out.plan().oldCapacity(), out.plan().newCapacity(), - out.plan().demotions().stream().map(CapacityChange.Demotion::bookingId).toList()); + out.plan().demotions().stream().map(CapacityChange.Demotion::bookingId).toList(), out.notified().size()); } @PostMapping("/bookings") diff --git a/services/scheduling-service/src/main/resources/db/migration/V4__candidate_notification_event.sql b/services/scheduling-service/src/main/resources/db/migration/V4__candidate_notification_event.sql new file mode 100644 index 00000000..cd7d50fe --- /dev/null +++ b/services/scheduling-service/src/main/resources/db/migration/V4__candidate_notification_event.sql @@ -0,0 +1,15 @@ +-- MBA-3831: outbox event CandidateCapacityImpactNotified (one per candidate affected by a capacity change, +-- docs/events.md). The relay hands it to NotificationPort instead of AssessmentDelivery (legacy has no notifications, +-- MR-04). The type is appended to whatever ck_outbox_event_type allows at this point, so other migrations that +-- extend the list (e.g. V3) keep their values. +DECLARE @def NVARCHAR(MAX) = (SELECT definition FROM sys.check_constraints + WHERE name = 'ck_outbox_event_type' AND parent_object_id = OBJECT_ID('outbox_event')); +IF @def IS NULL + THROW 50000, 'ck_outbox_event_type not found', 1; +IF CHARINDEX('''CandidateCapacityImpactNotified''', @def) = 0 +BEGIN + ALTER TABLE outbox_event DROP CONSTRAINT ck_outbox_event_type; + DECLARE @sql NVARCHAR(MAX) = N'ALTER TABLE outbox_event ADD CONSTRAINT ck_outbox_event_type CHECK (' + + @def + N' OR [event_type] = ''CandidateCapacityImpactNotified'')'; + EXEC sp_executesql @sql; +END diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/domain/CapacityImpactTest.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/domain/CapacityImpactTest.java new file mode 100644 index 00000000..0ebece40 --- /dev/null +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/domain/CapacityImpactTest.java @@ -0,0 +1,109 @@ +package com.northwind.scheduling.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.IntStream; + +import org.junit.jupiter.api.Test; + +import com.northwind.scheduling.domain.CapacityImpact.Affected; +import com.northwind.scheduling.domain.CapacityImpact.BookingState; +import com.northwind.scheduling.domain.CapacityImpact.Kind; + +class CapacityImpactTest { + + static List booked(int n) { + return IntStream.rangeClosed(1, n).mapToObj(i -> new BookingState(i, String.format("NW%08d", 900 + i), + BookingStatus.BOOKED)).toList(); + } + + static List with(List rows, int bookingId, BookingStatus status) { + List out = new ArrayList<>(); + for (BookingState r : rows) { + out.add(r.bookingId() == bookingId ? new BookingState(r.bookingId(), r.candidateNumber(), status) : r); + } + return out; + } + + @Test + void reductionWithTwoDemotionsGivesTwoStatusChangesAndEightSeatConfirmations() { + List before = booked(10); + List after = with(with(before, 9, BookingStatus.WAITLISTED), 10, BookingStatus.WAITLISTED); + + List affected = CapacityImpact.affected(20, 8, before, after); + + assertThat(affected).hasSize(10); + assertThat(affected).filteredOn(a -> a.kind() == Kind.STATUS_CHANGED) + .containsExactly(new Affected(9, "NW00000909", BookingStatus.BOOKED, BookingStatus.WAITLISTED, Kind.STATUS_CHANGED), + new Affected(10, "NW00000910", BookingStatus.BOOKED, BookingStatus.WAITLISTED, Kind.STATUS_CHANGED)); + assertThat(affected).filteredOn(a -> a.kind() == Kind.SEAT_CONFIRMED).hasSize(8) + .allSatisfy(a -> { + assertThat(a.previousStatus()).isEqualTo(BookingStatus.BOOKED); + assertThat(a.newStatus()).isEqualTo(BookingStatus.BOOKED); + assertThat(a.bookingId()).isBetween(1, 8); + }); + } + + @Test + void reductionWithoutDemotionsConfirmsEveryRemainingBookedSeatOnly() { + List before = new ArrayList<>(booked(3)); + before.add(new BookingState(4, "NW00000904", BookingStatus.WAITLISTED)); + before.add(new BookingState(5, "NW00000905", BookingStatus.CANCELLED)); + before.add(new BookingState(6, "NW00000906", BookingStatus.ATTENDED)); + + List affected = CapacityImpact.affected(20, 10, before, before); + + assertThat(affected).extracting(Affected::bookingId).containsExactly(1, 2, 3); + assertThat(affected).extracting(Affected::kind).containsOnly(Kind.SEAT_CONFIRMED); + } + + @Test + void increaseWithoutStatusChangesNotifiesNobody() { + List before = with(booked(5), 5, BookingStatus.WAITLISTED); + assertThat(CapacityImpact.affected(8, 12, before, before)).isEmpty(); + assertThat(CapacityImpact.affected(8, 8, before, before)).isEmpty(); + } + + @Test + void increaseWithAStatusChangeNotifiesThatCandidate() { + // e.g. an A4 waitlist offer made in the same transaction: WAITLISTED -> BOOKED + List before = with(booked(5), 5, BookingStatus.WAITLISTED); + List after = with(before, 5, BookingStatus.BOOKED); + + assertThat(CapacityImpact.affected(4, 5, before, after)).containsExactly( + new Affected(5, "NW00000905", BookingStatus.WAITLISTED, BookingStatus.BOOKED, Kind.STATUS_CHANGED)); + } + + @Test + void increaseThatMakesSeatOffersNotifiesTheOfferedWaitlistedCandidatesOnly() { + List state = with(with(booked(5), 4, BookingStatus.WAITLISTED), 5, BookingStatus.WAITLISTED); + + assertThat(CapacityImpact.affected(3, 5, state, state, Set.of(), Set.of(4, 5))) + .containsExactly(new Affected(4, "NW00000904", BookingStatus.WAITLISTED, BookingStatus.WAITLISTED, Kind.SEAT_OFFERED), + new Affected(5, "NW00000905", BookingStatus.WAITLISTED, BookingStatus.WAITLISTED, Kind.SEAT_OFFERED)); + // an offer that was already pending is not news + assertThat(CapacityImpact.affected(3, 4, state, state, Set.of(4), Set.of(4))).isEmpty(); + } + + @Test + void reductionThatWithdrawsOffersNotifiesWithdrawalsDemotionsAndConfirmations() { + List before = with(booked(4), 4, BookingStatus.WAITLISTED); + List after = with(before, 3, BookingStatus.WAITLISTED); + + assertThat(CapacityImpact.affected(4, 2, before, after, Set.of(4), Set.of())) + .extracting(Affected::bookingId, Affected::kind) + .containsExactly(org.assertj.core.groups.Tuple.tuple(1, Kind.SEAT_CONFIRMED), + org.assertj.core.groups.Tuple.tuple(2, Kind.SEAT_CONFIRMED), + org.assertj.core.groups.Tuple.tuple(3, Kind.STATUS_CHANGED), + org.assertj.core.groups.Tuple.tuple(4, Kind.OFFER_WITHDRAWN)); + } + + @Test + void bookingsUnknownBeforeTheChangeAreIgnored() { + List after = booked(2); + assertThat(CapacityImpact.affected(5, 3, after.subList(0, 1), after)).extracting(Affected::bookingId).containsExactly(1); + } +} diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/notification/CandidateCapacityImpactSchemaTest.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/notification/CandidateCapacityImpactSchemaTest.java new file mode 100644 index 00000000..b558f864 --- /dev/null +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/notification/CandidateCapacityImpactSchemaTest.java @@ -0,0 +1,116 @@ +package com.northwind.scheduling.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.UUID; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.networknt.schema.JsonSchema; +import com.networknt.schema.JsonSchemaFactory; +import com.networknt.schema.SchemaValidatorsConfig; +import com.networknt.schema.SpecVersion; +import com.networknt.schema.ValidationMessage; +import com.northwind.scheduling.domain.BookingStatus; +import com.northwind.scheduling.domain.CapacityImpact; +import com.northwind.scheduling.outbox.OutboxPayload; + +/** MBA-3831: docs/schemas/candidate-capacity-impact-notified.schema.json matches the emitted event and docs/events.md. */ +public class CandidateCapacityImpactSchemaTest { + + public static final Path SCHEMA = Path.of("docs/schemas/candidate-capacity-impact-notified.schema.json"); + static final Path DOC = Path.of("docs/events.md"); + /** spring.jackson settings of the service (application.yml): ISO date-times, nulls included */ + static final ObjectMapper JSON = new ObjectMapper().registerModule(new JavaTimeModule()) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + + public static JsonSchema schema() throws IOException { + SchemaValidatorsConfig config = SchemaValidatorsConfig.builder().formatAssertionsEnabled(true).build(); + return JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012).getSchema(Files.readString(SCHEMA), config); + } + + static CandidateCapacityImpactNotified sample() { + return new CandidateCapacityImpactNotified(UUID.randomUUID(), 154, "SFO01", "MHL-RN1", + LocalDateTime.of(2026, 11, 12, 13, 30), 20, 8, "NW00000909", 9, "BOOKED", "WAITLISTED", + CapacityImpact.Kind.STATUS_CHANGED); + } + + static ObjectNode sampleJson() { + return JSON.valueToTree(sample()); + } + + @Test + void serializedEventMatchesTheSchema() throws IOException { + Set errors = schema().validate(sampleJson()); + assertThat(errors).isEmpty(); + } + + @Test + void notificationInsideTheOutboxPayloadMatchesTheSchemaAndRoundTrips() throws IOException { + CandidateCapacityImpactNotified n = sample(); + String body = JSON.writeValueAsString(new OutboxPayload("CandidateCapacityImpactNotified", "d", List.of(), List.of(), n)); + + JsonNode tree = JSON.readTree(body); + assertThat(schema().validate(tree.get("notification"))).isEmpty(); + assertThat(JSON.readValue(body, OutboxPayload.class).notification()).isEqualTo(n); + } + + @Test + void schemaPropertiesAreExactlyTheRecordComponentsAndAllRequired() throws IOException { + JsonNode schema = JSON.readTree(Files.readString(SCHEMA)); + Set props = new TreeSet<>(); + schema.get("properties").fieldNames().forEachRemaining(props::add); + Set required = new TreeSet<>(); + schema.get("required").forEach(r -> required.add(r.asText())); + Set components = new TreeSet<>(Arrays.stream(CandidateCapacityImpactNotified.class.getRecordComponents()) + .map(c -> c.getName()).toList()); + + assertThat(props).isEqualTo(components).isEqualTo(required); + assertThat(props).containsAll(List.of("eventId", "sessionId", "centerCode", "examCode", "startsAt", "oldCapacity", + "newCapacity", "candidateNumber", "bookingId", "previousStatus", "newStatus")); + List statuses = new ArrayList<>(); + schema.at("/$defs/bookingStatus/enum").forEach(s -> statuses.add(s.asText())); + assertThat(statuses).containsExactlyInAnyOrderElementsOf(Arrays.stream(BookingStatus.values()).map(Enum::name).toList()); + List impacts = new ArrayList<>(); + schema.at("/properties/impact/enum").forEach(s -> impacts.add(s.asText())); + assertThat(impacts).containsExactlyInAnyOrderElementsOf(Arrays.stream(CapacityImpact.Kind.values()).map(Enum::name).toList()); + } + + @Test + void invalidEventsAreRejected() throws IOException { + JsonSchema schema = schema(); + assertThat(schema.validate(sampleJson().without("candidateNumber"))).isNotEmpty(); + assertThat(schema.validate(sampleJson().put("newStatus", "DEMOTED"))).isNotEmpty(); + assertThat(schema.validate(sampleJson().put("eventId", "not-a-uuid"))).isNotEmpty(); + assertThat(schema.validate(sampleJson().put("startsAt", "2026-11-12T13:30:00Z"))).isNotEmpty(); + assertThat(schema.validate(sampleJson().put("candidateNumber", "X1"))).isNotEmpty(); + assertThat(schema.validate(sampleJson().put("extra", 1))).isNotEmpty(); + assertThat(schema.validate(sampleJson().put("newCapacity", -1))).isNotEmpty(); + } + + @Test + void eventsDocDocumentsEveryFieldAndLinksTheSchema() throws IOException { + String doc = Files.readString(DOC); + assertThat(doc).contains("## CandidateCapacityImpactNotified", "schemas/candidate-capacity-impact-notified.schema.json"); + for (var c : CandidateCapacityImpactNotified.class.getRecordComponents()) { + assertThat(doc).as("docs/events.md documents " + c.getName()).contains("`" + c.getName() + "`"); + } + int start = doc.indexOf("```json") + "```json".length(); + JsonNode example = JSON.readTree(doc.substring(start, doc.indexOf("```", start))); + assertThat(schema().validate(example)).as("example in docs/events.md").isEmpty(); + } +} diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/notification/CapacityImpactNotificationIT.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/notification/CapacityImpactNotificationIT.java new file mode 100644 index 00000000..fb1cd133 --- /dev/null +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/notification/CapacityImpactNotificationIT.java @@ -0,0 +1,225 @@ +package com.northwind.scheduling.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +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.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.jdbc.core.JdbcTemplate; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.northwind.scheduling.SqlServerTestBase; +import com.northwind.scheduling.importer.SnapshotImporter; +import com.northwind.scheduling.outbox.OutboxEvent; +import com.northwind.scheduling.outbox.OutboxEventType; +import com.northwind.scheduling.outbox.OutboxRepository; + +/** + * MBA-3831 acceptance criteria on Testcontainers SQL Server: PUT capacity -> one CandidateCapacityImpactNotified outbox + * row per affected candidate (same transaction as CapacityChanged) -> NotificationDelivery (what the relay calls) -> + * stub, readable at GET /internal/notifications. The relay itself is covered by RelayIT. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Import(SqlServerTestBase.FixtureLegacy.class) +class CapacityImpactNotificationIT extends SqlServerTestBase { + + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() { + }; + private static final ParameterizedTypeReference>> LIST = new ParameterizedTypeReference<>() { + }; + + @Autowired TestRestTemplate http; + @Autowired SnapshotImporter importer; + @Autowired JdbcTemplate jdbc; + @Autowired OutboxRepository outbox; + @Autowired NotificationDelivery delivery; + @Autowired ObjectMapper json; + + long seqBefore; + + @BeforeEach + void reset() { + importer.run(SnapshotImporter.Mode.RESET); + jdbc.update("UPDATE outbox_event SET relayed_at = SYSUTCDATETIME() WHERE relayed_at IS NULL"); + Long max = jdbc.queryForObject("SELECT MAX(event_seq) FROM outbox_event", Long.class); + seqBefore = max == null ? 0 : max; + } + + @Test + @SuppressWarnings("unchecked") + void reductionOnTenBookedGivesTwoStatusChangedAndEightSeatConfirmedNotifications() throws Exception { + // fixture session 154: capacity 20, bookings 1-9 BOOKED for NW00000901..909; book a 10th + ResponseEntity> tenth = http.exchange("/api/v2/bookings", HttpMethod.POST, + new HttpEntity<>(Map.of("sessionId", 154, "candidateNumber", "NW00000920")), MAP); + assertThat(tenth.getStatusCode()).isEqualTo(HttpStatus.CREATED); + int tenthId = (Integer) tenth.getBody().get("bookingId"); + seqBefore = jdbc.queryForObject("SELECT MAX(event_seq) FROM outbox_event", Long.class); + + Map r = capacity(154, 8); + assertThat(r).containsEntry("oldCapacity", 20).containsEntry("newCapacity", 8).containsEntry("notifiedCandidates", 10); + assertThat((List) r.get("demotedBookingIds")).containsExactlyInAnyOrder(9, tenthId); + + List events = newEvents(); + assertThat(events.get(0).type()).isEqualTo(OutboxEventType.CapacityChanged); + List sent = events.stream() + .filter(e -> e.type() == OutboxEventType.CandidateCapacityImpactNotified) + .map(e -> e.payload().notification()).toList(); + assertThat(sent).hasSize(10).allSatisfy(n -> { + assertThat(n.sessionId()).isEqualTo(154); + assertThat(n.centerCode()).isEqualTo("SFO01"); + assertThat(n.examCode()).isEqualTo("MHL-RN1"); + assertThat(n.startsAt()).isEqualTo(java.time.LocalDateTime.of(2026, 11, 12, 13, 30)); + assertThat(n.oldCapacity()).isEqualTo(20); + assertThat(n.newCapacity()).isEqualTo(8); + }); + assertThat(sent).filteredOn(n -> n.impact() == com.northwind.scheduling.domain.CapacityImpact.Kind.STATUS_CHANGED) + .extracting(CandidateCapacityImpactNotified::candidateNumber, CandidateCapacityImpactNotified::bookingId, + CandidateCapacityImpactNotified::previousStatus, CandidateCapacityImpactNotified::newStatus) + .containsExactlyInAnyOrder(org.assertj.core.groups.Tuple.tuple("NW00000909", 9, "BOOKED", "WAITLISTED"), + org.assertj.core.groups.Tuple.tuple("NW00000920", tenthId, "BOOKED", "WAITLISTED")); + assertThat(sent).filteredOn(n -> n.impact() == com.northwind.scheduling.domain.CapacityImpact.Kind.SEAT_CONFIRMED) + .hasSize(8).allSatisfy(n -> assertThat(n.previousStatus() + "->" + n.newStatus()).isEqualTo("BOOKED->BOOKED")) + .extracting(CandidateCapacityImpactNotified::candidateNumber) + .containsExactlyInAnyOrder("NW00000901", "NW00000902", "NW00000903", "NW00000904", "NW00000905", + "NW00000906", "NW00000907", "NW00000908"); + + // stored payloads conform to docs/schemas and carry the outbox event id + var schema = CandidateCapacityImpactSchemaTest.schema(); + for (Map row : jdbc.queryForList("SELECT event_id, payload FROM outbox_event WHERE event_seq > ? " + + "AND event_type = 'CandidateCapacityImpactNotified'", seqBefore)) { + JsonNode n = json.readTree((String) row.get("payload")).get("notification"); + assertThat(schema.validate(n)).isEmpty(); + assertThat(n.get("eventId").asText()).isEqualToIgnoringCase(row.get("event_id").toString()); + } + + deliverNewEventsTwice(); + List> demoted = notifications("NW00000909"); + assertThat(demoted).hasSize(1); + assertThat(demoted.get(0)).containsEntry("previousStatus", "BOOKED").containsEntry("newStatus", "WAITLISTED") + .containsEntry("impact", "STATUS_CHANGED").containsEntry("bookingId", 9).containsEntry("centerCode", "SFO01") + .containsEntry("startsAt", "2026-11-12T13:30:00"); + assertThat(notifications("NW00000901")).singleElement().satisfies(n -> assertThat(n) + .containsEntry("impact", "SEAT_CONFIRMED").containsEntry("newStatus", "BOOKED")); + } + + @Test + void increaseWithoutStatusChangesEmitsNoNotification() { + Map r = capacity(154, 25); + assertThat(r).containsEntry("notifiedCandidates", 0); + assertThat(newEvents()).extracting(OutboxEvent::type).containsExactly(OutboxEventType.CapacityChanged); + } + + @Test + void capacityChangesNotifyOfferedAndWithdrawnCandidatesInTheSameTransactionAsTheOffers() { + // fixture session 163 (A4): capacity 3, BOOKED 10, 11, 12; WAITLISTED 13 at position 1; add a second waitlister + int w14 = (Integer) http.exchange("/api/v2/bookings", HttpMethod.POST, + new HttpEntity<>(Map.of("sessionId", 163, "candidateNumber", "NW00000914")), MAP).getBody().get("bookingId"); + seqBefore = jdbc.queryForObject("SELECT MAX(event_seq) FROM outbox_event", Long.class); + + Map up = capacity(163, 5); + assertThat(up).containsEntry("notifiedCandidates", 2); + List upEvents = newEvents(); + assertThat(upEvents).extracting(e -> e.type().name() + ":" + e.aggregateId()).containsExactly( + "CapacityChanged:163", "SeatOffered:13", "SeatOffered:" + w14, + "CandidateCapacityImpactNotified:13", "CandidateCapacityImpactNotified:" + w14); + assertThat(upEvents).filteredOn(e -> e.type() == OutboxEventType.CandidateCapacityImpactNotified) + .extracting(e -> e.payload().notification()).allSatisfy(n -> { + assertThat(n.impact()).isEqualTo(com.northwind.scheduling.domain.CapacityImpact.Kind.SEAT_OFFERED); + assertThat(n.previousStatus() + "->" + n.newStatus()).isEqualTo("WAITLISTED->WAITLISTED"); + assertThat(CandidateCapacityImpactSchemaTest.schema().validate(json.valueToTree(n))).isEmpty(); + }); + assertThat(jdbc.queryForList("SELECT booking_id FROM seat_offer WHERE session_id = 163 AND status = 'PENDING'", + Integer.class)).containsExactlyInAnyOrder(13, w14); + + seqBefore = jdbc.queryForObject("SELECT MAX(event_seq) FROM outbox_event", Long.class); + Map down = capacity(163, 2); + @SuppressWarnings("unchecked") + List demoted = (List) down.get("demotedBookingIds"); + assertThat(demoted).isNotEmpty(); + List stillBooked = jdbc.queryForList("SELECT booking_id FROM booking WHERE session_id = 163 AND status = 'BOOKED'", + Integer.class); + List downEvents = newEvents(); + assertThat(downEvents).extracting(e -> e.type().name()).first().isEqualTo("CapacityChanged"); + assertThat(downEvents).filteredOn(e -> e.type() == OutboxEventType.SeatOfferWithdrawn) + .extracting(OutboxEvent::aggregateId).containsExactlyInAnyOrder(13, w14); + List sent = downEvents.stream() + .filter(e -> e.type() == OutboxEventType.CandidateCapacityImpactNotified) + .map(e -> e.payload().notification()).toList(); + assertThat(down).containsEntry("notifiedCandidates", sent.size()); + assertThat(sent).filteredOn(n -> n.impact() == com.northwind.scheduling.domain.CapacityImpact.Kind.STATUS_CHANGED) + .allSatisfy(n -> assertThat(n.previousStatus() + "->" + n.newStatus()).isEqualTo("BOOKED->WAITLISTED")) + .extracting(CandidateCapacityImpactNotified::bookingId).containsExactlyInAnyOrderElementsOf(demoted); + assertThat(sent).filteredOn(n -> n.impact() == com.northwind.scheduling.domain.CapacityImpact.Kind.OFFER_WITHDRAWN) + .extracting(CandidateCapacityImpactNotified::bookingId).containsExactlyInAnyOrder(13, w14); + assertThat(sent).filteredOn(n -> n.impact() == com.northwind.scheduling.domain.CapacityImpact.Kind.SEAT_CONFIRMED) + .extracting(CandidateCapacityImpactNotified::bookingId).containsExactlyInAnyOrderElementsOf(stillBooked); + assertThat(sent).hasSize(demoted.size() + 2 + stillBooked.size()); + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM seat_offer WHERE session_id = 163 AND status = 'PENDING'", + Integer.class)).isZero(); + } + + @Test + void sameEventDeliveredTwiceIsRecordedOnce() { + capacity(154, 7); // 9 booked: bookings 8 and 9 demoted, 1-7 confirmed + List notifications = newEvents().stream() + .filter(e -> e.type() == OutboxEventType.CandidateCapacityImpactNotified).toList(); + assertThat(notifications).hasSize(9); + + OutboxEvent eight = notifications.stream().filter(e -> e.payload().notification().bookingId() == 8).findFirst() + .orElseThrow(); + int before = notifications("NW00000908").size(); + assertThat(delivery.deliver(eight)).isTrue(); + assertThat(delivery.deliver(eight)).isFalse(); // relay retry of the same event_id + List> recorded = notifications("NW00000908"); + assertThat(recorded).hasSize(before + 1); + assertThat(recorded.get(recorded.size() - 1)).containsEntry("eventId", eight.eventId().toString()) + .containsEntry("newStatus", "WAITLISTED"); + } + + @Test + void notificationsEndpointIsInternalOnlyAndFiltersByCandidate() { + ResponseEntity>> unknown = http.exchange("/internal/notifications?candidateNumber=NW09999999", + HttpMethod.GET, null, LIST); + assertThat(unknown.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(unknown.getBody()).isEmpty(); + assertThat(http.getForEntity("/internal/notifications", String.class).getStatusCode().value()).isEqualTo(400); + assertThat(http.getForEntity("/internal/notifications?candidateNumber=+", String.class).getStatusCode().value()) + .isEqualTo(400); + assertThat(http.getForObject("/v3/api-docs", String.class)).doesNotContain("/internal/notifications"); + } + + private Map capacity(int sessionId, int capacity) { + ResponseEntity> r = http.exchange("/api/v2/sessions/" + sessionId + "/capacity", HttpMethod.PUT, + new HttpEntity<>(Map.of("capacity", capacity, "reason", "MBA-3831 IT")), MAP); + assertThat(r.getStatusCode()).isEqualTo(HttpStatus.OK); + return r.getBody(); + } + + private List newEvents() { + return outbox.pending(1000).stream().filter(e -> e.seq() > seqBefore).toList(); + } + + private void deliverNewEventsTwice() { + for (int i = 0; i < 2; i++) { + newEvents().stream().filter(e -> e.type() == OutboxEventType.CandidateCapacityImpactNotified) + .forEach(delivery::deliver); + } + } + + private List> notifications(String candidateNumber) { + return http.exchange("/internal/notifications?candidateNumber=" + candidateNumber, HttpMethod.GET, null, LIST) + .getBody(); + } +} diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/notification/LoggingNotificationAdapterTest.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/notification/LoggingNotificationAdapterTest.java new file mode 100644 index 00000000..ef6115b7 --- /dev/null +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/notification/LoggingNotificationAdapterTest.java @@ -0,0 +1,58 @@ +package com.northwind.scheduling.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDateTime; +import java.util.UUID; + +import org.junit.jupiter.api.Test; + +import com.northwind.scheduling.domain.CapacityImpact; + +class LoggingNotificationAdapterTest { + + static CandidateCapacityImpactNotified event(UUID id, String candidate, int bookingId) { + return new CandidateCapacityImpactNotified(id, 154, "SFO01", "MHL-RN1", LocalDateTime.of(2026, 11, 12, 13, 30), 20, 8, + candidate, bookingId, "BOOKED", "WAITLISTED", CapacityImpact.Kind.STATUS_CHANGED); + } + + @Test + void sameEventIdDeliveredTwiceIsRecordedOnce() { + LoggingNotificationAdapter stub = new LoggingNotificationAdapter(100); + CandidateCapacityImpactNotified n = event(UUID.randomUUID(), "NW00000909", 9); + + assertThat(stub.notify(n)).isTrue(); + assertThat(stub.notify(n)).isFalse(); + + assertThat(stub.sent("NW00000909")).containsExactly(n); + } + + @Test + void filtersByCandidateNumberCaseInsensitivelyAndKeepsDeliveryOrder() { + LoggingNotificationAdapter stub = new LoggingNotificationAdapter(100); + CandidateCapacityImpactNotified a = event(UUID.randomUUID(), "NW00000901", 1); + CandidateCapacityImpactNotified b = event(UUID.randomUUID(), "NW00000902", 2); + CandidateCapacityImpactNotified c = event(UUID.randomUUID(), "NW00000901", 3); + stub.notify(a); + stub.notify(b); + stub.notify(c); + + assertThat(stub.sent(" nw00000901 ")).containsExactly(a, c); + assertThat(stub.sent(null)).containsExactly(a, b, c); + assertThat(stub.sent("")).hasSize(3); + assertThat(stub.sent("NW00000999")).isEmpty(); + } + + @Test + void keepsOnlyTheNewestMaxRecords() { + LoggingNotificationAdapter stub = new LoggingNotificationAdapter(2); + CandidateCapacityImpactNotified a = event(UUID.randomUUID(), "NW00000901", 1); + CandidateCapacityImpactNotified b = event(UUID.randomUUID(), "NW00000902", 2); + CandidateCapacityImpactNotified c = event(UUID.randomUUID(), "NW00000903", 3); + stub.notify(a); + stub.notify(b); + stub.notify(c); + + assertThat(stub.sent(null)).containsExactly(b, c); + } +} 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 1669d041..db8bae9a 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 @@ -19,7 +19,10 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; +import com.northwind.scheduling.domain.CapacityImpact; +import com.northwind.scheduling.notification.LoggingNotificationAdapter; import com.northwind.scheduling.outbox.OutboxEvent; +import com.northwind.scheduling.outbox.OutboxEventType; import com.northwind.scheduling.outbox.OutboxRepository; import com.northwind.scheduling.reconciliation.Reconciliation; import com.northwind.scheduling.reconciliation.ReconciliationService; @@ -28,7 +31,7 @@ /** * MBA-3823 end to end on a real AssessmentDelivery ({@link LegacyEstateDb}): snapshot import -> modern mutations -> * outbox -> relay as ad_sched_relay -> legacy rows equal Scheduling (reconcile 0 mismatches, seat-drift 0 rows), - * and every event replayed twice changes nothing. + * and every event replayed twice changes nothing. MBA-3831: capacity notifications go to the stub once, not to legacy. */ @EnabledIf("com.northwind.scheduling.relay.LegacyEstateDb#available") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) @@ -59,6 +62,7 @@ static void props(DynamicPropertyRegistry r) { @Autowired LegacyRelay relay; @Autowired ReconciliationService reconciliation; @Autowired JdbcTemplate scheduling; + @Autowired LoggingNotificationAdapter notifications; @Test @Order(1) @@ -184,6 +188,39 @@ AND NOT EXISTS (SELECT 1 FROM booking w WHERE w.session_id = s.session_id AND w. .contains("SeatOffered", "SeatOfferAccepted", "SeatOfferDeclined", "SeatOfferExpired"); } + @Test + @Order(6) + void capacityNotificationsAreDeliveredOnceToTheStubAndNeverWrittenToLegacy() throws SQLException { + int occupied = legacyInt("SELECT COUNT(*) FROM dbo.Booking WHERE SessionId = 154 AND Status IN ('BOOKED','ATTENDED')"); + Map before = legacyCounts(); + int sentBefore = notifications.sent(null).size(); + + var out = service.changeCapacity(154, Math.max(2, occupied - 1), "MBA-3831 relay"); + List pending = outbox.pending(1000); + assertThat(pending).extracting(e -> e.type().name()).first().isEqualTo("CapacityChanged"); + assertThat(pending).filteredOn(e -> e.type() == OutboxEventType.CandidateCapacityImpactNotified) + .hasSize(out.notified().size()).isNotEmpty(); + assertThat(out.notified()).anyMatch(a -> a.kind() == CapacityImpact.Kind.STATUS_CHANGED) + .anyMatch(a -> a.kind() == CapacityImpact.Kind.SEAT_CONFIRMED); + + assertRelayed(); + assertThat(notifications.sent(null)).hasSize(sentBefore + out.notified().size()); + Map after = legacyCounts(); + // only the CapacityChanged event reaches legacy: one AuditLog CAPACITY row and one RelayCheckpoint + assertThat(after.get("AuditLog")).isEqualTo(before.get("AuditLog") + 1); + assertThat(after.get("RelayCheckpoint")).isEqualTo(before.get("RelayCheckpoint") + 1); + assertThat(relay.checkpointedEventIds()).doesNotContainAnyElementsOf(pending.stream() + .filter(e -> e.type() == OutboxEventType.CandidateCapacityImpactNotified) + .map(e -> e.eventId().toString()).toList()); + + // relay retry of every event of this change (crash before markRelayed): nothing recorded or written twice + scheduling.update("UPDATE outbox_event SET relayed_at = NULL WHERE event_seq >= ?", pending.get(0).seq()); + assertThat(worker.relayPending()).isEqualTo(pending.size()); + assertThat(notifications.sent(null)).hasSize(sentBefore + out.notified().size()); + assertThat(legacyCounts()).isEqualTo(after); + assertZeroDrift(); + } + 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/web/SchedulingApiIT.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/web/SchedulingApiIT.java index 3fb379bc..eac004d9 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 @@ -70,9 +70,12 @@ HttpResponse attendance(String path, String token) throws Exception { } @Test - void flywayCreatesSchedulingDbAndImporterLoadsSnapshots() { + void flywayCreatesSchedulingDbAndImporterLoadsSnapshots() throws java.io.IOException { 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(3); + try (var migrations = java.nio.file.Files.list(java.nio.file.Path.of("src/main/resources/db/migration"))) { + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM flyway_schema_history WHERE success = 1", Integer.class)) + .isEqualTo((int) migrations.filter(f -> f.getFileName().toString().matches("V\\d+__.*\\.sql")).count()); + } 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", diff --git a/services/scheduling-service/src/test/resources/contracts/scheduling_ui/capacity.yml b/services/scheduling-service/src/test/resources/contracts/scheduling_ui/capacity.yml index 087627f3..0c2ad949 100644 --- a/services/scheduling-service/src/test/resources/contracts/scheduling_ui/capacity.yml +++ b/services/scheduling-service/src/test/resources/contracts/scheduling_ui/capacity.yml @@ -1,4 +1,4 @@ -description: UI admin capacity change (api.changeCapacity); newest bookings above the new capacity are demoted (ODD-02). +description: UI admin capacity change (api.changeCapacity); newest bookings above the new capacity are demoted (ODD-02); the demoted and the 8 remaining BOOKED candidates are notified (MBA-3831). name: ui changes capacity request: method: PUT @@ -16,6 +16,7 @@ response: oldCapacity: 20 newCapacity: 8 demotedBookingIds: [9] + notifiedCandidates: 9 session: sessionId: 154 capacity: 8