ShiftCircle

ShiftCircle — API Specification

Status: v1.1, checked against the controllers on main (23 Nov 2026; release v1.3 endpoints and fields, proposals and supervisor posts, added through 25 Nov 2026) · REST + JSON · this document is the contract (no generated OpenAPI document exists in the prototype; docs/10 §8)

1. Conventions

Topic Convention
Base path /api/v1 (nginx proxies /api/ to the api container)
Docs Planned: OpenAPI 3 at /api/v1/openapi.json and Swagger UI (demo and dev profiles only). Not built (NFR-09, docs/10 §8): this document is the contract
Auth Authorization: Bearer <token> from mock sign-in (see 09-access-control.md)
IDs UUID strings
Time Instants as ISO-8601 with offset (2026-11-21T07:00:00-06:00); dates as YYYY-MM-DD; all in America/Regina
Lists Plain JSON arrays; the prototype has no page/size paging. The one long list, GET /audit-events, is keyset-paged: ?limit= (default 50, at most 200) and ?beforeId=, answering { "items": [...], "nextBeforeId": <id or null> }
Concurrency Editable resources return ETag: "<version>"; updates require If-Match. A stale version gets 412 Precondition Failed. In the prototype this is built for assignment move and cancel (§4.2), the planner’s draft edits and commit (§4.9) and proposal withdraw and decision (§4.4) only. Rule-table drafts are protected by the build fingerprint and the maker/checker states instead.
Errors RFC 9457 Problem Details (application/problem+json), with a ruleResults extension when rules decide (see §3)
CSV Report and export endpoints also answer Accept: text/csv
Correlation X-Correlation-Id is accepted or generated, echoed back, and written to logs and audit

2. Status codes

Code When
200 / 201 Success; 201 with Location for creates (POST /proposals sends none: its GET /proposals/{id} is the decider’s view, not the officer’s)
400 Malformed request or invalid values (field errors listed)
401 / 403 Not signed in / role or unit scope doesn’t allow it; also (release v1.3) a supervisor’s write on their own shift, time entry, absence or overtime offer: “You can’t change your own schedule; ask another supervisor.” (not audited)
404 Not found, or outside the caller’s scope (we don’t reveal what exists)
409 State conflict (e.g. pay period locked, offer already answered, lock refused because past shifts lack actuals)
412 Stale If-Match version
428 If-Match missing where it is required (assignment move and cancel, §4.2; planner draft edits and commit, §4.9; proposal withdraw and decision, §4.4)
422 A rule blocked the change (body includes ruleResults), or Warn results need acknowledgement

2.1 Database conflicts (problem types)

A database constraint that fires under the api answers a problem document, never a raw 500 and never a driver message. One place maps them (ApiProblemAdvice): two advices claiming the same exception, with one of them rethrowing the SQLSTATEs it did not recognise, aborted the handler resolution and answered a 500 (dev-qa, 2026-11-20).

SQLSTATE Problem type Status Title
23P01 (exclusion) .../problems/shift-conflict 409 This officer already has a shift at that time
23505 (unique) .../problems/duplicate-record 409 That record already exists
23514 (check) .../problems/409 409 State conflict (the locked-pay-period trigger is a check violation)
23P01 on pay_period_no_overlap .../problems/pay-period-overlap 409 The pay periods for this plan overlap periods that already exist
22003 (numeric overflow) .../problems/invalid-hours 400 The hours are out of range
maker/checker check .../problems/403 403 The author of a rule version cannot approve it

The body carries no SQLSTATE, no constraint name, no driver message and no stack trace. The exclusion constraint is the one the api can meet: an emergency override lets the rule engine pass, and the database still refuses the overlap. The overtime confirm path checks the overlap itself and answers 422 (.../problems/officer-unavailable) before the database is asked. The unique and numeric-overflow paths are not reachable through the current endpoints (the offer path upserts, and the actual window is validated before the hours are computed); they are mapped for defence in depth.

Everything else answers a problem document too. One advice owns the catch-all, and it is the last one consulted (@Order 10 / 20 / 30 / 40 across the four advices), so it cannot shadow the rule, assignment or payroll advice:

Situation Answer
A role or scope refusal from Spring Security 403 with a problem body (before, it was an empty body)
Not signed in 401 with a problem body (the token filter answers it)
Spring’s own web failures (a wrong verb, a wrong media type) Their own status (405, 415) with a problem body
Anything unexpected 500 with a problem body that says nothing about the internals, plus a traceId; the exception and stack are logged at ERROR under that same id

A refusal also leaves a trace server-side, so hiding the cause from the caller does not hide it from the operator. A database conflict is logged at WARN with its SQLSTATE and constraint name, the rule-compile refusal at WARN with the compiler’s detail, and a boot-validation refusal at ERROR before the app stops. None of that detail is in the response body; the body keeps plain words (and, for an unexpected 500, the traceId to quote).

Known limits of the error contract. A path rejected by Spring Security’s HTTP firewall (an encoded traversal, a session-id suffix) is answered before the api advice, with Spring’s default JSON rather than problem+json; and nginx answers an oversized body (413), a malformed request line or a traversal to a static path with its own HTML page. Neither response carries application internals. Tightening both is deployment work; the api’s own failures are all problem+json.

3. Rule checks: preview, save, override

Every schedule-changing endpoint runs the rules engine. Clients use the same body three ways:

  1. Preview: POST /rule-checks with the proposed change → results, nothing saved.
  2. Save: the real endpoint (e.g. POST /assignments) → 201 if every result is Pass or Info.
    • If any Warn results: 422 with type: .../warnings-need-acknowledgement; resend with "acknowledgeWarnings": ["U-14"].
    • If any Block: 422 with type: .../blocked-by-rules.
  3. Override: resend with "override": { "reason": "Lockdown, no relief available" } (supervisor only, and only for rules whose override policy is EMERGENCY). Creates an override row and an audit event. An override does not acknowledge warnings: the same request must also list every Warn code in acknowledgeWarnings, or it is refused with 422 warnings-need-acknowledgement. Nothing auto-approves, including the warnings that accompany an emergency override.

Locked pay periods are a wall, not a prompt. A preview or save whose shift’s work date falls in a LOCKED period is refused with 409 .../pay-period-locked before any rule check (docs/07 E4, ADR-017). Otherwise a shift could be saved into a closed period and never get its actual.

Preview request (the same body is sent to /assignments; type is ASSIGN or EXTRA, and any other value is 400 naming the field):

POST /api/v1/rule-checks
{
  "change": {
    "type": "ASSIGN",
    "employeeId": "6f1c…",
    "unitId": "a2b9…",
    "shiftTemplate": "D8",
    "startAt": "2026-11-21T07:00:00-06:00"
  },
  "acknowledgeWarnings": ["U-14"],
  "override": { "reason": "Lockdown, relief unavailable" }
}

Each rule result carries ruleCode, outcome, message, facts ({ "required", "actual", "unit" }), evidence ([ { "label": "…" } ]) and overridePolicy (EMERGENCY, ACKNOWLEDGE, NONE). The outcome body has outcome, ruleSetVersion (number) and overridable. The browser contract in web/src/api/types.ts is the implementation reference.

Who can work a post (release v1.3, rule set v4). The check also reads the person’s position, the qualifications they hold on the shift’s date and the unit’s kind, so a result can come from the POSTS table (ruleTable: "POSTS"): R-01 for an officer on a supervisor post (BLOCK with overridePolicy: "NONE", so overridable is false; WARN with ACKNOWLEDGE when the officer holds ACTING_SUP) and R-02 for a supervisor on an officer post (WARN, ACKNOWLEDGE). Their facts are { "required": 0, "actual": 0, "unit": "post" }; the evidence label names the person’s number, their position in words and the post. No request field changed.

Blocked response:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://shiftcircle.local/problems/blocked-by-rules",
  "title": "This change breaks 2 rules",
  "status": 422,
  "outcome": "BLOCK",
  "ruleSetVersion": 7,
  "overridable": true,
  "ruleResults": [
    {
      "ruleCode": "U-01", "outcome": "BLOCK",
      "message": "Only 7 hours' rest after the 12 h shift ending Fri 24:00. The minimum is 8 consecutive hours in any 24 hours.",
      "facts": { "restHours": 7, "minHours": 8 },
      "evidence": [ { "label": "P12 ending Fri 20 Nov 24:00, next shift D8 starts Sat 21 Nov 07:00 (7.00 h rest)" } ],
      "source": "Saskatchewan Employment Act"
    },
    { "ruleCode": "U-05", "outcome": "BLOCK", "message": "17 hours of work in 24 hours (Fri 12:00 – Sat 12:00).", "facts": { "hours": 17, "maxHours": 16 } },
    { "ruleCode": "U-14", "outcome": "WARN", "message": "52 hours this week, over the 48 h warning level." }
  ]
}

