Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/runbooks/scheduling-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions reports/reconciliation-20261111-222613.md
Original file line number Diff line number Diff line change
@@ -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).
2 changes: 2 additions & 0 deletions services/scheduling-service/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ with `JAVA_HOME=<JDK 21> ./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).
4 changes: 4 additions & 0 deletions services/scheduling-service/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1328,6 +1328,9 @@ components:
type: integer
format: int32
example: 5
notifiedCandidates:
type: integer
format: int32
oldCapacity:
type: integer
format: int32
Expand All @@ -1337,6 +1340,7 @@ components:
required:
- demotedBookingIds
- newCapacity
- notifiedCandidates
- oldCapacity
- session
CenterDto:
Expand Down
65 changes: 65 additions & 0 deletions services/scheduling-service/docs/events.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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"] }
}
}
2 changes: 1 addition & 1 deletion services/scheduling-service/frontend/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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;
Expand Down Expand Up @@ -59,6 +63,7 @@ export default function CapacityEditor({ session, onChanged }: { session: Sessio
<Modal open={confirming} title="Confirm capacity change" onClose={() => setConfirming(false)}>
<p className="text-sm text-slate-600">Change session #{session.sessionId} from <b>{session.capacity}</b> to <b>{n}</b> seats?</p>
{demotions > 0 && <p className="mt-2 rounded-lg bg-amber-50 p-3 text-sm text-amber-800">{demotions} active booking(s) exceed the new capacity; the newest will be moved to the waitlist.</p>}
{n < session.capacity && session.bookedSeats > 0 && <p className="mt-2 text-xs text-slate-500" data-testid="capacity-notify-hint">A notification event is queued for each affected candidate (MBA-3831; stub, no email/SMS yet).</p>}
<div className="mt-5 flex justify-end gap-2">
<button className="btn-secondary" onClick={() => setConfirming(false)}>Back</button>
<button className="btn-primary" disabled={busy} onClick={apply} data-testid="confirm-capacity">{busy ? 'Saving…' : 'Confirm'}</button>
Expand Down
7 changes: 7 additions & 0 deletions services/scheduling-service/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,13 @@
<version>${openapi-diff.version}</version>
<scope>test</scope>
</dependency>
<!-- MBA-3831: docs/schemas/*.schema.json validated against emitted outbox payloads -->
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>1.5.9</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -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> affected(int oldCapacity, int newCapacity, List<BookingState> before,
List<BookingState> 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> affected(int oldCapacity, int newCapacity, List<BookingState> before,
List<BookingState> after, Set<Integer> offeredBefore,
Set<Integer> offeredAfter) {
Map<Integer, BookingState> prev = before.stream()
.collect(Collectors.toMap(BookingState::bookingId, Function.identity(), (a, b) -> a));
List<Affected> 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);
}
}
Original file line number Diff line number Diff line change
@@ -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) {
}
Loading
Loading