feat(exit): forgiven exit — open the exit barrier with no payment (barrier:create)
Build & push images / images (push) Successful in 3m23s

The owner (or any role the owner grants barrier:create) lets a car out for free.
Exit side only. Every use is signed, attributed, photographed and on the operator's
Z-report; the shift's cash/card/drawer are untouched by construction.

- shared: resource 'barrier' + permission 'barrier:create'; reason codes
  exit.forgiven / exit.forgiven.noSession; LedgerPayload.forgoneMinor.
- pay-station: forgive() signs a $0 payment carrying the quoted fee as forgoneMinor
  (no tender), refuses a ticket with module charge lines (a wash is not forgiven).
- exit-flow: reopenBarrier(..., { forgiven }) bypasses the walk-back check and stamps
  the forgiven reason on the anomaly + vehicle_exit; forgiveExitNoSession() for a car
  with no ticket (anomaly under forgiven:<id> + exit snapshot + pulse). Relay driving
  shared in #pulseExit.
- route POST /api/barrier/forgive { identity?, note? }: barrier:create + open shift;
  the reason is optional (an empty note is signed as '(no reason given)').
- shift-service: forgoneTotalMinor + forgoneCount on the report/summary/signed
  shift_z_report (only when > 0), print line 'Dalje të falura (N)'.
- web: 'Forgive & open' in the pay/exit modal for an open transient that owes money;
  'Forgive & open exit' on the booth header for the no-ticket case; forgone line on
  the X-report, close confirm and history; en/sq. Prints nothing.
- tests: exit-flow, pay-station, shift-service, HTTP route (403 without the
  permission, 409 no shift, empty note accepted, ledger sequence, report figures).
- wiki: decisions/forgiven-exit.md (decision + as-built), booth-exit-flow, shift,
  index, log.