4. Endpoints

4.1 Session and reference data

Method Path Purpose Roles
GET /auth/demo-users List users for the mock sign-in picker public (demo profile only)
POST /auth/mock-login { "userId" } → { "token", "expiresAt", "user" } public (demo profile only)
GET /me Current user, roles, unit scope, linked employee (employeeId is an empty string when the account has no officer) and their position in words, e.g. Correctional officer (empty string without a linked officer) any
GET /units Active units (id, code, name, kind, allows_12h, allows_16h, active); a supervisor sees only the units in scope any
GET /units/{id}/requirements Not built. The unit requirements are used by the board, coverage and planner payloads; there is no endpoint of their own (answers 404) —
GET /shift-templates The active templates only: A12, D12, D8, P12, E8, N12, N8 (code, label, start, duration_minutes, regular_allowed, chip_style). L16 is retired and not listed (ADR-029) any
GET /qualifications Qualification list any
GET /employees?unitId= Officers in scope SUPERVISOR, AUDITOR
GET /employees/{id} Not built (answers 404); /employees?unitId= carries what the screens need —

4.2 Schedule (planning board and My schedule)

Method Path Purpose Roles
GET /schedule?unitId=&from=&to= Planning board payload: days, coverage per block (required / scheduled / actual, each with the lowest hourly count and the short hour ranges, see below), officer rows with assignments, overtime status per officer, warnings, overridesThisPeriod, asOf and publishedState (see below) SUPERVISOR (own units), AUDITOR, PLANNER (read-only, all units)
GET /me/schedule?from=&to= My shifts, hours this pay period, overtime this quarter, next shift, my position in words, asOf (the server’s “today”, as on GET /schedule). Since release v1.3 S7 employee.post names a supervisor’s post and the line units it covers (“Supervision · Operations (ADM, CTL, ESC)”); it is null for anyone homed on a line unit any account linked to an employee record (404 otherwise)
POST /rule-checks Preview any change (§3) SUPERVISOR; EMPLOYEE for their own shifts (the Propose shifts check)
POST /assignments Assign a shift (§3 rules apply) SUPERVISOR; never on the caller’s own record (403, release v1.3)
PATCH /assignments/{id} Move or change a shift (If-Match) SUPERVISOR; never on the caller’s own record (403, release v1.3): neither the shift moved nor the person it moves to
DELETE /assignments/{id} Cancel (sets CANCELLED; never hard-deletes) SUPERVISOR; never on the caller’s own record (403, release v1.3)

A change’s startAt must be within five years of the business “today”; a date outside that range is 400 naming startAt, not a conflict. A Locked pay period refusal stays 409. | POST | /schedule-periods/{id}/publish | Publish a period | SUPERVISOR | | POST | /absences | Record sick, vacation or other (type only) | SUPERVISOR; never on the caller’s own record (403, release v1.3) |

Publishing is one-way in the prototype: it sets the period to PUBLISHED, records published_at and published_by, writes a publish_schedule_period audit row and answers {id, status, publishedAt}. A second publish answers 409; an unknown period is 404, and another unit’s period is also 404 so its existence is not revealed. The board’s publishedState.published reads the same rows.

A period is one roster week (Monday to Sunday) of one unit. The demo dataset seeds one period per unit and per week of the demo window: the weeks that ended before the demo day are PUBLISHED (they are history), and the week the demo day falls in and the weeks after it are DRAFT, so a supervisor has a period to publish on a fresh stack. GET /schedule returns the period it shows as period { id, label, status } (see the board header below), and that id is what POST /schedule-periods/{id}/publish takes. The status column is DRAFT or PUBLISHED; there is no UNPUBLISHED status in the schema.

Publishing is a recorded state, not an access gate (FR-06, prototype scope). GET /me/schedule and GET /me/offers do not filter by period status: the demo day’s own week is seeded DRAFT (so a supervisor has something to publish) and the employee’s current week and Sat 21 Nov offer must stay visible. Gating them would need the seeded current week to be PUBLISHED, which changes the pinned dataset checksums and the publish step of the demo. Future work.

Move and cancel (PATCH / DELETE /assignments/{id}): the exact contract (decided 2026-11-20 so the builder doesn’t have to guess):

Topic Rule
Version shift_assignment.version is the version. GET /schedule shift items carry version; POST, PATCH and DELETE answers carry ETag: "<version>". Each successful move or cancel increments it.
If-Match Required on both. Missing: 428 Precondition Required (.../problems/if-match-required). Stale: 412 (.../problems/stale-version). The If-Match check happens inside the per-officer lock (ADR-021), so two concurrent edits can’t both pass it.
Cancel body DELETE takes a JSON body { "reason": "…" }. The reason is required, at least 10 characters after trimming (same rule as overrides and unlock), else 400. It isn’t stored on the assignment: it goes into the cancel_assignment audit event (before = the assignment, after = { status: CANCELLED, reason }).
Cancel effect Sets status = CANCELLED; never deletes. No rule check (removing a shift can’t break a rest or hours rule; coverage shows any gap). Answers 200 with { id, status, version }. A second cancel is 409 (.../problems/already-cancelled).
Move body PATCH takes the same body as POST /assignments: change with all four of employeeId, unitId, shiftTemplate and startAt (the full target, not a partial patch), plus optional acknowledgeWarnings and override. kind and source don’t change. A move needs no separate reason; an override carries its own.
Move rules The full §3 pipeline runs on the target, with the assignment’s own current slot left out of the officer’s existing shifts, so it can’t conflict with itself. 422 blocked or warnings, and overrides, exactly as §3. Updated in place: same id, new version, a move_assignment audit event with before/after. If the officer changes, both officers’ locks are taken in id order. Answers 200 with the save outcome.
Locked period 409 .../pay-period-locked if the current work date is in a locked period (move and cancel), or the target work date is (move).
Started shifts 409 .../shift-started if the assignment has started by the server’s “today” clock (the demo clock on the demo profile: noon on the demo day). Past shifts are corrected in Time & attendance, not on the schedule. GET /schedule sends that clock as now, so the board can say so before the request (v1.2, below). A move whose target start has already passed (startAt <= now, the same clock) is refused with 409 .../target-started (“The new start has already passed · Pick a date and shift that start later. Past shifts are corrected in Time & attendance, not on the schedule.”), with or without an override, before the rules run (v1.2).
Recorded actual or absence DELETE answers 409 .../actual-recorded when a time entry already references the shift, and 409 .../absence-recorded when an absence row does, even if the start time alone would not have refused it. Correct the record in Time & attendance instead.
Filled open shift Cancelling an assignment that filled an open shift (open_shift.filled_assignment_id) puts that open shift back to OPEN with filled_assignment_id cleared, so the gap is visible and can be offered again. Offer rows are left unchanged (not set to WITHDRAWN): the confirmed offer stays as history, and the cancellation is in the audit trail. Moving such an assignment is refused with 409 .../fills-open-shift: cancel it and assign again.
Offers A pending offer (offer: true chip) is not an assignment, so these endpoints don’t apply to it. Withdrawing an offer is not built (docs/10 §8).
Order of checks role (403) → unknown or out of scope (404) → body (400) → own record (403, release v1.3: the shift, or for a move the target person, is the caller’s own; for a cancel this comes before the body, so a self-cancel with no reason is a 403) → If-Match (428, 412; a self-move without If-Match is a 403, not a 428) → state (409: already cancelled, locked, started, fills open shift, target locked, target started; actual or absence recorded for a cancel) → rules (422, move only).
Roles SUPERVISOR, own units only. For a move, both the current and the target unit must be in scope. Scope is checked on the unit of the shift, not the officer’s home unit: a supervisor may assign an officer from any unit into a unit in their own scope (cross-unit cover, ADR-024). The rule preview then shows that officer’s rest conflicts. A supervisor can’t assign into a unit outside their scope (404), and can’t read an officer’s data outside their scope except through that preview.

