import type { FastifyInstance, FastifyReply } from "fastify"; import type { Db } from "@parking/db"; import { tillGuards, type TillId } from "@parking/shared"; import { requireAuth, roleHasPermissions } from "../auth.js"; import { parseTill, requireTill, tillsReadableBy } from "../modules.js"; import { NoOpenShiftError, ShiftAlreadyOpenError, type ShiftService, type ShiftSummary } from "../shift-service.js"; interface ShiftsQuery { /** Filter to one operator (admin-only; non-admins are forced to themselves). */ operator?: string; /** ISO window over shift START time. */ from?: string; to?: string; /** Filter to one till; absent = every till the role may read. */ till?: string; } // Shift endpoints (manned mode). The operator is the logged-in user; a shift is // opened/closed explicitly (not time-based — see wiki/concepts/shift.md and // local-jwt-auth.md "until logout"). End Shift signs a shift_z_report + prints it. // // TILLS + PERMISSIONS: every endpoint addresses a `till` (query on GET, body on POST; // default booth) and its guard is resolved FROM THE TILL (requireTill): the booth's shift // is `shift:read` / `shift:create`, the wash's is `carwash:read` / `carwash:cash` — each // desk's money is guarded by that desk's own permissions, so a wash role holds no // `shift:*` at all and cannot touch the booth. See venue-modules.md §"Permissions matrix". export async function shiftRoutes(app: FastifyInstance, db: Db, shift: ShiftService): Promise { const statusOf = (till: TillId, me: string, roleId: string) => { const open = shift.currentOpenShift(till); const heldBy = open?.identity ?? null; const drawer = shift.drawerBalance(till); return { till, open: open ? { startedAt: open.occurredAt, operator: heldBy } : null, isMine: open != null && heldBy === me, /** May this role open/close this till's shift? (The UI offers the button only then.) */ canWork: roleHasPermissions(roleId, [tillGuards(till).shift]), drawerMinor: drawer.balanceMinor, currency: drawer.currency, }; }; // The shift state of ONE till (at most one shift open per till). The UI uses this // to render a till's control: no shift → "Open"; my shift → "Close" (enabled); // someone else's shift → disabled. Also returns the live drawer balance. // - till: which till this describes // - open: the open shift { startedAt, operator } or null // - isMine: true iff the open shift belongs to the requesting operator // - canWork: may this role open/close it // - operator: the requesting user (for the UI's own identity) // - tills: every till THIS ROLE may read — what the UI offers controls for app.get("/api/shift/current", { preHandler: requireTill(db, "read", "query") }, async (req) => ({ operator: req.user.username, tills: tillsReadableBy(db, req.user.roleId), ...statusOf(req.till!, req.user.username, req.user.roleId), })); // The state of every till this role may read, in one read — the shift hub lists // each open shift and offers "start" for the idle ones it may work. app.get("/api/shift/tills", { preHandler: requireAuth }, async (req) => { const me = req.user.username; return { operator: me, tills: tillsReadableBy(db, req.user.roleId).map((t) => statusOf(t, me, req.user.roleId)) }; }); // Mid-shift X-report: a READ-ONLY "so far" snapshot of the OPEN shift's takings + // drawer (opening float, cash/card taken, pay-ins/outs, expected drawer), computed // as of now. Appends nothing — it's not an accountability mark, just a projection // (the Z-report at close is the signed record). 204 when no shift is open. app.get("/api/shift/report", { preHandler: requireTill(db, "read", "query") }, async (req, reply) => { const report = shift.currentReport(req.till!); if (!report) return reply.code(204).send(); return report; }); // Completed shift history. SCOPED by permission: // - a till's `read` guard (operators) → own shifts only, on the tills they may read; // operator/from/to params ignored. // - `shift:cash` (admin-grade) → all operators, optionally filtered by // `operator` and a `from`/`to` time window over each shift's START. // This keeps one operator from reading another's takings while letting admins // reconcile across the site. The data is the signed shift_z_report chain. Both // scopes may filter by `till` (must be one the role may read). app.get<{ Querystring: ShiftsQuery }>("/api/shifts", { preHandler: requireAuth }, async (req, reply) => { const canSeeAll = roleHasPermissions(req.user.roleId, ["shift:cash"]); const readable = tillsReadableBy(db, req.user.roleId); if (!canSeeAll && readable.length === 0) return reply.code(403).send({ error: "forbidden" }); const q = req.query ?? {}; // Non-admins are hard-scoped to themselves regardless of any operator param. const operator = canSeeAll ? (q.operator?.trim() || undefined) : req.user.username; const from = canSeeAll ? q.from?.trim() || undefined : undefined; const to = canSeeAll ? q.to?.trim() || undefined : undefined; let tills: TillId[] = canSeeAll ? [] : readable; // [] = no till filter (admin) if (q.till?.trim()) { const parsed = parseTill(db, q.till.trim()); if (!parsed) return reply.code(400).send({ error: "unknown till", code: "bad_till" }); if (!canSeeAll && !readable.includes(parsed)) return badTill(reply, parsed); tills = [parsed]; } const shifts: ShiftSummary[] = tills.length === 0 ? shift.listShifts({ operator, from, to }) : tills.flatMap((till) => shift.listShifts({ operator, from, to, till })).sort((a, b) => b.index - a.index); // Admins also get the distinct operator list (unfiltered) for the filter // dropdown — operators don't see other names, so it's scope-gated. if (canSeeAll) return { shifts, scope: "all", operators: shift.listOperators(), tills: tillsReadableBy(db, req.user.roleId) }; return { shifts, scope: "self", tills: readable }; }); // NB: drawer cash movements (record/review) moved to routes/drawer.ts (2026-07-01) — the // feature is no longer part of the shift route. See wiki/concepts/shift.md. app.post("/api/shift/open", { preHandler: requireTill(db, "shift", "body") }, async (req, reply) => { try { return await shift.open(req.user.username, req.till!); } catch (err) { if (err instanceof ShiftAlreadyOpenError) return reply.code(409).send({ error: err.message }); return reply.code(500).send({ error: (err as Error).message }); } }); app.post("/api/shift/close", { preHandler: requireTill(db, "shift", "body") }, async (req, reply) => { try { return await shift.close(req.user.username, req.till!); } catch (err) { if (err instanceof NoOpenShiftError) return reply.code(409).send({ error: err.message }); return reply.code(500).send({ error: (err as Error).message }); } }); } function badTill(reply: FastifyReply, till: TillId): FastifyReply { return reply.code(403).send({ error: `your role cannot see the ${till} till`, code: "till_forbidden", till }); }