8a437d0c4b
CI / check (push) Failing after 56s
Cancel a misprinted/test/wrong-vehicle ticket via a SIGNED `void` event — the
vehicle_entry is never edited/deleted (append-only). VoidFlow appends void{
voidedEntryRef, voidReason, operator, reasonCode:"void.ticketCancelled" }; route
POST /api/tickets/void gated event:void + open shift; reason REQUIRED. Refuses a
subscription / already-exited / already-voided / paid ticket (refund out of scope).
The void folds the session CLOSED everywhere it's counted — occupancy (count +
reserved spots), pay-station (lookup/activeSessions), exit-flow (#sessionFor), and
reports (excluded from entries) — so a voided car stops occupying a spot, can't be
paid/exited, and doesn't inflate "cars entered". No barrier action. Booth UI: a
"Cancel ticket" action in the pay/exit lookup modal (transient + unpaid + open;
gated on event:void) with a preset-or-free reason prompt.
Reclassify the Live feed: refused-action events (exitRefused/entryRefused/
permitRefused — e.g. a double card-scan, at-capacity subscriber, exit on a closed
session) are benign warnings, not red anomalies. event-detail.tsx now shows them as
amber REFUZUAR/REFUSED, reserving red ANOMALI for genuine red-flags. Display-only —
no ledger change, so historical events reclassify too.
CI: install uv + sync vision deps before the Turbo run. @parking/vision's lint/
typecheck/test shell to `uv run …`, but CI set up only Node+pnpm, so `uv run ruff`
failed ("uv not found") and broke the whole Turbo run. The Python checks pass once
uv provisions the toolchain.
- new: void-flow.ts (+ tests, 8) ; occupancy void-fold test
- shared: reason code void.ticketCancelled ; both web catalogs (sq/en parity)
- wiki: parking-session (ticket-void folds + guards, refused/anomaly split), log
Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
257 lines
11 KiB
TypeScript
257 lines
11 KiB
TypeScript
import type { FastifyInstance } from "fastify";
|
|
import type { Db } from "@parking/db";
|
|
import { NoPrinterAvailableError } from "@parking/devices";
|
|
import { requirePermission } from "../auth.js";
|
|
import {
|
|
NoOpenSessionError,
|
|
NoTariffError,
|
|
type PayStation,
|
|
} from "../pay-station.js";
|
|
import type { ExitFlow } from "../exit-flow.js";
|
|
import type { VoidFlow } from "../void-flow.js";
|
|
import { NoShiftOpenError, type ShiftService } from "../shift-service.js";
|
|
import { printPaymentReceipt } from "../booth-print.js";
|
|
|
|
// Booth endpoints (pay-on-foot): look up a session, quote it, take payment, and —
|
|
// when the booth is at/near the exit — open the barrier. The payment becomes a
|
|
// signed ledger event; PCI scope stays OUT of the app (card capture is a standalone
|
|
// P2PE terminal; `tender` just records cash vs. card). The booth exit reuses the
|
|
// SAME validation as the reader path — no booth-only bypass admits an unpaid car.
|
|
// See wiki/concepts/tariff.md, parking-session.md, booth-exit-flow.md, bom.md.
|
|
|
|
interface QuoteQuery {
|
|
identity: string;
|
|
}
|
|
interface PayBody {
|
|
identity: string;
|
|
tender: "cash" | "card";
|
|
/** Operator-set amount (lost ticket / dispute) — overrides the computed fee. */
|
|
overrideMinor?: number;
|
|
}
|
|
interface ExitBody {
|
|
identity: string;
|
|
}
|
|
interface VoucherBody {
|
|
identity: string;
|
|
}
|
|
interface ReceiptBody {
|
|
identity: string;
|
|
}
|
|
interface VoidBody {
|
|
identity: string;
|
|
reason: string;
|
|
}
|
|
|
|
export async function payRoutes(
|
|
app: FastifyInstance,
|
|
db: Db,
|
|
payStation: PayStation,
|
|
exitFlow: ExitFlow,
|
|
shift: ShiftService,
|
|
voidFlow: VoidFlow,
|
|
): Promise<void> {
|
|
// Reads (lookup, active sessions, quote) need session/payment read; the booth
|
|
// money actions (pay, exit, voucher, receipt, reopen) need payment:create. A
|
|
// single guard covers the whole booth flow — anyone who takes payment also reads
|
|
// sessions. Read-only callers (a viewer role) get the reads but not the actions.
|
|
const guard = requirePermission("payment:create");
|
|
const readGuard = requirePermission("session:read");
|
|
const voidGuard = requirePermission("event:void");
|
|
|
|
// Money-path gate: a shift must be open site-wide before any payment/exit/voucher/
|
|
// re-open is processed, so every taking is attributed to a shift (one operator's
|
|
// accountability period). Read-only lookups (session/active/quote) stay ungated so
|
|
// the modal can still DISPLAY the session and prompt the operator to open a shift.
|
|
// Returns 409 { error, code: "no_shift" } so the UI can show the "open a shift"
|
|
// prompt rather than a generic failure. See wiki/concepts/shift.md.
|
|
const requireShift = async (
|
|
_req: import("fastify").FastifyRequest,
|
|
reply: import("fastify").FastifyReply,
|
|
) => {
|
|
try {
|
|
shift.requireOpenShift();
|
|
} catch (err) {
|
|
if (err instanceof NoShiftOpenError) {
|
|
return reply.code(409).send({ error: err.message, code: "no_shift" });
|
|
}
|
|
throw err;
|
|
}
|
|
};
|
|
|
|
// Active sessions for the booth list: still-open OR exited-but-within-grace
|
|
// (barrier unconfirmed → a paid/exited car is presumed possibly-present until
|
|
// grace expires). Read-only. See wiki/concepts/booth-exit-flow.md.
|
|
app.get("/api/sessions/active", { preHandler: readGuard }, async () => ({
|
|
sessions: payStation.activeSessions(),
|
|
}));
|
|
|
|
// Session lookup for the booth pay/exit modal: entry/exit times, paid state,
|
|
// amount owed now, walk-back-grace status. Read-only (no side effect).
|
|
app.get<{ Params: { identity: string } }>(
|
|
"/api/session/:identity",
|
|
{ preHandler: readGuard },
|
|
async (req, reply) => {
|
|
const identity = (req.params.identity ?? "").trim();
|
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
|
return payStation.lookup(identity);
|
|
},
|
|
);
|
|
|
|
// Booth-driven exit: validate (paid + grace, or free entry-grace) THEN sign
|
|
// vehicle_exit + open the barrier. Maps the discriminated result to HTTP:
|
|
// - validation reject → 409 with a reason (operator takes payment first),
|
|
// - exit signed but barrier didn't open → 200 { opened:false } (payment stands;
|
|
// operator opens manually; an anomaly is already signed),
|
|
// - clean exit → 200 { opened:true }.
|
|
app.post<{ Body: ExitBody }>(
|
|
"/api/exit",
|
|
{ preHandler: [guard, requireShift] },
|
|
async (req, reply) => {
|
|
const identity = (req.body?.identity ?? "").trim();
|
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
|
const res = await exitFlow.exitForBooth(identity);
|
|
if (!res.ok) return reply.code(409).send({ error: res.reason, status: res.status });
|
|
return reply.code(200).send(res);
|
|
},
|
|
);
|
|
|
|
// Human-intervention barrier re-open for an ACTIVE (paid) session — damaged
|
|
// ticket / dead scanner / phantom re-close. Re-pulses the exit relay + signs an
|
|
// anomaly (attributed); NEVER a second vehicle_exit. Refused without a payment
|
|
// (no-unpaid-bypass). See wiki/concepts/booth-exit-flow.md.
|
|
app.post<{ Body: ExitBody }>(
|
|
"/api/barrier/reopen",
|
|
{ preHandler: [guard, requireShift] },
|
|
async (req, reply) => {
|
|
const identity = (req.body?.identity ?? "").trim();
|
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
|
const operator = req.user?.username;
|
|
const res = await exitFlow.reopenBarrier(identity, operator);
|
|
if (!res.ok) return reply.code(409).send({ error: res.reason });
|
|
return reply.code(200).send(res);
|
|
},
|
|
);
|
|
|
|
// Cancel (void) a wrongly-printed transient ticket. Appends a SIGNED `void` event
|
|
// referencing the entry, with the operator + a REQUIRED reason — the entry itself is
|
|
// never edited/deleted (append-only). The session projection folds the void to CLOSED,
|
|
// so the voided car stops counting inside and can't be paid/exited. Opens NO barrier
|
|
// (the misprinted ticket's car never entered). Gated on event:void + an open shift
|
|
// (the booth accountability period). Refusals (subscription / already exited / already
|
|
// voided / already paid) → 409. See void-flow.ts, wiki/concepts/append-only-event-chain.md.
|
|
app.post<{ Body: VoidBody }>(
|
|
"/api/tickets/void",
|
|
{ preHandler: [voidGuard, requireShift] },
|
|
async (req, reply) => {
|
|
const identity = (req.body?.identity ?? "").trim();
|
|
const reason = (req.body?.reason ?? "").trim();
|
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
|
if (!reason) return reply.code(400).send({ error: "a cancellation reason is required" });
|
|
const operator = req.user?.username ?? "unknown";
|
|
const res = await voidFlow.voidTicket({ identity, reason, operator });
|
|
if (!res.ok) return reply.code(409).send({ error: res.reason });
|
|
return reply.code(201).send(res);
|
|
},
|
|
);
|
|
|
|
// Quote: what does this session owe right now? (No side effect.)
|
|
app.get<{ Querystring: QuoteQuery }>(
|
|
"/api/pay/quote",
|
|
{ preHandler: readGuard },
|
|
async (req, reply) => {
|
|
const identity = (req.query.identity ?? "").trim();
|
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
|
try {
|
|
return payStation.quote(identity);
|
|
} catch (err) {
|
|
return mapError(reply, err);
|
|
}
|
|
},
|
|
);
|
|
|
|
// Pay: take payment and append the signed `payment` event.
|
|
app.post<{ Body: PayBody }>(
|
|
"/api/pay",
|
|
{ preHandler: [guard, requireShift] },
|
|
async (req, reply) => {
|
|
const { identity, tender, overrideMinor } = req.body ?? {};
|
|
if (!identity || (tender !== "cash" && tender !== "card")) {
|
|
return reply.code(400).send({ error: "identity and tender (cash|card) required" });
|
|
}
|
|
if (overrideMinor != null && (!Number.isInteger(overrideMinor) || overrideMinor < 0)) {
|
|
return reply.code(400).send({ error: "overrideMinor must be a non-negative integer (minor units)" });
|
|
}
|
|
try {
|
|
const res = await payStation.pay(identity, tender, overrideMinor);
|
|
return reply.code(201).send(res);
|
|
} catch (err) {
|
|
return mapError(reply, err);
|
|
}
|
|
},
|
|
);
|
|
|
|
// Print an exit voucher (the paid ticket id reprinted as a barcode) on the booth
|
|
// printer. Used when the booth is far from the exit — the customer self-scans the
|
|
// voucher at the exit reader, which runs the normal validated exit. Requires the
|
|
// session to be PAID (no free vouchers for unpaid sessions). See booth-exit-flow.md.
|
|
app.post<{ Body: VoucherBody }>(
|
|
"/api/voucher",
|
|
{ preHandler: [guard, requireShift] },
|
|
async (req, reply) => {
|
|
const identity = (req.body?.identity ?? "").trim();
|
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
|
const view = payStation.lookup(identity);
|
|
if (!view.found || !view.open) {
|
|
return reply.code(404).send({ error: "no open session for ticket" });
|
|
}
|
|
if (view.paidAt == null) {
|
|
return reply.code(409).send({ error: "session not paid — take payment before printing a voucher" });
|
|
}
|
|
try {
|
|
const printedBy = await printPaymentReceipt(db, identity, { voucher: true }, app.log);
|
|
return reply.code(200).send({ ok: true, printedBy });
|
|
} catch (err) {
|
|
if (err instanceof NoPrinterAvailableError) {
|
|
return reply.code(503).send({ error: err.message });
|
|
}
|
|
return reply.code(500).send({ error: (err as Error).message });
|
|
}
|
|
},
|
|
);
|
|
|
|
// Print a standalone PAYMENT RECEIPT (transparency: entry/paid/duration/amount,
|
|
// no barcode) on the booth printer. Used (a) auto, right after a payment when no
|
|
// voucher is issued, and (b) on-demand "reprint" if the slip jammed. Requires the
|
|
// session to be PAID. See wiki/concepts/booth-exit-flow.md.
|
|
app.post<{ Body: ReceiptBody }>(
|
|
"/api/receipt",
|
|
{ preHandler: [guard, requireShift] },
|
|
async (req, reply) => {
|
|
const identity = (req.body?.identity ?? "").trim();
|
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
|
const view = payStation.lookup(identity);
|
|
if (!view.found) {
|
|
return reply.code(404).send({ error: "no session for ticket" });
|
|
}
|
|
if (view.paidAt == null) {
|
|
return reply.code(409).send({ error: "session not paid — nothing to receipt" });
|
|
}
|
|
try {
|
|
const printedBy = await printPaymentReceipt(db, identity, { voucher: false }, app.log);
|
|
return reply.code(200).send({ ok: true, printedBy });
|
|
} catch (err) {
|
|
if (err instanceof NoPrinterAvailableError) {
|
|
return reply.code(503).send({ error: err.message });
|
|
}
|
|
return reply.code(500).send({ error: (err as Error).message });
|
|
}
|
|
},
|
|
);
|
|
}
|
|
|
|
function mapError(reply: import("fastify").FastifyReply, err: unknown) {
|
|
if (err instanceof NoOpenSessionError) return reply.code(404).send({ error: err.message });
|
|
if (err instanceof NoTariffError) return reply.code(409).send({ error: err.message });
|
|
return reply.code(500).send({ error: (err as Error).message });
|
|
}
|