Coverage per block (ADR-013 revised, ADR-017): coverage is hourly, so one number per block can hide a short hour. GET /schedule returns a flat coverage array (one entry per block per day); GET /display/today uses the same block shape. Each entry carries:

{ "block": "EVENING", "date": "2026-11-20", "required": 5,
  "scheduled": { "lowestHourly": 4, "shortHours": [ { "from": "15:00", "to": "17:00", "count": 4 } ], "maxHourly": 6 },
  "actual":    { "lowestHourly": 5, "shortHours": [], "maxHourly": 6 },
  "covered": false }

The payload also has unit { id, name }, days (ISO dates), asOf (the demo today), now (the business clock’s instant, v1.2), officers (rows with day cells of SHIFT items), warnings, overridesThisPeriod, publishedState { published, unpublishedChanges } and period { id, label, status }, matching web/src/api/types.ts.

Supervisor posts (v1.3 S6): on the live board unit also carries kind (SUPERVISION for a supervisor post, else the line unit’s kind), each officer row carries position (CO officer, CS supervisor) and supervisory (the position’s is_supervisory flag), and a line unit covered by a post (unit_supervision) carries supervisorsOnDuty: [{ date, block, names[] }], one entry per day and block: the people on the post whose shift overlaps the block’s hours (Days 07–15, Evenings 15–23, Nights 23–07, the coverage windows) and has no recorded absence, counting only a supervisor or an officer holding Acting supervisor on that day; empty when nobody, and on a day the unit is closed. Only posts in the caller’s scope are read (facility-wide roles see all); with none, the field is left out. Names are sent because this is the signed-in board; the wall display stays counts only. On a post’s own board the coverage counts the same people (R-01): an officer left on the post without a valid Acting supervisor qualification is a row but does not cover it. A supervisor post’s own board and the planner’s draft leave supervisorsOnDuty out, and the draft leaves kind, position and supervisory out too.

Move and cancel refusals known in advance (v1.2): on the live board each SHIFT item also carries actualRecorded (any time entry references it, actual or absence), absenceRecorded (an absence row references it), fillsOpenShift (it fills an open shift) and payPeriodLocked (its work date is in a locked pay period, the first state the api checks), and fromProposal: true when an approved shift proposal created it (source = 'PROPOSAL', v1.3 P4; left out otherwise, for the chip’s “from an approved proposal” tooltip), the same queries PATCH/DELETE /assignments/{id} run. With now (a shift has started when startAt <= now) the shift dialog says which action the api would refuse, in the api’s own words, and does not offer it. now and the flags are as of the board’s last load: a board left open across a shift’s start still offers the move, and the api’s 409 answer is then shown. They are hints for the screen only: the api still checks every move and cancel. The planner’s draft roster leaves now and the four flags out. “Already cancelled” cannot be known in advance (the board never lists a cancelled shift) and stays an answer.

lowestHourly is the minimum headcount over the block’s hours; shortHours lists merged hour ranges below required (to is exclusive); covered is true when shortHours is empty. actual is present for past hours only. The display version has the same shape and still no names.

Board header fields: four facts on the board are neither per-officer nor per-block, so GET /schedule returns them at the top level of the payload:

{ "asOf": "2026-11-19",
  "overridesThisPeriod": 1,
  "publishedState": { "published": true, "unpublishedChanges": 3 },
  "period": { "id": "9f0a…", "label": "16 – 22 Nov 2026", "status": "PUBLISHED" } }

asOf is the server’s “today” (SC_DEMO_TODAY on the demo profile), so the board marks the same days the api does instead of guessing from the browser clock. now (v1.2, for example "2026-11-19T18:00:00Z") is the business clock’s instant (BusinessClock: noon on the demo day in Regina on the demo profile, the real clock otherwise), the “now” behind 409 .../shift-started. overridesThisPeriod counts the emergency overrides recorded in the pay period on the board.

period is the roster week the board shows: the schedule_period row whose dates contain the board’s range (from and to). It is null when the range is not inside one period — a board that spans two weeks has no single period. id is what POST /schedule-periods/{id}/publish takes, label is the week for people (“16 – 22 Nov 2026”) and status is DRAFT or PUBLISHED.

publishedState.published is true when that period is published. publishedState.unpublishedChanges counts the shifts of that period that were assigned, moved or cancelled after it was published; the source is the append-only audit trail (the assign_shift, move_assignment and cancel_assignment events of those shifts). It is null when the period is not published: there is no publication to compare against, and the board says “not published” instead of a change count.

4.3 Overtime

Method Path Purpose Roles
GET /open-shifts?unitId=&from=&to=&status= Open shifts SUPERVISOR
POST /open-shifts Create an open shift SUPERVISOR
GET /open-shifts/{id}/candidates Ranked list: order from the overtime-ranking rule table; each candidate has eligibility (ELIGIBLE, WARN, SKIPPED, UNAVAILABLE) and rule results SUPERVISOR
POST /open-shifts/{id}/offers { "employeeIds": [...], "ordered": false } → offers recorded in-app SUPERVISOR; never to oneself (403 if any listed employee is the caller; nothing is written)
POST /open-shifts/{id}/assign Assign directly (§3 rules and overrides apply) SUPERVISOR; never to oneself (403)

Overtime pools by position (release v1.3, S5; owner answer Q4). The candidate list and the offer path keep to the post’s pool. For an open shift on a SUPERVISION unit the list holds the supervisors (CS), ranked by O-01/O-02, then the officers who hold ACTING_SUP, ranked by O-01/O-02 among themselves and placed after every supervisor (R-01 makes each a WARN); other officers are not listed. For an open shift on an officer unit the list holds officers (CO) only. O-02’s tie-break and seniorityDate are seniority inside the rank, coalesce(position_since, seniority_date) (an officer’s service date; a supervisor’s promotion date). Overtime hours this quarter are each person’s own. POST /open-shifts/{id}/offers with anyone outside the pool answers 422 (.../problems/officer-unavailable, detail “Not in this officer post’s overtime pool …” or “Not in this supervisor post’s overtime pool …”) before any offer is written. A direct assign is not limited by the pool: the rule check (R-01/R-02) decides it, as on the board. The proposal’s openShift.otOrderPosition/otOrderSize read the same pools.

A direct assign and an offer confirm both lock the open_shift row before the officer, then fill it conditionally: of any number of concurrent attempts, even by different officers, exactly one succeeds and the rest answer 409 “This shift is already filled”. | GET | /me/offers?status=OFFERED | My pending offers | EMPLOYEE | | POST | /offers/{id}/accept · /offers/{id}/decline | Respond. Accepting re-checks rules; the supervisor then confirms. | EMPLOYEE (own) | | POST | /offers/{id}/confirm | Confirm an accepted offer → creates the assignment | SUPERVISOR; never one’s own offer (403, after the offer and shift state checks: a filled shift is still 409) |

Who appears in the candidate list. The list is the fair-distribution order for the people in the post’s overtime pool whose home unit is in the caller’s scope: for an officer post, officers; for a supervisor post, supervisors and then officers who hold ACTING_SUP (release v1.3 S5, above). A supervisor outside the shift’s scope gets 404 for it. The ranking is still fewest overtime hours this quarter, ties by seniority inside the rank (O-02); a person a Block rule would stop is SKIPPED in place, and a person who cannot take the shift (unqualified for Control or Escort, already scheduled) is UNAVAILABLE in place, so the fairest next person stays visible (O-03, PC-09).

Offers and confirmation. The supervisor makes offers only to people in the post’s pool whom the rules allow (outside the pool: 422 officer-unavailable, checked again at confirmation for an offer made before the pools); a BLOCK at offer time is refused with the rule results. The employee’s accept re-checks the rules. The confirmation re-checks again: a BLOCK refuses, a warning the supervisor already saw in the offer-time snapshot does not need a second answer, but a new warning is refused with 422 warnings-need-acknowledgement. The assignment is created through the normal rules/override path (POST /assignments), so S-04 and the audit event still hold.

4.4 Proposals (employee shift planner) — API built (v1.3 P1 officer side, P2 decider side); officer screen built (P3), inbox screen built (P4)