This commit is contained in:
2026-10-09 08:14:36 +02:00
parent 5d247a5729
commit a761398301
21 changed files with 710 additions and 26 deletions
@@ -0,0 +1,86 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { FastifyInstance } from "fastify";
import { createTestDb } from "@parking/db/testing";
import { ledgerEvents, eq, type Db } from "@parking/db";
import { buildServer } from "../server.js";
import { login, makeLog, minutesAgo, seedTariff, seedUser } from "../test-helpers.js";
// HTTP integration for the FORGIVEN exit (wiki/decisions/forgiven-exit.md): the route is
// gated on `barrier:create` (admin by default, grantable per role), needs an open shift
// and a reason, and signs a $0 payment carrying the forgone fee + the exit. Drives the
// REAL app over a fresh in-memory DB via app.inject.
let db: Db;
let close: () => void;
let app: FastifyInstance;
beforeEach(async () => {
const t = createTestDb();
db = t.db;
close = t.close;
app = await buildServer({ db });
await app.ready();
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60 });
});
afterEach(async () => {
await app.close();
close();
});
async function as(opts: { username: string; roleId?: string; permissions?: Parameters<typeof seedUser>[1]["permissions"] }) {
const { username, password } = await seedUser(db, opts);
const { cookie, csrf } = await login(app, username, password);
return { cookie, "x-csrf-token": csrf };
}
async function enter(identity: string) {
await makeLog(db).append({ type: "vehicle_entry", direction: "entry", identity, occurredAt: minutesAgo(90), payload: null });
}
function events(identity: string) {
return db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).all();
}
describe("POST /api/barrier/forgive", () => {
it("is refused without barrier:create (an operator who can take payment but was not granted it)", async () => {
const h = await as({ username: "op", roleId: "operator", permissions: ["payment:create", "session:read", "shift:create"] });
await app.inject({ method: "POST", url: "/api/shift/open", headers: h, payload: {} });
await enter("T1");
const r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: { identity: "T1", note: "friend" } });
expect(r.statusCode).toBe(403);
expect(events("T1").map((e) => e.type)).toEqual(["vehicle_entry"]);
});
it("a role the owner granted barrier:create can forgive; the reason is optional; a shift must be open", async () => {
const h = await as({ username: "trusted", roleId: "senior", permissions: ["payment:create", "session:read", "shift:create", "shift:read", "barrier:create"] });
await enter("T1");
// No shift yet → the money-path gate refuses.
let r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: { identity: "T1", note: "x" } });
expect(r.statusCode).toBe(409);
expect(r.json()).toMatchObject({ code: "no_shift" });
await app.inject({ method: "POST", url: "/api/shift/open", headers: h, payload: {} });
// Forgiven: $0 payment with the fee as forgone, then the exit. No relay configured →
// ok:true, opened:false with the open-by-hand reason (the ledger side is complete).
r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: { identity: "T1", note: "known customer, lost ticket" } });
expect(r.statusCode).toBe(200);
expect(r.json()).toMatchObject({ ok: true, opened: false, forgoneMinor: 20000 });
const types = events("T1").map((e) => e.type);
expect(types).toEqual(["vehicle_entry", "payment", "anomaly", "vehicle_exit"]);
const payment = events("T1").find((e) => e.type === "payment")!;
expect(payment.payload).toMatchObject({ amountMinor: 0, forgoneMinor: 20000, operator: "trusted", reasonCode: "exit.forgiven" });
// The Z-report carries it as its own line, and the takings stay at zero.
const rep = (await app.inject({ method: "GET", url: "/api/shift/report", headers: h })).json() as Record<string, unknown>;
expect(rep).toMatchObject({ cashTotalMinor: 0, cardTotalMinor: 0, forgoneTotalMinor: 20000, forgoneCount: 1 });
});
it("no ticket, no reason: admin opens the exit for a car with no session → anomaly only, readable sentence", async () => {
const h = await as({ username: "boss", roleId: "admin" });
await app.inject({ method: "POST", url: "/api/shift/open", headers: h, payload: {} });
const r = await app.inject({ method: "POST", url: "/api/barrier/forgive", headers: h, payload: {} });
expect(r.statusCode).toBe(200);
const all = db.select().from(ledgerEvents).all();
const anomaly = all.find((e) => e.type === "anomaly")!;
expect(anomaly.identity).toMatch(/^forgiven:/);
expect(anomaly.payload).toMatchObject({ reasonCode: "exit.forgiven.noSession", operator: "boss" });
expect((anomaly.payload as { reason: string }).reason).toContain("(no reason given)");
expect(all.filter((e) => e.type === "payment" || e.type === "vehicle_exit")).toHaveLength(0);
});
});
+32
View File
@@ -60,6 +60,7 @@ export async function payRoutes(
const guard = requirePermission("payment:create");
const readGuard = requirePermission("session:read");
const voidGuard = requirePermission("event:void");
const forgiveGuard = requirePermission("barrier:create");
// 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
@@ -144,6 +145,37 @@ export async function payRoutes(
},
);
// FORGIVEN exit (wiki/decisions/forgiven-exit.md): an operator holding barrier:create
// lets a car out with NO money. With a ticket: PayStation.forgive signs a $0 payment
// carrying the forgone fee (never in cash/card), then the human-intervention re-open
// signs the exit + pulses. Without a ticket: anomaly + snapshot + pulse. A free-text
// reason is OPTIONAL (user, 2026-10-09 — the signature + snapshot + Z-report line are
// the accountability); an open shift is required so it lands on someone's Z-report.
// Prints nothing.
app.post<{ Body: { identity?: string; note?: string } }>(
"/api/barrier/forgive",
{ preHandler: [forgiveGuard, requireShift] },
async (req, reply) => {
const note = (req.body?.note ?? "").trim();
const identity = (req.body?.identity ?? "").trim();
const operator = req.user?.username ?? "?";
if (!identity) {
const r = await exitFlow.forgiveExitNoSession(operator, note);
if (!r.ok) return reply.code(409).send({ error: r.reason });
return reply.code(200).send(r);
}
try {
const f = await payStation.forgive(identity, { operator, note });
if (!f.ok) return reply.code(409).send({ error: f.reason });
const r = await exitFlow.reopenBarrier(identity, operator, { forgiven: { note, forgoneMinor: f.forgoneMinor, currency: f.currency } });
if (!r.ok) return reply.code(409).send({ error: r.reason });
return reply.code(200).send({ ...r, forgoneMinor: f.forgoneMinor, currency: f.currency });
} catch (err) {
return mapError(reply, err);
}
},
);
// 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,