An officer proposes extra shifts to add; a supervisor in scope approves or declines each one, and an approved shift becomes an EXTRA / PROPOSAL assignment. The API for both sides is built: preview, send, list, withdraw and expiry (P1), and the inbox, detail and decision (P2). The officer’s screen is built (P3): My schedule’s Propose shifts card previews, sends and lists through these endpoints, and /me/propose redirects to it. The inbox screen is built (P4): each inbox card also carries shifts (unit, shiftTemplate, startAt, workDate, decision, the items on the caller’s units in start order), so several proposals from one officer can be told apart. /proposals lists, opens and decides through these endpoints, with “Proposals (n)” in the nav from GET /proposals/count; a 422 decision refusal’s items replace the shown “rules now” in place. Design: owner answers Q1 to Q5 (overtime-order acknowledgement, add-only, no sending Blocked drafts, any active unit with supervisors in scope deciding and the planner as fallback, paid like an accepted overtime offer).

Method Path Purpose Roles
POST /proposals/preview { "items": [ { "unitId", "shiftTemplate", "startAt" } ] }. Each item is rule-checked as an EXTRA shift with the items that start before it as extra facts, so rest and hours between two drafts show. Saves nothing. Returns { outcome, canSend, items: [ { index, unit, shiftTemplate, startAt, endAt, outcome, ruleSetVersion, ruleResults, problem, problemCode } ] }; problem is a plain-words 409-type reason (locked period, closed unit, already waiting) EMPLOYEE (own)
POST /proposals { "note", "items": [...] }. Re-checks server-side and stores the proposal and its items (201, the proposal view). The warn codes are kept in each item’s rule_snapshot. Audit submit_proposal (the note’s length, never its text) EMPLOYEE (own)
GET /me/proposals?status= The caller’s proposals, newest first (at most 200), with item outcomes, decider name and comment. status is ALL (default), WAITING, APPROVED, PARTLY_APPROVED, DECLINED, WITHDRAWN or EXPIRED. Expiry is applied first EMPLOYEE (own)
POST /proposals/{id}/withdraw If-Match: "<version>". Allowed only while every item is still waiting. 200 with the proposal view. Audit withdraw_proposal EMPLOYEE (own)

The proposer is always the caller. The account must be linked to an officer (404 otherwise, as for /me/schedule). The body is strict: an employeeId anywhere in it is 400, so nobody proposes for someone else. Someone else’s proposal is 404 on withdraw, and never appears in /me/proposals. AUDITOR, RULES_* and DISPLAY get 403.

Order of checks (send): role (403) → linked officer (404) → body (400) → state (409) → rules (422).

Status When
400 No items; more than 10 items; two items that overlap in time; a missing field or unknown unit; an inactive or retired shift type (L16); a start that is not in the future, or after the end of the planned quarter (11 Apr 2027); a note over 500 characters; an unknown field (including employeeId)
409 pay-period-locked; unit-closed (the unit’s hard switch is off or unit_active_on is false that day); duplicate-waiting-item (the officer already has a waiting item overlapping that time); too-many-waiting (more than 20 waiting items for the officer)
422 blocked-by-rules: any item is a Block. Warn items can be sent. The body carries items[] with each item’s outcome and ruleResults
withdraw 428 no If-Match; 400 not a number; 412 stale version; 409 not-withdrawable once any item is decided, expired or the proposal is withdrawn already

Proposal view: { id, status (WAITING, DECIDED, WITHDRAWN, EXPIRED), displayState, note, submittedAt, withdrawnAt, version, canWithdraw, items: [ { id, unitId, unit, unitName, shiftTemplate, startAt, endAt, workDate, decision (PENDING, ACCEPTED, DECLINED, WITHDRAWN, EXPIRED), outcomeAtSubmit, ruleAtSubmit, decidedBy, decidedAt, comment } ] }. displayState is derived: Waiting while any item is pending; then Approved (all accepted), Partly approved, Declined (all declined) or Expired.

Expiry. A waiting item expires when its shift starts (start_at <= now, the business clock, demo day 19 Nov 2026). It is applied inside every read and withdraw of a proposal and by an hourly sweep, so nobody acts on a shift that has started. Each expiry writes expire_proposal_item once, with no actor (the system).

Limits. At most 10 items per proposal and 20 waiting items per officer; dates from now to the end of the planned quarter. An officer may propose in any active unit (not only the home unit); the rules and qualifications decide eligibility. The per-officer advisory lock is taken on send and withdraw, the same lock the board uses. Per officer and minute: 60 previews, 10 sends and 10 withdraws, then 429 (.../problems/rate-limited, with retryAfterSeconds). Reading /me/proposals expires only the caller’s own items; the hourly sweep expires everyone’s.

Demo data (v1.3 P5). Every reset (and the first boot) plants four proposals, so the inboxes are not empty: Tara’s Waiting proposal with two shifts (Unit B, Tue 22 Dec, for M. Ellis; Admissions, Wed 30 Dec, for J. Chen), her proposal Declined by J. Chen with a comment, one Expired (its shift started on 16 Nov), and M. Ellis’s own Waiting SUP-L day shift (Sun 29 Nov) for J. Chen or the planner. A fresh reset’s GET /proposals/count is 1 for M. Ellis and 2 for J. Chen (and the planner). They create no shift, so no checksum moves; see docs/demo-script.md §8 and ADR-032.

The decider’s side (v1.3 P2)

Method Path Purpose Roles
GET /proposals?status=WAITING\|ALL&unitId=&from=&to= The inbox: proposals with at least one item on a unit in the caller’s scope (the planner: every unit), newest first, at most 200. WAITING (default) keeps those with a waiting item in scope. unitId outside the scope is 404; from/to filter on the items’ work dates. Card: { id, employeeId, officerName, homeUnit, units (in scope), itemCount, itemsInScope, waitingInScope, submittedAt, status, displayState, version, own, shifts }; shifts is [ { unit, shiftTemplate, startAt, workDate, decision } ], only the items on the caller’s units, in start order (a mixed-scope proposal shows each supervisor only their own shifts; itemCount still says how many there are in all) SUPERVISOR, PLANNER
GET /proposals/count?status=WAITING The nav count: waiting proposals in scope that the caller may decide (their own are left out). { status, count } SUPERVISOR, PLANNER
GET /proposals/{id} The detail (below). Expiry is applied first SUPERVISOR (≥ 1 item in scope), PLANNER
POST /proposals/{id}/decision If-Match: "<version>", { "items": [ { "id", "accept", "comment"?, "acknowledgeWarnings"?: [codes], "acknowledgeOutOfOrder"?: bool } ] }. 200 with the detail. Audit decide_proposal_item per item SUPERVISOR (item’s unit in scope), PLANNER

Who decides. A supervisor decides the items on units in their scope; the planner sees and decides every item, so Unit C (no supervisor scope in the demo) and a supervisor’s own proposal always have a decider. Nobody decides their own proposal: 403 “You can’t approve your own proposal; another supervisor or the planner will” when the caller’s employee is the proposer (SelfActionGuard, the predicate the supervisors’ self-edit guard shares). A proposal with no item in the caller’s scope is 404 on detail and decision (it is not revealed); naming an item on a unit outside your scope in a decision you can otherwise see is 403. EMPLOYEE, AUDITOR, RULES_* and DISPLAY get 403 on all four.

Detail: { id, status, displayState, version, note, submittedAt, withdrawnAt, employeeId, officerName, homeUnit, own, canDecide, items: [ … ] }. Each item carries id, unitId, unit, unitName, shiftTemplate, startAt, endAt, workDate, hours, decision, inScope, canDecide and the outcome fields decidedBy, decidedAt, comment, acknowledgedCodes, outOfOvertimeOrder, assignmentId. An item in scope also carries:

An item outside the caller’s scope is listed with its unit, time and decision only, with no rule detail and no action. The note is the officer’s plain text: clients show it as text, never as HTML, and it is never in an audit row, a report or the wall display.

The decision, in one transaction, items in start order:

  1. Checks: visibility (404) → self-approval (403) → body (400) → item scope (403) → If-Match (428 / 400) → the open-shift rows, then the officer’s advisory lock (the overtime confirm’s order), expiry, and the item rows (FOR UPDATE, so the hourly sweep skips them) → state (409) → version (412) → locked pay period / closed unit / retired shift type (409) → rules and the overtime order (422).
  2. Every accepted item is checked again now, with the items accepted earlier in the same send as extra facts and before any of them is saved (so nothing is counted twice). A Block refuses the whole send with 422 blocked-by-rules and nothing is saved: there is no override from a proposal (owner Q3; decline and use the board’s emergency override instead). A Warn needs every current code in that item’s acknowledgeWarnings (422 warnings-need-acknowledgement); the codes are stored in acknowledged_codes. An approval of someone who is not first in the overtime order needs acknowledgeOutOfOrder: true (422 out-of-overtime-order, owner Q1). Every 422 carries items[] with each accepted item’s outcome, warnCodes, ruleResults and, for a matched open shift, otOrderPosition, otOrderSize, outOfOrder, openShiftId and liveOffers (the OFFERED offers on it now, which an approval withdraws; an ACCEPTED one stays, so the screen never repeats the detail’s older count; v1.3 P5).
  3. Then each accepted item is written through AssignmentWriter, the planning board’s own write path (rules, insert, assign_shift audit with source: PROPOSAL, proposalId, proposalItemId), as a shift_assignment with kind EXTRA, source PROPOSAL and no override. A matched open shift becomes FILLED with that assignment, and its offers still waiting for an answer (OFFERED) become WITHDRAWN (plan §4). An offer the officer already ACCEPTED is left as it is; confirming it is then refused with 409 “This shift is already filled”, as for any filled shift. The rule result the writer enforces is the one checked in step 2 (it is passed in, not evaluated twice), so what is stored and audited is what was enforced. The item stores the decider, time, comment, the assignment, decision_snapshot, the acknowledged codes, out_of_ot_order and the open shift.
  4. A declined item needs a comment of at least 3 characters (400); the officer sees it in /me/proposals. Comments are at most 500 characters.
  5. The proposal’s version goes up by one, conditionally on the version the decision checked; it is DECIDED once no item waits. Every item update must change exactly one row. Either check failing rolls back the whole decision.

ruleNow and the decision gate differ on purpose. The detail’s ruleNow assumes every earlier waiting item is approved (as the send did); the decision checks each accepted item only with the items accepted earlier in the same send. An item can therefore show a Warn in the detail that the decision does not ask about when the earlier item is declined. The inbox screen (P4) says so under each item while other items of the proposal wait.

Status When
400 No items; an item id that is not in the proposal or is listed twice; accept missing; a decline without a comment of 3+ characters; a comment over 500; more than 50 codes in an item’s acknowledgeWarnings; an unknown field
403 Your own proposal; an item on a unit outside your scope; a role that may not decide
404 No such proposal, or none of its items is on your units
409 proposal-withdrawn; shift-started (the item expired: its shift started before anyone answered); already-decided; pay-period-locked; unit-closed; shift-type-retired (retired after the send); open-shift-filled (filled between the check and the write); an overlap with a shift saved meanwhile (shift-conflict, the database exclusion). An item that changes underneath the decision (expired by the sweep, withdrawn) is 409 too, and the whole decision rolls back: no shift, no fill, no audit row
412 / 428 Stale If-Match / missing If-Match
422 blocked-by-rules, warnings-need-acknowledgement, out-of-overtime-order (body above)

Audit decide_proposal_item (entity proposal, one row per item): itemId, employeeId, unit, template, startAt, decision, comment, and for an approval outcomeNow, acknowledgedCodes, assignmentId, openShiftId, offersWithdrawn, outOfOvertimeOrder (plus otOrderPosition / otOrderSize when an open shift matched). The created shift has its own assign_shift row.

The planner writes shifts here. This is the first place PLANNER creates a shift_assignment outside a plan commit; it is the fallback decider for units no supervisor scopes (owner Q4). A later plan commit treats source = 'PROPOSAL' rows like supervisor edits (ADR-030: refuse rather than overwrite). ADR-032 records it; docs/09 has the matrix row.

4.5 Time and payroll

Method Path Purpose Roles
GET /pay-periods Periods with status, the period’s overtime threshold and the lock totals SUPERVISOR, AUDITOR
GET /pay-periods/{id}/time-entries?employeeId= Scheduled vs actual entries with pay codes, the officer’s name and unit, the actual start and end, and the unpaid extension under 30 min (P-04) SUPERVISOR, AUDITOR; EMPLOYEE (own)
PUT /time-entries/{id} Record actuals (worked as scheduled / adjusted times / absence type); changing a recorded absence to worked (or back) replaces the previous record SUPERVISOR; never on the caller’s own record (403, release v1.3)
DELETE /time-entries/{id} Clear the actual or absence and return the shift to needsActual; a locked period answers 409, and the change is audited (clear_actual) SUPERVISOR; never on the caller’s own record (403, release v1.3)
POST /pay-periods/{id}/lock Lock: actuals become read-only. Refused with 409 (type: .../problems/missing-actuals, body lists missing: [{ assignmentId, employeeId, start }] and a count) while any shift in the period that has ended (end_at ≤ now) has no actual time entry or absence (ADR-017). Idempotent: locking a period that is already LOCKED returns 200 with the period view and writes no second audit row. Facility-wide: any supervisor with at least one unit in scope (ADR-022) SUPERVISOR
POST /pay-periods/{id}/unlock { "reason" }; audited with actor and reason. Facility-wide (ADR-022). Concurrent unlocks apply once and write one audit row SUPERVISOR
GET /pay-periods/{id}/payroll-export text/csv; locked periods only; records a payroll_export row with the actor and file hash. Facility-wide: every officer in the period, not only the caller’s units (ADR-022) SUPERVISOR

Time entries and pay periods (what the Time and attendance screen needs): a time entry carries the officer’s employeeName and the unitId / unitName it belongs to, so the grid needs no second call; when something was recorded it carries actualStart and actualEnd, and an extension under 30 minutes that is not paid is unpaidExtensionMinutes (P-04). A shift that has ended (end_at ≤ now) with no actual and no absence is needsActual: true. A pay period carries overtimeThresholdHours (80 h by default, ADR-016) and the totals the lock confirmation repeats: totals.officers, totals.workedHours and totals.overtimeHours. A locked period also carries lockedBy (the supervisor’s display name) and lockedAt, for both a period locked through the API and a period the demo dataset seeded as locked, so the screen names the actor instead of saying “a supervisor”.

Overtime classification: overtime is computed per pay period (P-01): hours beyond the threshold, in time order, get overtime codes. Any change to a period’s actuals recalculates its codes; locking freezes them.

Payroll CSV columns: employee_no, pay_period_start, pay_period_end, work_date, pay_code, hours, unit_code, cost_centre, with hours to 2 decimals in 15-minute increments. Totals per employee must equal the sum of actual time entries (tested).

4.6 Reports

Method Path Purpose Roles
GET /reports/coverage?from=&to=&unitId=&groupBy=day\|week Required vs scheduled vs actual staff-hours and fill rate; each bucket carries extraHours and extraHoursByBlock (DAY, EVENING, NIGHT) for assignments of kind EXTRA or source OVERTIME_OFFER, plus extraPercent (the scheduled-percent points made of those hours: extraHours / requiredHours * 100, 0 if none), and the CSV adds extra_hours,extra_day,extra_evening,extra_night. The axis floor axisFrom includes scheduledPercent - extraPercent for every week, so the regular part is never clipped. extraHours is scheduled extra-shift hours, not payroll overtime SUPERVISOR, AUDITOR
GET /reports/hours?from=&to=&unitId=&employeeId=&position= Scheduled, worked, and hours by pay code per person; each row carries position (CO/CS, release v1.3 S7) SUPERVISOR, AUDITOR; EMPLOYEE (own only)
GET /reports/overtime?from=&to=&unitId=&top=&position= Overtime hours by person and unit; each row carries position. With position, the rows and averageHours are that rank’s pool only (release v1.3 S7). On both reports an unknown position code is 400 SUPERVISOR, AUDITOR
GET /reports/overrides?from=&to=&unitId= Emergency overrides with reasons SUPERVISOR, AUDITOR

employeeId is read by the hours report only (an officer is always limited to their own row); the overtime and overrides reports answer 400 if it is sent. A chosen unitId narrows every report; a supervisor may pick only a unit in their scope (404 otherwise), and an auditor reads the whole facility when none is given. Without from/to each report uses its own default range. to must not be before from and at most 366 days after it, and both must fall in the years 1900–2999; anything else answers 400.

CSV export: each report answers text/csv on the same path when the request sends Accept: text/csv; the web’s Export CSV button uses that. Columns: coverage week, required_hours, scheduled_hours, actual_hours, scheduled_percent, actual_percent, planned; hours employee_no, name, scheduled, worked, regular, overtime_15, overtime_20, sick, vacation, position; overtime employee_no, name, overtime_hours, position (position = CO/CS, added last in release v1.3 S7 so the earlier columns keep their places; the payroll CSV is unchanged); overrides at, employee, unit, rule_codes, actor, reason. Cells are RFC 4180 quoted where needed and a leading =, +, -, @, TAB or CR is neutralised with a single quote, so a spreadsheet cannot evaluate a value as a formula.

Definitions: coverage is hourly (ADR-013): required staff-hours are the unit requirements per block × the block’s hours, and scheduled/actual hours count each assignment or actual entry once per hour slot it covers. A week that has not started is planned with no actual figure; an in-progress week compares against the required hours that have elapsed at the demo “today”. Overtime is classified per pay period through the same PayClassifier as payroll, so a full period’s OT15 hours equal the payroll export’s. For a custom range, classification covers only the entries with a work date inside the range, so a partial period can differ from the payroll export. Override rows carry the reason, the rule codes and the actor who recorded them (docs/09 §6). Defaults when no range is given: coverage = the last six weeks plus next week; hours = the latest locked pay period; overtime = the current quarter; overrides = the last four weeks.

4.7 Rules administration

Method Path Purpose Roles
GET /rule-sets Versions and status RULES_ADMIN, RULES_APPROVER, AUDITOR, SUPERVISOR (read)
GET /rule-sets/{version}/tables/{code} Rows, column schema and plain-language sentences. code is the table code or the web’s slug; release v1.3 adds POSTS (slug posts, “Who can work a post”), whose columns read Post, Who can work it, If someone else, Override and whose rows carry params.postKind, params.allowedPositions and params.actingQualification. Every row carries must (true for a rule the mock agreement requires: its result, override and enabled cannot change, and the build refuses a change; ignored on PUT) same
POST /rule-sets/drafts { "basedOn": 7, "reason" } → new draft (also used to roll back to an older version) RULES_ADMIN
PUT /rule-sets/{version}/tables/{code}/rows Replace a table’s rows in a draft (no If-Match in the prototype: saving clears the build, and a stale build can’t be submitted) RULES_ADMIN
POST /rule-sets/{version}/build Validate → compile (Drools) → run test scenarios → dry run on the published roster; returns the report (steps, scenarios, and errors: why the build did not pass, one plain line per problem, which the screen lists under the checklist) RULES_ADMIN
POST /rule-sets/{version}/submit Submit a successfully built draft for approval RULES_ADMIN
POST /rule-sets/{version}/approve · /reject Second-person decision (approved_by ≠ created_by) RULES_APPROVER
POST /rule-sets/{version}/publish Hot-swap the live rule base at the effective date RULES_APPROVER

A row edit is saved or refused, never silently dropped. The PUT checks every params key against the table’s column schema: an unknown key, a value of the wrong type, a list longer than 16 values, or a missing value in a column that is not nullable answers 400 naming the column (and the key). minExtensionMinutes is part of the REST table’s contract even though the v1 column schema predates it, so a new row and a stored row behave the same; any other undeclared key is refused. An unknown top-level field on a row object is also 400, naming the field (the request fails on unknown properties rather than ignoring them). afterShiftKind is the stored column for the rest table’s “After this kind of shift” field: the friendly labels (Any shift, Regular shift, 16 h shift, 12 h 00–12, 12 h 12–24) map to their patterns, and a raw pattern such as D8|E8 or (D8|N8|A12) is accepted when it matches the strict grammar; anything else is 400, never stored as .*. When both after (the friendly label) and params.afterShiftKind are sent they must agree: a disagreement is 400 naming both fields, and a client that edits the column sends one value in both fields (or only afterShiftKind). A rule code uses letters, digits and hyphens (for example U-01 or P-01b). A message is a string of at most 500 characters; result is BLOCK, WARN or INFO; override is EMERGENCY, ACKNOWLEDGE or NOT_ALLOWED; anything else is 400 naming the column. Every numeric column has a documented range (docs/04 §5a) enforced at the PUT. A refusal names the visible column label (for example “The At least (hours) off column must be between 8 and 24 hours”), never the params key; an unknown key still names itself, because there the client must fix the field. The build’s validation is total: a row stored with a bad value (for example by a direct database edit) becomes a validation error, not a 500, and a report shows at most 20 errors with a count of the rest.

The sentence is for the person reading it, not the compiler. Each row’s sentence is plain language: the afterShiftKind pattern appears as a phrase (“any shift”, “a regular shift”, “a 16-hour shift”, or the shift codes in words), never as the stored regex (.*), and the severity is a word (“blocked”, “warned”, “noted”), never the raw enum (BLOCK). The override policy is its own sentence (“A supervisor may override only in an emergency, with a written reason.”). A row message is shown as written. RuleSentenceTest pins this for every shipped row, including the message rows.

The build is the evidence, and it goes stale if the rows move. build stores a fingerprint of the exact rows it validated, compiled and ran; saving rows again clears the report and the fingerprint, and submit/publish refuse an older build with 409. At boot the live rule base is the published version’s rows from PostgreSQL, not a code constant, so a restart keeps the published rules. The dry run reports counts per rule, unit and old→new outcome, never names (ADR-017). Publishing an older approved version after a newer one is allowed and supersedes the newer one: it is the rollback path, and the audit row records which version went live.

Excel export and import: future work (not built in the prototype). The design planned GET /rule-sets/{version}/tables/{code}/export (an .xlsx Drools decision table) and POST …/import (a multipart .xlsx into a draft, then build as usual). Neither exists, and there is no plan to build them for the prototype (docs/10 §8). If built, an import must go through the same validation as the grid (R24/R28: rule values are code input).

4.8 Wall display, audit, operations

Method Path Purpose Roles
GET /display/today Counts per unit and block, open shifts and overtime counts. No names. Since release v1.3 S7 a posts array gives each supervisor post in scope as {post:{id, name}, area, coverage} (area = “Operations”; coverage in the unit block shape); units and the two totals stay the line units only DISPLAY, SUPERVISOR (own units), AUDITOR
GET /audit-events?actor=&action=&entityType=&entityId=&from=&to=&beforeId=&limit= Audit trail, newest first, keyset-paged (§1 Lists) AUDITOR, SUPERVISOR (own units)
GET /audit-events/actors The actors whose events the caller can see, for the filter dropdown (same scope as the trail) AUDITOR, SUPERVISOR (own units)
GET /version Build name, version and buildTime, gitCommit, live rule set version (ruleSetVersion, e.g. v4), profiles, asOf (the server’s “today”, so the web’s clock shows the demo day), and on the demo profile demoMode, the reset datasets (["100","120","150"]) and activeDataset (the dataset loaded now; the Quarter plan warns when it is 100) any
GET /actuator/health Liveness and readiness. Internal only, not proxied by nginx. container network

4.9 Quarter planner (ADR-026)

Method Path Purpose Roles
GET /planner/plan Window (4 Jan – 11 Apr 2027, 7 periods), default seed, the 8 h patterns, current draft and last committed plan PLANNER
POST /planner/drafts {seed, pattern8h?, staffTypes?, partTimeFill?, crossUnitFill?} → generate a draft over the whole quarter; replaces the open draft. v1.2 options: staffTypes is ["FULL_TIME"] or ["FULL_TIME","PART_TIME"] (default; PART_TIME = FTE below 1.0), partTimeFill is AFTER_FULL_TIME (default) or UP_TO_FTE, crossUnitFill is OFF (default) or ON (gaps left after the home-unit fills go to qualified officers from other units with hours left; the scorecard then carries crossUnit: {gapsBefore, gapsCovered, shifts, officers, fromUnits, stillShortReasons, stillShortByUnitBlock, line}, measured at generation and kept through hand edits). Omitted options take the defaults, which make the same plan as before. Any other value (including a crossUnitFill other than OFF/ON), a list without FULL_TIME, or UP_TO_FTE without PART_TIME is 400 problem+json whose title names the field. crossUnit.stillShortReasons counts each gap the pass could not cover by the first filter nobody passed: NO_OFFICER_FREE, NOT_QUALIFIED (for the gap block, or for any block the borrowed shift also covers), NO_SHIFT_FITS, NO_HOURS_LEFT, RULE_BLOCK. The draft summary (here, GET /planner/drafts/{id} and GET /planner/plan) carries options: {staffTypes, partTimeFill, crossUnitFill}; the audit event generate_plan records them. With no pattern8h, every 8 h officer uses their own employee.shift_pattern (the normal call); a sent pattern8h is the one-release facility override and the draft summary keeps that code. If the window already has a committed plan, 409 problem+json with reason: ALREADY_COMMITTED_WINDOW and a plain sentence naming the commit date/author and pointing at Reset the demo data PLANNER
GET /planner/inputs Plan inputs (v1.2): what Generate would use now, counts only. {window, options:{seed, pattern8h, staffTypes, partTimeFill, crossUnitFill}, officers:{total, fullTime, partTime, fte, neededFte, neededFrom, neededTo, neededPeriods, units}, units:[{code, name, allows12h, officers, fullTime, partTime, fte, minimums:{NIGHT, DAY, EVENING}, closedDays, groups:[{employment: FULL_TIME\|PART_TIME, hours, pattern, patternWords, officers, fte}]}], leave:{days, officers, byType}, preferences:{officers, shiftLength, timesOfDay, daysOffOfficers, …}, seniority:{earliest, latest}, rules:{ruleSetVersion, historyDays, fillOrder[]}}. Built from the generator’s own loaders. partTime is every officer under 1.0 FTE (the generator has no separate casual class). neededFte is the Staffing floor of the stretch between unit closures that needs the most officers (neededFrom–neededTo, one of neededPeriods stretches; with no closure, the quarter; on a tie, the earliest such stretch); units is every planned unit. With a forced pattern8h the 8 h groups follow it. fillOrder is worded for the draft’s options. Generate options go in options; a draft keeps its own copy as scorecard.inputs (the seed, pattern8h, staffTypes, partTimeFill and crossUnitFill it was generated with), unchanged by hand edits. GET /planner/inputs takes the same three options as query parameters (?staffTypes=FULL_TIME&partTimeFill=…&crossUnitFill=…), so the landing card and its fill order follow the Generate form; a bad value is the same 400; officers.partTimeFte lets a full-time-only headline count only the staff it plans with PLANNER
GET /planner/drafts/{id} Draft summary and scorecard PLANNER
GET /planner/drafts/{id}/schedule?unitId&from&to The Roster tab: the draft’s shifts in the same SchedulePayload shape as the planning board; an officer placed in this unit from another (cross-unit fill or closed-unit relief) has homeUnit (their home unit’s name), omitted otherwise and never sent by GET /schedule (rotation says the pattern in words; publishedState is false; period null). Planned leave (absence rows with no shift assignment) is added to a cell as {type: "ABSENCE", absenceType: "VACATION"\|"SICK"\|"OTHER"}, the My schedule item shape; an active officer of this home unit on leave with no draft shift in the range gets a leave-only row (rotation “On leave”, 0 h). GET /schedule (the live board) does not carry planned leave (PR-D, fit-gap i-7) PLANNER
GET /planner/drafts/{id}/coverage?from&to One entry per unit with its BlockCoverage[] (same hourly shape as the board) PLANNER
GET /planner/drafts/{id}/gaps Short block-days with unit, date, block, required and placed PLANNER
GET /planner/drafts/{id}/warnings All warnings, grouped by plain rule name PLANNER
GET /planner/drafts/{id}/commit-preview Version, shifts, officers, gaps and warning count the commit will ask to accept PLANNER
POST /planner/drafts/{id}/assignment-checks Preview one draft add/move; saves nothing. Body {assignmentId?, employeeId, unitId, shiftTemplate, startAt, kind?}; 200 with {outcome, ruleSetVersion, overridable, ruleResults} PLANNER
POST /planner/drafts/{id}/assignments Add one shift to a DRAFT; If-Match draft version; Pass saves, Warn needs acknowledgeWarnings:true, Block refuses PLANNER
PUT /planner/drafts/{id}/assignments/{assignmentId} Move time/unit or reassign the one shift; same body/rules/If-Match PLANNER
DELETE /planner/drafts/{id}/assignments/{assignmentId} Remove one draft shift; If-Match draft version PLANNER
POST /planner/drafts/{id}/commit If-Match: <version>, {acceptedWarningCount} → write every assignment atomically and audit once; 412 stale, 422 per-assignment failures, 409 locked period or changed warnings PLANNER
POST /planner/drafts/{id}/discard Discard an open draft; 409 if it is no longer a draft (a commit or another discard already won, including a discard that raced a running commit) PLANNER
GET /planner/drafts/{id}/compare Draft vs the board. Rows cover coverage gaps, unfilled gap hours, shifts, officers scheduled, planned hours, plan-added warnings, preferences met (the same per-criterion count as the scorecard’s preferences.met), and weekends min/avg/max, each with board, draft, unit and direction (LOWER_IS_BETTER/HIGHER_IS_BETTER/NEUTRAL), plus one coverage-gap row per unit. Board measures come from the committed shifts through the board’s own coverage code; draft measures from the plan tables PLANNER
POST /planner/absences {employeeId, date, type} → mark a future absence (SICK/VACATION/OTHER) inside the quarter; the next draft skips that officer on that date. Idempotent for the same officer/date/type (200 with the existing row); a different type on that date is 409. Read-only input, not leave management; PLANNER only PLANNER
GET /planner/preferences?unitId= Every officer’s preferences with how the open draft met them; after a commit it evaluates the committed plan (MET/PARTLY/NOT_MET, with unmet reasons), not “No draft”. Each row also carries the officer’s pattern (ROTATING_5_2/5_ON_2_OFF/7_ON_3_OFF, or 4_ON_4_OFF for a 12 h officer), patternWords in plain words and patternEditable (true only for an 8 h officer) PLANNER
PUT /planner/preferences/{employeeId}/pattern {pattern} → set an 8 h officer’s pattern and return the updated row. 400 in plain words for a 12 h officer (“A 12-hour officer keeps the crew’s 4 on, 4 off pattern”), a 12 h code on an 8 h officer, or an unknown code; 404 for an unknown officer. The next generate uses it; a pattern change does not touch an existing draft, exactly like a preference change PLANNER
GET · PUT · DELETE /me/preferences The signed-in officer’s own preferences (shiftLength, timesOfDay, up to 2 daysOff). timesOfDay is an array of DAY/EVENING/NIGHT without duplicates; empty = no preference; responses carry timesOfDay only. The old single timeOfDay is accepted on input for one release and mapped to a one-element set (NONE/null to empty); if both are sent, timesOfDay wins any account linked to an officer

After a commit the plan is still readable. GET /planner/plan answers state: COMMITTED, draft: null, lastCommitted as before, and a committedDraft with the same DraftSummary shape (id, version, seed, pattern8h, status: COMMITTED, createdAt, createdBy, generatedMs, scorecard). The read-only endpoints GET /planner/drafts/{id}/gaps, /warnings, /schedule, /coverage and /compare answer for a committed id, so the tabs survive the commit. Compare adds draftStatus and basis: a committed plan is compared with the current board, including supervisor edits since the commit; an open draft is compared with the last committed plan (or the seeded roster before a commit). A committed id is never writable: commit/discard still refuse it.

Supervisors in the planner (release v1.3, S3). The planner is rank-aware; nothing changes until there is a supervisor or a supervisor post (the datasets get them in S4), so every pin is unchanged.

Draft hand edits (release 7 #27). A PLANNER may add, move time/unit, reassign one-way, or remove one shift in an uncommitted DRAFT. Draft rows live in plan_draft_assignment; the live board is untouched. Every save requires If-Match with the draft version (428/412) and uses the planner’s RuleCheckService seam: a Block is 422 blocked-by-rules with ruleResults and saves nothing; a Warn without acknowledgeWarnings:true is 422 warnings-need-acknowledgement and saves nothing; here acknowledgeWarnings is a boolean (true keeps every Warn shown), unlike the supervisor’s POST /assignments, which takes an array of Warn codes (["U-14"]); a Pass or acknowledged Warn writes one row, bumps the version, writes one edit_plan_draft audit row and recomputes gaps, warnings and the scorecard synchronously. DRAFT only (409 after commit/discard); closed unit, duplicate (employee,start), unknown id, retired template, non-PLANNER and a busy reset/generate get plain problem details. No EMERGENCY override. Success: {draftId, assignmentId, version, handEdits, editedAssignmentIds, scorecard, warnings, warningCount, gaps}; DraftSummary carries handEdits/editedAssignmentIds, and roster shift items carry edited:true (derived from audit rows, no migration). Generate/discard delete edits; commit still re-verifies every row, edits included.

A draft is not a roster.A draft is not a roster. plan_draft_assignment is separate from shift_assignment; the planning board never reads it. Every generated assignment is verified by RuleCheckService against the draft’s own assignments plus the committed history before the window, and a Block rule leaves a visible gap instead of a shift. Commit re-runs every check against the current committed state, refuses any Block with a per-assignment list, requires the exact warning count to be acknowledged (acceptedWarningCount), refuses a locked period, and writes all rows plus one commit_plan audit event in one transaction. Each written row carries plan_draft_id; overrides are never implied. The scorecard also carries qualification (release 6 #6, warn-only): failingBlockDays, checkedBlockDays, passes, from, to, byUnitBlock (unitCode, unitName, block, qualification, minimum, failingBlockDays, checkedBlockDays), validFromRespected: false, validFromNote and sentence. It is read-only over the draft; PlanGenerator and every placement path are untouched. It counts active unit-days only (a date-aware closure has no checked or failing day) and counts an officer placed as relief in the unit where they are placed, with their own qualifications. valid_from is not read: an officer with the qualification counts for the whole quarter, stated on the card. Measured with no closures: 100 346 of 1,470, 120 0 of 1,470, 150 103 of 1,470.

The scorecard carries coverage gaps measured in absolute time (the NIGHT block on date D runs 23:00 D to 07:00 D+1, the same code the board uses), warnings by plain rule name (only warnings the plan adds: each officer’s history-only baseline is subtracted), preferences asked/met by kind, night share by seniority band plus the newest-first check, nightPolicy (only 12 h officers work nights; an 8 h night preference is shown unmet with that reason), absences (officers, days, coveredByRelief, uncovered and one plain line such as “3 officers on leave were skipped: relief officers covered 22 of the shifts”), n12Officers/ n12NightShifts and a fixed-crew note when the dataset has N12 crews, officers and hours over 80, generation time, the staffing report (staffing: leave allowance, periods split at closure boundaries, per-unit allocated/filled/needed/shortfall and the visible breakdown), weekends worked per officer (min/avg/max), fteBands (full-time / 0.7-0.9 / under 0.7: officers, target hours, planned min/avg/max) with the plain note that part-time and casual officers are not guaranteed hours, and patterns (officers: [{employeeNo, name, unitCode, pattern, words}] plus a plain note) so every officer’s pattern is visible in words, never a raw code. The shift pattern is per officer (Option C): every 8 h officer carries ROTATING_5_2 (default; the days-off pair retreats one weekday per pay period and the wrap takes a 3-day break, so weekends rotate and the changeover period is 72 h with one U-12 and one U-14 warning), or the planner’s 5_ON_2_OFF (fixed pairs, 80 h, no warnings) or 7_ON_3_OFF. A 12 h officer’s 4-on/4-off cycle comes from the crew and is read-only. The generator resolves each officer’s days and staggers phases per pattern cohort, so mixed cohorts sit side by side and every proposal still goes through the rule engine; with every 8 h officer on the default the 100 and 120 drafts are shift-for-shift unchanged (the reset test pins both assignment fingerprints). The 100 seed’s 12 h officers use A12/P12 4-on/4-off; the 120 dataset uses the V6 D12 07-19 / N12 19-07 crews with paired phases. The planner never rosters 16 h (a 16 h preference is stored and shown unmet; in practice a “16 h shift” is a 12 h shift plus ~4 h overtime extension recorded after the fact). A committed quarter creates its seven 14-day pay periods and each unit’s schedule periods, so it can be locked and paid.

4.11 Units, closures and staffing (Release 3, ADR-027 addendum)

Method Path Purpose Roles
GET /planner/units Units with today (OPEN/CLOSED/SWITCHED_OFF), todayNote, allocated, filled and closures (id, closedFrom, reopensOn|null, reason, createdBy, createdAt, state FUTURE/CURRENT/ENDED) PLANNER
POST /planner/units/{id}/closures/preview {closedFrom, reopensOn?} → {officersHomed, publishedShiftsAffected}; no write PLANNER
POST · PUT · DELETE /planner/units/{id}/closures[/{closureId}] Close from a date, change/reopen, or remove; reason required (>=5 characters). 400 plain messages for a past closing date, reopening not after closing, an overlapping closure, or a short reason; 404 unknown unit/closure; 409 “Supervisor posts can’t be closed; change the minimum instead” for a SUPERVISION unit (release v1.3; also on the preview) PLANNER
GET /planner/flagged-shifts Future non-cancelled shift_assignment rows in a unit closed on the shift date: shiftId, unitId, unitCode, unitName, date, templateCode, shiftLabel, officerName, start, end, closedFrom, reason. Nothing is deleted PLANNER
GET /planner/staffing leaveAllowance, periods split at every closure boundary (max 3 by shortage), each with unit rows {closed, allocated, filled, needed, shortfall, breakdown{posts12Day, posts12Night, posts8, rawNeeded, leaveAllowance, needed}} and summed totals; note/truncated when capped PLANNER
PUT /planner/units/{id}/staffing {allocated, reason} → the unit’s staffing row; 0-999 whole number, reason >=5, audited PLANNER
PUT /planner/settings/leave-allowance {percent, reason} → {leaveAllowance}; 0-50 whole percent, reason >=5, audited PLANNER

needed = ceil((2 × (posts12Day + posts12Night) + 1.4 × posts8) / (1 - leaveAllowance)). With 12 h allowed, posts12Day is the DAY minimum, posts12Night the NIGHT minimum and posts8 = max(0, EVENING - NIGHT) (the 19-23 hours the night crew does not cover); a unit without 12 h uses 8 h posts for every block. shortfall = max(0, needed - filled). A unit closed for a whole period needs 0. The board/roster SchedulePayload.unit and each planner UnitCoverage carry closedFrom, closedTo, closedLabel, closedReason and closedDates; the Coverage report carries closureNotes; the wall display carries closedToday/closedNote. Audit codes: unit_closure_added, unit_closure_changed, unit_closure_removed, unit_staffing_changed, leave_allowance_changed. The 100/120 seeds have no closure rows, so their checksums, payroll golden and plan fingerprints are unchanged until a planner closes a unit.

4.10 Demo reset (demo profile only)

Method Path Purpose Roles
POST /demo/reset { "confirm": "RESET", "dataset": "100" } → start emptying and reloading the selected demo dataset. dataset defaults to 100; 120 is the 100 full-time crews + 20 casual relief pool; 150 is 120 full-time + 30 part-time with 20% leave (ADR-028); an unknown value is 400 listing the available datasets; 409 while a reset or a planner generate/commit is in flight PLANNER
GET /demo/reset/status { state: IDLE\|RUNNING\|DONE\|FAILED, step, startedAt, elapsedMs, checksum, dataset, error }; dataset is the one that ran PLANNER

The endpoints exist only on the demo profile (/version carries demoMode and the datasets list ["100","120","150"] so the web shows the selector there). The reset is asynchronous: it clean-migrates the schema, re-runs the same deterministic DemoDataGenerator, reloads the live rule base, plants the four demo shift proposals against those rules (step: proposals, v1.3 P5; they create no shift), and returns the dataset checksum. While it runs, every other API call answers 409 (status and version stay reachable), and the first audit event afterwards is demo_reset, so it is visible that the previous history was erased. User ids are stable, so a signed-in planner stays signed in.

5. Screen-to-endpoint map

Screen (UI canvas) Main calls
Planning board GET /schedule, POST /rule-checks, POST/PATCH/DELETE /assignments, POST /schedule-periods/{id}/publish
My schedule GET /me/schedule, GET /me/offers, POST /offers/{id}/accept, POST /rule-checks, POST /proposals/preview, POST /proposals, GET /me/proposals, POST /proposals/{id}/withdraw (built in v1.3: the API in P1, the screen in P3; it drafts, sends, lists and withdraws)
Proposals inbox GET /proposals, GET /proposals/count, GET /proposals/{id}, POST /proposals/{id}/decision (API v1.3 P2, screen P4)
Overtime board GET /open-shifts, GET /open-shifts/{id}/candidates, POST /open-shifts/{id}/offers, POST /open-shifts/{id}/assign
Rules GET /rule-sets…, PUT …/rows, POST …/build, …/submit, …/approve, …/publish (Excel export/import: not built)
Reports GET /reports/*, GET /pay-periods/{id}/payroll-export
Wall display GET /display/today every 60 s