diff --git a/apps/server/src/exit-flow.test.ts b/apps/server/src/exit-flow.test.ts index 3ca93c0..e190a67 100644 --- a/apps/server/src/exit-flow.test.ts +++ b/apps/server/src/exit-flow.test.ts @@ -111,6 +111,44 @@ describe("exitForBooth — valid exit signs the vehicle_exit", () => { }); }); +describe("forgiven exit (wiki/decisions/forgiven-exit.md)", () => { + function payments(identity: string) { + return db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).all().filter((r) => r.type === "payment"); + } + + it("ticketed car: $0 payment carrying the forgone fee, then the exit is signed with the forgiven reason", async () => { + seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60, gracePeriodExitMin: 0 }); + await enter("T1", minutesAgo(90)); // 2 increments → 20000 owed + const f = await pay.forgive("T1", { operator: "owner", note: "regular customer, printer jammed" }); + expect(f).toMatchObject({ ok: true, forgoneMinor: 20000 }); + const p = payments("T1"); + expect(p).toHaveLength(1); + expect(p[0]!.payload).toMatchObject({ amountMinor: 0, forgoneMinor: 20000, operator: "owner", reasonCode: "exit.forgiven" }); + expect((p[0]!.payload as { reason: string }).reason).toContain("regular customer, printer jammed"); + + // Even with a 0-minute walk-back grace, the forgiven re-open goes through. + const r = await exit.reopenBarrier("T1", "owner", { forgiven: { note: "regular customer, printer jammed", forgoneMinor: 20000, currency: "ALL" } }); + expect(r.ok).toBe(true); + expect(exitsSigned("T1")).toHaveLength(1); + expect(exitsSigned("T1")[0]!.payload).toMatchObject({ reasonCode: "exit.forgiven" }); + expect(anomalies("forgiven exit by owner")).toHaveLength(1); + expect(anomalies("forgiven exit by owner")[0]!.payload).toMatchObject({ forgiven: true, forgoneMinor: 20000, operator: "owner" }); + // The plain unpaid re-open path is still refused for the NEXT unpaid car. + await enter("T2", minutesAgo(90)); + expect((await exit.reopenBarrier("T2", "owner")).ok).toBe(false); + }); + + it("no session: a signed anomaly under a fresh forgiven: ref, no exit, no payment", async () => { + const r = await exit.forgiveExitNoSession("owner", "came in while the barriers were up"); + expect(r.ok).toBe(true); + const a = anomalies("no ticket / no session"); + expect(a).toHaveLength(1); + expect(a[0]!.identity).toMatch(/^forgiven:/); + expect(a[0]!.payload).toMatchObject({ reasonCode: "exit.forgiven.noSession", forgiven: true, operator: "owner" }); + expect(db.select().from(ledgerEvents).all().filter((e) => e.type === "payment" || e.type === "vehicle_exit")).toHaveLength(0); + }); +}); + describe("reopenBarrier — no unpaid re-open", () => { it("refuses to re-open an unpaid transient session", async () => { seedTariff(db, { pricePerIncrementMinor: 10000 }); diff --git a/apps/server/src/exit-flow.ts b/apps/server/src/exit-flow.ts index ee0f5fa..e8dddd4 100644 --- a/apps/server/src/exit-flow.ts +++ b/apps/server/src/exit-flow.ts @@ -1,3 +1,4 @@ +import { randomUUID } from "node:crypto"; import { desc, eq, ledgerEvents, sessions, tariffVersions, tariffs, type Db, type DeviceRow } from "@parking/db"; import { registry, type AccessControlDevice } from "@parking/devices"; import { firstRelayByDirection, type ResolvedRelay } from "./device-resolve.js"; @@ -63,6 +64,14 @@ export type BoothReopenResult = | { ok: false; reason: string } | { ok: true; opened: boolean; reason?: string }; +/** A forgiven exit's audit facts (wiki/decisions/forgiven-exit.md): the operator's + * mandatory free-text note and the fee the $0 payment just waived. */ +export interface ForgivenExit { + readonly note: string; + readonly forgoneMinor: number; + readonly currency: string; +} + /** Minimum ANPR confidence for a plate to participate in swap reconciliation, both for the * exiting read and the matched open session's entry read. Below this, the read is advisory- * only and never triggers a swap warning (a fuzzy read must not block a legit car). */ @@ -234,9 +243,10 @@ export class ExitFlow { * second exit (that would double-count occupancy): anomaly only, as before. * See wiki/concepts/booth-exit-flow.md. */ - async reopenBarrier(identity: string, operator?: string): Promise { + async reopenBarrier(identity: string, operator?: string, opts?: { forgiven?: ForgivenExit }): Promise { const id = identity.trim(); if (!id) return { ok: false, reason: "ticket id required" }; + const forgiven = opts?.forgiven ?? null; const view = this.#sessionFor(id); if (!view) return { ok: false, reason: "no session for ticket" }; @@ -251,7 +261,10 @@ export class ExitFlow { const paid = view.paidAt != null; const withinGrace = paid && view.graceExitMin != null && Date.now() - Date.parse(view.paidAt!) <= view.graceExitMin * 60_000; - if (!view.subscription && (!paid || !withinGrace)) { + // FORGIVEN exit (barrier:create): the $0 payment carrying the forgone fee was just + // signed by PayStation.forgive(); the walk-back check is moot (and a 0-minute grace + // tariff must not refuse it). The audit lives on the anomaly + exit below. + if (!forgiven && !view.subscription && (!paid || !withinGrace)) { return { ok: false, reason: paid ? "walk-back grace expired — take a top-up payment first" : "session not paid — no barrier open without payment", @@ -269,9 +282,10 @@ export class ExitFlow { type: "anomaly", identity: id, payload: { - ...reasonPayload("exit.manualOpen"), + ...(forgiven ? reasonPayload("exit.forgiven", this.#forgivenParams(operator, forgiven)) : reasonPayload("exit.manualOpen")), source: "booth", barrierReopen: true, + ...(forgiven ? { forgiven: true, forgoneMinor: forgiven.forgoneMinor, currency: forgiven.currency } : {}), ...(operator ? { operator } : {}), }, }); @@ -280,34 +294,82 @@ export class ExitFlow { // session leaves the active list + occupancy settles. Skip when already exited // (no double-count). Recorded as a human-intervention exit for the audit trail. if (view.open) { - await this.#signExit(id, "manual"); + await this.#signExit(id, "manual", forgiven ? reasonPayload("exit.forgiven", this.#forgivenParams(operator, forgiven)) : undefined); this.#closeSessionCache(id); this.#fireExitSnapshot(id); this.#logger.info(`barrier re-open also closed open session ${id} (human-intervention exit)`); } - if (!resolved) { - this.#logger.warn(`barrier re-open for ${id}: no exit relay configured`); - return { ok: true, opened: false, reason: renderReasonEn("exit.open.noBarrier") }; + const r = await this.#pulseExit(resolved, `barrier re-open for ${id}`); + if (r.opened) { + if (forgiven) this.#logger.warn(`FORGIVEN exit barrier open for ${id} by ${operator ?? "?"}: ${forgiven.note}`); + else this.#logger.info(`manual barrier open for ${id}${operator ? ` by ${operator}` : ""}`); } - const access = this.#buildAccess(resolved.controller); - if (!access) { - this.#logger.warn(`barrier re-open for ${id}: exit controller would not build`); - return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") }; - } - try { - await access.pulseOpen(resolved.relay); - } catch (err) { - this.#logger.error(`barrier re-open pulseOpen failed (${id}): ${(err as Error).message}`); - return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") }; - } - this.#logger.info(`manual barrier open for ${id}${operator ? ` by ${operator}` : ""}`); - return { ok: true, opened: true }; + return r; } finally { this.#inFlight.delete(key); } } + /** + * FORGIVEN exit for a car with NO ticket / no session (it came in while the barriers + * were up, lost everything, …). Nothing to forgive and nothing to close: a signed, + * attributed anomaly with the exit snapshot as evidence, then the pulse. The anomaly's + * identity is a fresh `forgiven:` ref so the live feed can show its snapshot. + * See wiki/decisions/forgiven-exit.md. + */ + async forgiveExitNoSession(operator: string, note: string): Promise { + const key = "forgive:nosession"; + if (this.#inFlight.has(key)) return { ok: false, reason: "a forgiven open is already in progress" }; + this.#inFlight.add(key); + try { + const ref = `forgiven:${randomUUID()}`; + const resolved = firstRelayByDirection(this.#db, "exit"); + await this.#log.append({ + type: "anomaly", + identity: ref, + payload: { + ...reasonPayload("exit.forgiven.noSession", { operator, note: note || "(no reason given)" }), + source: "booth", + barrierReopen: true, + forgiven: true, + operator, + }, + }); + this.#fireExitSnapshot(ref); + const r = await this.#pulseExit(resolved, `forgiven open (no session) ${ref}`); + if (r.opened) this.#logger.warn(`FORGIVEN exit barrier open with no session by ${operator}: ${note}`); + return r; + } finally { + this.#inFlight.delete(key); + } + } + + /** Drive the exit relay for a human-intervention open; the exit/anomaly is already + * signed, so every failure is `ok: true, opened: false` + the reason to open by hand. */ + async #pulseExit(resolved: ResolvedRelay | null, label: string): Promise> { + if (!resolved) { + this.#logger.warn(`${label}: no exit relay configured`); + return { ok: true, opened: false, reason: renderReasonEn("exit.open.noBarrier") }; + } + const access = this.#buildAccess(resolved.controller); + if (!access) { + this.#logger.warn(`${label}: exit controller would not build`); + return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") }; + } + try { + await access.pulseOpen(resolved.relay); + } catch (err) { + this.#logger.error(`${label}: pulseOpen failed: ${(err as Error).message}`); + return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") }; + } + return { ok: true, opened: true }; + } + + #forgivenParams(operator: string | undefined, f: ForgivenExit): Record { + return { operator: operator ?? "?", forgone: (f.forgoneMinor / 100).toFixed(2), currency: f.currency, note: f.note || "(no reason given)" }; + } + /** Handle a transient-ticket read at an exit barrier (the relay pre-resolved by the * read dispatcher from the reader's binding, which has ruled out a subscription match). */ async handleAt(resolved: ResolvedRelay, e: DeviceReadEvent): Promise { @@ -422,7 +484,11 @@ export class ExitFlow { /** Append the signed vehicle_exit. `source`: "ticket" (booth/reader), "lpr" (plate), * or "manual" (a human-intervention barrier re-open that closes an open session — * see reopenBarrier). */ - async #signExit(identity: string, source: "ticket" | "lpr" | "manual" = "ticket"): Promise { + async #signExit( + identity: string, + source: "ticket" | "lpr" | "manual" = "ticket", + reason?: ReturnType, + ): Promise { await this.#log.append({ type: "vehicle_exit", direction: "exit", @@ -430,7 +496,7 @@ export class ExitFlow { identity, payload: { sessionRef: identity, - ...(source === "manual" ? reasonPayload("exit.manualOpen") : {}), + ...(reason ?? (source === "manual" ? reasonPayload("exit.manualOpen") : {})), }, }); } diff --git a/apps/server/src/pay-station.test.ts b/apps/server/src/pay-station.test.ts index e91436e..159d43a 100644 --- a/apps/server/src/pay-station.test.ts +++ b/apps/server/src/pay-station.test.ts @@ -28,6 +28,24 @@ async function enter(identity: string, enteredAt: string, payload?: Record { + it("signs a $0 payment with the quoted fee as forgoneMinor and marks the session paid", async () => { + seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60 }); + await enter("T1", minutesAgo(90)); + const r = await pay.forgive("T1", { operator: "owner", note: "lost ticket, known customer" }); + expect(r).toEqual({ ok: true, forgoneMinor: 20000, currency: expect.any(String) }); + const ev = db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, "T1")).all().find((e) => e.type === "payment")!; + expect(ev.payload).toMatchObject({ amountMinor: 0, forgoneMinor: 20000, operator: "owner", reasonCode: "exit.forgiven" }); + expect((ev.payload as { tender?: string }).tender).toBeUndefined(); // nothing was tendered + expect(pay.lookup("T1").paidAt).not.toBeNull(); + }); + + it("throws like quote() for an unknown ticket", async () => { + seedTariff(db); + await expect(pay.forgive("nope", { operator: "owner", note: "x" })).rejects.toThrow(NoOpenSessionError); + }); +}); + describe("PayStation.quote", () => { it("throws NoOpenSessionError for an unknown ticket", () => { seedTariff(db); diff --git a/apps/server/src/pay-station.ts b/apps/server/src/pay-station.ts index 6950a52..0105ace 100644 --- a/apps/server/src/pay-station.ts +++ b/apps/server/src/pay-station.ts @@ -1,5 +1,5 @@ import { desc, eq, ledgerEvents, sessions, subscriptions, tariffVersions, tariffs, type Db } from "@parking/db"; -import { BOOTH_TILL, priceSession, type ChargeLine, type TariffStructure, type Tender, type ValidationLine } from "@parking/shared"; +import { BOOTH_TILL, priceSession, reasonPayload, type ChargeLine, type TariffStructure, type Tender, type ValidationLine } from "@parking/shared"; import type { FastifyBaseLogger } from "fastify"; import type { EventLog } from "./event-log.js"; import { plateForIdentity, platesForIdentities } from "./plate-lookup.js"; @@ -373,6 +373,53 @@ export class PayStation { return { amountMinor, currency: q.currency }; } + /** + * FORGIVEN EXIT (wiki/decisions/forgiven-exit.md): the owner lets a ticketed car out + * with no money. Signs a ZERO-amount payment that carries the fee the car owed as + * `forgoneMinor`, so the shift's cash/card/drawer are untouched by construction while + * the Z-report shows the forgone amount as its own line; the exit that follows closes + * the ticket (no reuse). Refused when the quote carries module charge lines (a wash on + * the ticket): parking is forgiven, a wash is not — settle it first. Throws + * NoOpenSessionError / NoTariffError like `quote()`. + */ + async forgive( + identity: string, + opts: { operator: string; note: string }, + ): Promise<{ ok: true; forgoneMinor: number; currency: string } | { ok: false; reason: string }> { + const q = this.quote(identity); + if (q.chargesMinor > 0) { + return { ok: false, reason: "ticket carries a module charge (e.g. a wash) — settle it first; only parking can be forgiven" }; + } + await this.#log.append({ + type: "payment", + source: "manual", + identity, + payload: { + sessionRef: identity, + amountMinor: 0, + forgoneMinor: q.amountMinor, + currency: q.currency, + till: BOOTH_TILL, + tariffVersionId: q.tariffVersionId, + graceExitMin: q.graceExitMin, + operator: opts.operator, + ...reasonPayload("exit.forgiven", { + operator: opts.operator, + forgone: (q.amountMinor / 100).toFixed(2), + currency: q.currency, + note: opts.note || "(no reason given)", + }), + }, + }); + try { + this.#db.update(sessions).set({ state: "paid" }).where(eq(sessions.id, identity)).run(); + } catch (err) { + this.#logger.error(`session-cache mark-paid failed for ${identity}: ${(err as Error).message}`); + } + this.#logger.warn(`FORGIVEN exit for ${identity} by ${opts.operator}: ${q.amountMinor} ${q.currency} waived — ${opts.note}`); + return { ok: true, forgoneMinor: q.amountMinor, currency: q.currency }; + } + /** * One-read session view for the booth pay/exit modal: entry/exit times, paid * state, amount owed now, and walk-back-grace status. Read-only — folds the diff --git a/apps/server/src/routes/forgive-exit.test.ts b/apps/server/src/routes/forgive-exit.test.ts new file mode 100644 index 0000000..b685eef --- /dev/null +++ b/apps/server/src/routes/forgive-exit.test.ts @@ -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[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; + 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); + }); +}); diff --git a/apps/server/src/routes/pay.ts b/apps/server/src/routes/pay.ts index 2489b02..62ed37b 100644 --- a/apps/server/src/routes/pay.ts +++ b/apps/server/src/routes/pay.ts @@ -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, diff --git a/apps/server/src/shift-service.test.ts b/apps/server/src/shift-service.test.ts index f20e36b..5256a2e 100644 --- a/apps/server/src/shift-service.test.ts +++ b/apps/server/src/shift-service.test.ts @@ -34,12 +34,14 @@ afterEach(() => close()); /** Append a signed payment with source-split flags, as the booth/pay paths do. */ async function payment( amountMinor: number, - opts: { tender?: "cash" | "card"; subscriptionSale?: boolean; subscriptionWindowCharge?: boolean } = {}, + opts: { tender?: "cash" | "card"; subscriptionSale?: boolean; subscriptionWindowCharge?: boolean; forgoneMinor?: number } = {}, ) { await log.append({ type: "payment", source: "manual", identity: "T", payload: { - sessionRef: "T", amountMinor, currency: "ALL", tender: opts.tender ?? "cash", + sessionRef: "T", amountMinor, currency: "ALL", + // A forgiven exit's $0 payment carries no tender (nothing was tendered). + ...(opts.forgoneMinor != null ? { forgoneMinor: opts.forgoneMinor } : { tender: opts.tender ?? "cash" }), ...(opts.subscriptionSale ? { subscriptionSale: true } : {}), ...(opts.subscriptionWindowCharge ? { subscriptionWindowCharge: true } : {}), }, @@ -74,6 +76,29 @@ describe("single-open invariant", () => { }); }); +describe("forgiven exits on the Z-report", () => { + it("a $0 forgiven payment adds nothing to cash/card/drawer and is reported as its own line", async () => { + await shift.open("alice"); + await payment(10000); // a real ticket, cash + await payment(0, { forgoneMinor: 25000 }); + await payment(0, { forgoneMinor: 5000 }); + + const r = shift.currentReport()!; + expect(r.cashTotalMinor).toBe(10000); + expect(r.cardTotalMinor).toBe(0); + expect(r.ticketTotalMinor).toBe(10000); + expect(r.forgoneTotalMinor).toBe(30000); + expect(r.forgoneCount).toBe(2); + expect(r.discountTotalMinor).toBe(0); // not a merchant validation + expect(r.expectedDrawerMinor).toBe(r.openingFloatMinor + 10000); + + const closed = await shift.close("alice"); + expect(closed).toMatchObject({ forgoneTotalMinor: 30000, forgoneCount: 2, cashTotalMinor: 10000 }); + const hist = shift.listShifts(); + expect(hist[0]).toMatchObject({ forgoneTotalMinor: 30000, forgoneCount: 2 }); + }); +}); + describe("takings split by source", () => { it("separates subscription sales, out-of-window charges, and transient tickets", async () => { await shift.open("alice"); diff --git a/apps/server/src/shift-service.ts b/apps/server/src/shift-service.ts index 51a56a0..fe5b20a 100644 --- a/apps/server/src/shift-service.ts +++ b/apps/server/src/shift-service.ts @@ -71,6 +71,8 @@ export interface ShiftSummary { readonly subscriptionSalesMinor: number; readonly subscriptionWindowMinor: number; readonly discountTotalMinor: number; + readonly forgoneTotalMinor: number; + readonly forgoneCount: number; readonly chargesByModuleMinor: ChargesByModule; readonly openingFloatMinor: number; readonly cashAddedMinor: number; @@ -105,6 +107,10 @@ export interface ShiftReport { /** Merchant-validation DISCOUNT total given away in the window (leakage — the * cash/card figures above are already NET of it). See validation-discounts.md. */ readonly discountTotalMinor: number; + /** FORGIVEN exits (wiki/decisions/forgiven-exit.md): fees waived by an operator holding + * barrier:create, and how many. $0 payments — never inside cash/card; its own line. */ + readonly forgoneTotalMinor: number; + readonly forgoneCount: number; /** Module charges settled on this till's payments (a booth-paid wash), by module. */ readonly chargesByModuleMinor: ChargesByModule; // --- Drawer (physical cash till; carries across shifts) --- @@ -266,6 +272,8 @@ export class ShiftService { subscriptionSalesMinor?: number; subscriptionWindowMinor?: number; discountTotalMinor?: number; + forgoneTotalMinor?: number; + forgoneCount?: number; chargesByModuleMinor?: ChargesByModule; openingFloatMinor?: number; cashAddedMinor?: number; @@ -302,6 +310,9 @@ export class ShiftService { (pl.cashTotalMinor ?? 0) + (pl.cardTotalMinor ?? 0) - (pl.subscriptionTotalMinor ?? 0), // Merchant-validation leakage (added 2026-07-13). Old reports lack it → 0. discountTotalMinor: pl.discountTotalMinor ?? 0, + // Forgiven exits (added 2026-10-08). Old reports lack it → 0. + forgoneTotalMinor: pl.forgoneTotalMinor ?? 0, + forgoneCount: pl.forgoneCount ?? 0, // Module charges on the ticket (added 2026-09-06). Old reports lack it → none. chargesByModuleMinor: pl.chargesByModuleMinor ?? {}, openingFloatMinor: pl.openingFloatMinor ?? 0, @@ -599,6 +610,10 @@ export class ShiftService { // Merchant-validation leakage: Σ discountMinor across the window's payments. The // tender totals are already NET; this is the "given away" figure beside them. let discountTotalMinor = 0; + // Forgiven exits: $0 payments whose `forgoneMinor` is the fee waived. Not money — + // the tender sums above add 0 for them; this is the "let out for free" figure. + let forgoneTotalMinor = 0; + let forgoneCount = 0; // Module charges folded into this till's payments (chargeLines on a booth payment), // summed by owning module. Part of cash/card; NOT ticket money. const chargesByModuleMinor: ChargesByModule = {}; @@ -617,6 +632,10 @@ export class ShiftService { else if (pl.subscriptionWindowCharge === true) subscriptionWindowMinor += amt; // (else → transient ticket; derived below as total − subscription) if (typeof pl.discountMinor === "number") discountTotalMinor += pl.discountMinor; + if (typeof pl.forgoneMinor === "number") { + forgoneTotalMinor += pl.forgoneMinor; + forgoneCount += 1; + } for (const l of pl.chargeLines ?? []) { if (typeof l.amountMinor !== "number" || !l.module) continue; chargesByModuleMinor[l.module] = (chargesByModuleMinor[l.module] ?? 0) + l.amountMinor; @@ -682,6 +701,8 @@ export class ShiftService { subscriptionSalesMinor, subscriptionWindowMinor, discountTotalMinor, + forgoneTotalMinor, + forgoneCount, chargesByModuleMinor, openingFloatMinor, cashAddedMinor, @@ -723,6 +744,8 @@ export class ShiftService { subscriptionSalesMinor, subscriptionWindowMinor, discountTotalMinor, + forgoneTotalMinor, + forgoneCount, chargesByModuleMinor, openingFloatMinor, cashAddedMinor, @@ -748,6 +771,8 @@ export class ShiftService { subscriptionSalesMinor, subscriptionWindowMinor, discountTotalMinor, + // Forgiven exits — only when any happened (older payloads stay identical). + ...(forgoneCount > 0 ? { forgoneTotalMinor, forgoneCount } : {}), // Only when a module charged in the window (older slips/payloads stay identical). ...(Object.keys(chargesByModuleMinor).length ? { chargesByModuleMinor } : {}), openingFloatMinor, @@ -806,6 +831,8 @@ export class ShiftService { // Merchant-validation leakage — printed only when the shift actually gave any // (older slips stay byte-identical). The takings above are already NET of it. ...(r.discountTotalMinor > 0 ? [`Zbritje (validime): ${money(r.discountTotalMinor)} ${cur}`] : []), + // Forgiven exits — fees waived by an operator; $0 payments, NOT in the takings. + ...(r.forgoneCount > 0 ? [`Dalje të falura (${r.forgoneCount}): ${money(r.forgoneTotalMinor)} ${cur}`] : []), "", "-- Arka --", `Gjëndje fillestare: ${money(r.openingFloatMinor)} ${cur}`, diff --git a/apps/web/src/BoothPayModal.tsx b/apps/web/src/BoothPayModal.tsx index 1c12787..4b18f6b 100644 --- a/apps/web/src/BoothPayModal.tsx +++ b/apps/web/src/BoothPayModal.tsx @@ -6,6 +6,7 @@ import { boothExit, can, fetchSiteConfig, + forgiveExit, lookupSession, openShift, paySession, @@ -61,6 +62,12 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose const { user } = rootRoute.useRouteContext(); const canVoid = can(user, "event:void"); const [voiding, setVoiding] = useState(false); // reason prompt revealed + // FORGIVEN exit (barrier:create; wiki/decisions/forgiven-exit.md): let the car out with + // NO payment. The fee owed is signed as forgone on a $0 payment — on the shift report + // as its own line, never as cash. Reason optional; nothing printed. + const canForgivePerm = can(user, "barrier:create"); + const [forgiving, setForgiving] = useState(false); // reason prompt revealed + const [forgiveNote, setForgiveNote] = useState(""); // Plate-swap: set when boothExit returns swap_suspected. Holds the detail for the warning // panel; the operator must consciously "Override & release". See plate-reconciliation.md. const [swap, setSwap] = useState<{ plate: string; otherIdentity: string; otherEnteredAt: string | null } | null>(null); @@ -150,6 +157,31 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose // session (a subscription is closed via its own flow; a paid ticket is a refund). The // server enforces all of this too; the UI just hides the action when it can't apply. const canCancel = !!(canVoid && shiftReady && s?.found && s.open && !isSubscription && !alreadyPaid); + // Forgivable = an OPEN transient that owes money now (unpaid, or an overstay top-up). + // A paid-within-grace car takes the plain re-open; a subscriber the assist path. + const canForgive = !!(canForgivePerm && shiftReady && s?.found && s.open && !isSubscription && (!alreadyPaid || isOverstay)); + + async function handleForgiveExit() { + const note = forgiveNote.trim(); // optional + setError(null); + setPhase("finishing"); + try { + const r = await forgiveExit(identity, note); + const amount = formatMoney(r.forgoneMinor ?? 0, r.currency ?? s?.currency ?? ""); + setResult( + r.opened + ? t("pay.exitForgiven", { amount }) + : t("pay.exitForgivenNotOpened", { amount, reason: r.reason ?? t("booth.openManually") }), + ); + void qc.invalidateQueries({ queryKey: qk.events }); + void qc.invalidateQueries({ queryKey: qk.occupancy }); + void qc.invalidateQueries({ queryKey: qk.activeSessions }); + setPhase("done"); + } catch (e) { + setError((e as Error).message); + setPhase("error"); + } + } async function handleVoidTicket() { const reason = voidReason.trim(); @@ -556,6 +588,26 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose )} + {/* Forgiven-exit reason prompt (revealed by the "Forgive & open" button). + Free text, OPTIONAL. Signs a $0 payment carrying the forgone fee, then + the exit + barrier pulse. Nothing is printed. */} + {forgiving && phase !== "done" && ( +
+
+ {t("pay.forgiveTitle")} +
+
+ {t("pay.forgiveHint", { amount: formatMoney(s?.amountMinor ?? 0, s?.currency ?? "") })} +
+ setForgiveNote(e.target.value)} + placeholder={t("pay.forgiveReasonPlaceholder")} + /> +
+ )} + {/* PLATE-SWAP warning: the exiting plate is already inside under another ticket. A prominent, deliberate hold — the operator must consciously override to release. See wiki/concepts/plate-reconciliation.md. */} @@ -661,6 +713,16 @@ export function BoothPayModal({ identity, onClose }: { identity: string; onClose {t("pay.assistOpenReveal")} ) + ) : forgiving ? ( + // Forgiven-exit confirm (reason prompt is shown above). + ) : voiding ? ( // Cancel-ticket confirm (reason prompt is shown above). + )} {swap ? ( // Plate-swap held → the only forward action is a conscious // override (re-submit with override:true; payment already taken). diff --git a/apps/web/src/BoothScreen.tsx b/apps/web/src/BoothScreen.tsx index 224bc0d..84c067a 100644 --- a/apps/web/src/BoothScreen.tsx +++ b/apps/web/src/BoothScreen.tsx @@ -1,7 +1,7 @@ import { useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { can, fetchEvents, fetchOccupancy, fetchSiteConfig, issueEntryTicket, type LedgerEvent, type Occupancy } from "./api.js"; +import { can, fetchEvents, fetchOccupancy, fetchSiteConfig, forgiveExit, issueEntryTicket, type LedgerEvent, type Occupancy } from "./api.js"; import { rootRoute } from "./router.js"; import { qk } from "./lib/query.js"; import { useLiveStore } from "./lib/live-store.js"; @@ -216,6 +216,27 @@ function LaneIndicators() { if (window.confirm(t("booth.issueEntryConfirm"))) issue.mutate(); } + // FORGIVEN exit for a car with NO ticket (barrier:create; wiki/decisions/forgiven-exit.md): + // signed anomaly + exit snapshot + pulse, no money, nothing printed. Reason optional + // (Cancel in the prompt aborts; an empty answer proceeds). + const canForgive = can(user, "barrier:create") && shiftOpen && isMine; + const forgive = useMutation({ + mutationFn: (note: string) => forgiveExit(null, note), + onSuccess: (r) => { + setMsg({ ok: r.opened, text: r.opened ? t("booth.forgiveExitOk") : t("booth.forgiveExitNotOpened", { reason: r.reason ?? "" }) }); + void qc.invalidateQueries({ queryKey: qk.events }); + setTimeout(() => setMsg(null), 5000); + }, + onError: (e) => { + setMsg({ ok: false, text: (e as Error).message }); + setTimeout(() => setMsg(null), 5000); + }, + }); + function onForgiveNoTicket() { + const note = window.prompt(t("booth.forgiveExitPrompt")); + if (note !== null) forgive.mutate(note.trim()); + } + return (
+ {canForgive && ( + + )} {msg && ( {msg.text} )} diff --git a/apps/web/src/ShiftControl.tsx b/apps/web/src/ShiftControl.tsx index 4bd66b6..724f32b 100644 --- a/apps/web/src/ShiftControl.tsx +++ b/apps/web/src/ShiftControl.tsx @@ -174,6 +174,13 @@ function CloseShiftConfirm({ part is broken out below it; subscription SALES is not (it's the remainder). */} + {/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */} + {(x.forgoneCount ?? 0) > 0 && ( + <> + + + + )} )}
diff --git a/apps/web/src/ShiftsHistory.tsx b/apps/web/src/ShiftsHistory.tsx index 62324ef..ad1a0b9 100644 --- a/apps/web/src/ShiftsHistory.tsx +++ b/apps/web/src/ShiftsHistory.tsx @@ -92,6 +92,8 @@ function useCurrentShifts(): { current: CurrentShift[]; tills: TillId[]; workabl subscriptionSalesMinor: x.subscriptionSalesMinor, subscriptionWindowMinor: x.subscriptionWindowMinor, chargesByModuleMinor: x.chargesByModuleMinor, + forgoneTotalMinor: x.forgoneTotalMinor, + forgoneCount: x.forgoneCount, openingFloatMinor: x.openingFloatMinor, cashAddedMinor: x.cashAddedMinor, cashRemovedMinor: x.cashRemovedMinor, @@ -409,6 +411,10 @@ function ShiftActivityLog({
{/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
+ {/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */} + {(shift.forgoneCount ?? 0) > 0 && ( +
+ )}
@@ -471,6 +477,10 @@ function EndShiftModal({ shift, onClose, onDone }: { shift: ShiftSummary; onClos {/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
+ {/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */} + {(report.forgoneCount ?? 0) > 0 && ( +
+ )}
@@ -498,6 +508,10 @@ function EndShiftModal({ shift, onClose, onDone }: { shift: ShiftSummary; onClos {/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
+ {/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */} + {(shift.forgoneCount ?? 0) > 0 && ( +
+ )}
@@ -540,6 +554,10 @@ function TakingsModal({ till, onClose }: { till: TillId; onClose: () => void }) {/* Abonime is the subscription TOTAL; only the out-of-window part is broken out. */}
+ {/* Forgiven exits — fees waived with no payment; NOT in cash/card. Only when any. */} + {(x.forgoneCount ?? 0) > 0 && ( +
+ )}
diff --git a/apps/web/src/api.ts b/apps/web/src/api.ts index 11f9055..158d926 100644 --- a/apps/web/src/api.ts +++ b/apps/web/src/api.ts @@ -1102,6 +1102,10 @@ export interface ShiftSourceSplit { /** Module money that rode this till's tickets (a booth-paid wash), by module id. * Inside cash+card, OUTSIDE the ticket bucket. Absent on pre-2026-09 reports. */ chargesByModuleMinor?: Partial>; + /** Forgiven exits (wiki/decisions/forgiven-exit.md): fees an operator waived, and how + * many. $0 payments — NOT inside cash/card. Absent on pre-2026-10 reports. */ + forgoneTotalMinor?: number; + forgoneCount?: number; } export interface ShiftReport extends ShiftSourceSplit { @@ -1448,6 +1452,16 @@ export function reopenBarrier(identity: string): Promise<{ ok: true; opened: boo return apiFetch("/api/barrier/reopen", { method: "POST", body: JSON.stringify({ identity }) }); } +/** FORGIVEN exit (barrier:create): open the exit with NO payment. With a ticket the fee + * owed is signed as forgone on a $0 payment; with `identity` null the car has no + * session (anomaly + snapshot + pulse). `note` is the mandatory reason. Prints nothing. */ +export function forgiveExit( + identity: string | null, + note: string, +): Promise<{ ok: true; opened: boolean; reason?: string; forgoneMinor?: number; currency?: string }> { + return apiFetch("/api/barrier/forgive", { method: "POST", body: JSON.stringify({ ...(identity ? { identity } : {}), note }) }); +} + /** Take payment for a session → signed payment event. `overrideMinor` sets an * operator amount (lost ticket / dispute). */ export function paySession( diff --git a/apps/web/src/lib/i18n/en.ts b/apps/web/src/lib/i18n/en.ts index 837407a..a90c877 100644 --- a/apps/web/src/lib/i18n/en.ts +++ b/apps/web/src/lib/i18n/en.ts @@ -317,6 +317,11 @@ export const en: Catalog = { issueEntryTitle: "Issue an entry ticket & open the barrier (physical button broken)", issueEntryConfirm: "A vehicle is at the entry. Issue an entry ticket and open the barrier?", issueEntryOk: "Entry ticket {{ticket}} issued.", + forgiveExit: "Forgive & open exit", + forgiveExitTitle: "Open the exit barrier for a car with NO ticket — no money, signed and flagged", + forgiveExitPrompt: "Reason for opening the exit with no ticket (optional — OK to leave empty):", + forgiveExitOk: "Exit opened — forgiven, no payment.", + forgiveExitNotOpened: "Recorded, but the barrier did not open: {{reason}}", exitedGrace: "exited · grace", exitedGraceLeft: "exited · {{time}}", exitedGraceTitle: "Paid and exited — barrier not confirmed; waiting out the grace period.", @@ -419,6 +424,8 @@ export const en: Catalog = { "exit.open.failed": "Exit recorded, but the barrier did not open — open manually", "exit.freeGrace": "Free entry-grace (no charge)", "exit.manualOpen": "Manual barrier open (human intervention)", + "exit.forgiven": "Forgiven exit by {{operator}} — fee of {{forgone}} {{currency}} waived: {{note}}", + "exit.forgiven.noSession": "Forgiven exit by {{operator}} — no ticket / no session: {{note}}", "exit.plateSwapSuspected": "Possible ticket swap — plate {{plate}} is already inside under ticket {{otherIdentity}}", "exit.plateSwapOverride": "Operator {{operator}} released a suspected ticket-swap exit (plate {{plate}}, also open under {{otherIdentity}})", "sub.refused.notFound": "Subscription refused — not found", @@ -991,6 +998,7 @@ export const en: Catalog = { srcSubscriptions: "Subscriptions:", srcOnTicket: "{{module}} (on ticket):", srcSubWindow: "out-of-window", + srcForgone: "Forgiven exits ({{count}}):", drawerSection: "— Drawer —", openingFloat: "Opening cash:", cashTaken: "Daily takings:", @@ -1039,6 +1047,7 @@ export const en: Catalog = { srcTickets: "Tickets", srcSubscriptions: "Subscriptions", srcSubWindow: "out-of-window", + srcForgone: "Forgiven exits ({{count}})", expectedDrawer: "Expected drawer", filterFrom: "From", filterTo: "To", @@ -1246,6 +1255,14 @@ export const en: Catalog = { confirmCancelTicket: "Confirm cancellation", cancelling: "cancelling…", ticketCancelled: "Ticket cancelled.", + forgiveExit: "Forgive & open", + forgiveTitle: "Forgive this exit", + forgiveHint: "Lets the car out with NO payment. The fee owed ({{amount}}) is recorded as forgone on your shift report — never as cash. A reason is optional; nothing is printed.", + forgiveReasonPlaceholder: "Reason for forgiving (optional)…", + confirmForgive: "Confirm — open exit, no payment", + forgiving: "opening…", + exitForgiven: "Exit forgiven — {{amount}} waived, barrier opened.", + exitForgivenNotOpened: "Exit forgiven — {{amount}} waived, but the barrier did not open: {{reason}}", noSnapshots: "no snapshots", loadingSnapshots: "loading snapshots…", snapEntry: "entry", diff --git a/apps/web/src/lib/i18n/sq.ts b/apps/web/src/lib/i18n/sq.ts index 0f366d7..19e2e6c 100644 --- a/apps/web/src/lib/i18n/sq.ts +++ b/apps/web/src/lib/i18n/sq.ts @@ -319,6 +319,11 @@ export const sq = { issueEntryTitle: "Lësho një biletë hyrjeje & hap barrierën (butoni fizik i prishur)", issueEntryConfirm: "Një automjet është te hyrja. Të lëshohet një biletë hyrjeje dhe të hapet barriera?", issueEntryOk: "Bileta e hyrjes {{ticket}} u lëshua.", + forgiveExit: "Fal & hap daljen", + forgiveExitTitle: "Hap barrierën e daljes për një automjet PA biletë — pa para, e nënshkruar dhe e shënuar", + forgiveExitPrompt: "Arsyeja e hapjes së daljes pa biletë (opsionale — mund të lihet bosh):", + forgiveExitOk: "Dalja u hap — e falur, pa pagesë.", + forgiveExitNotOpened: "U regjistrua, por barriera nuk u hap: {{reason}}", exitedGrace: "doli · në afat", exitedGraceLeft: "doli · {{time}}", exitedGraceTitle: "Paguar dhe dalur — barriera nuk u konfirmua; po pret afatin kohor.", @@ -422,6 +427,8 @@ export const sq = { "exit.open.failed": "Dalja u regjistrua, por barriera nuk u hap — hape manualisht", "exit.freeGrace": "Periudhë pa pagesë në hyrje (pa tarifë)", "exit.manualOpen": "Hapje manuale e barrierës (ndërhyrje njerëzore)", + "exit.forgiven": "Dalje e falur nga {{operator}} — tarifa {{forgone}} {{currency}} u fal: {{note}}", + "exit.forgiven.noSession": "Dalje e falur nga {{operator}} — pa biletë / pa seancë: {{note}}", "exit.plateSwapSuspected": "Mundësi ndërrimi biletash — targa {{plate}} është tashmë brenda me biletën {{otherIdentity}}", "exit.plateSwapOverride": "Operatori {{operator}} lëshoi një dalje me dyshim ndërrimi biletash (targa {{plate}}, edhe e hapur me {{otherIdentity}})", "sub.refused.notFound": "Abonimi u refuzua — nuk u gjet", @@ -1004,6 +1011,7 @@ export const sq = { srcSubscriptions: "Abonime:", srcOnTicket: "{{module}} (në biletë):", srcSubWindow: "jashtë orarit", + srcForgone: "Dalje të falura ({{count}}):", drawerSection: "— Arka —", openingFloat: "Arka fillestare:", cashTaken: "Xhiro ditore:", @@ -1052,6 +1060,7 @@ export const sq = { srcTickets: "Bileta", srcSubscriptions: "Abonime", srcSubWindow: "jashtë orarit", + srcForgone: "Dalje të falura ({{count}})", expectedDrawer: "Gjëndje arke", // Filter (admin only). filterFrom: "Nga", @@ -1262,6 +1271,14 @@ export const sq = { confirmCancelTicket: "Konfirmo anulimin", cancelling: "duke anuluar…", ticketCancelled: "Bileta u anulua.", + forgiveExit: "Fal & hap", + forgiveTitle: "Fal këtë dalje", + forgiveHint: "E lë automjetin të dalë PA pagesë. Shuma e detyruar ({{amount}}) regjistrohet si e falur në raportin e turnit — kurrë si para. Arsyeja është opsionale; nuk printohet asgjë.", + forgiveReasonPlaceholder: "Arsyeja e faljes (opsionale)…", + confirmForgive: "Konfirmo — hap daljen, pa pagesë", + forgiving: "duke hapur…", + exitForgiven: "Dalja u fal — {{amount}} u fal, barriera u hap.", + exitForgivenNotOpened: "Dalja u fal — {{amount}} u fal, por barriera nuk u hap: {{reason}}", // snapshots noSnapshots: "asnjë foto", loadingSnapshots: "duke ngarkuar fotot…", diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 4e0aaf1..55d3de6 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -32,6 +32,7 @@ export const RESOURCES = [ "recyclebin", // soft-deleted master data: view / restore / purge "backup", // encrypted DB backups: configure target + trigger a manual run "carwash", // Car Wash module: orders/queue (read), intake (create), done/pay/void (update) + "barrier", // the EXIT barrier opened with NO payment (forgiven exit) — see wiki/decisions/forgiven-exit.md ] as const; export type Resource = (typeof RESOURCES)[number]; @@ -94,6 +95,12 @@ export const PERMISSIONS: readonly Permission[] = [ // `drawer:create`; see ModuleManifest.tillGuards). Settings (categories, services, // price matrix, sponsorship program) ride site:update. "carwash:read", "carwash:create", "carwash:update", "carwash:cash", + // Forgiven exit (wiki/decisions/forgiven-exit.md): open the EXIT barrier for a car with + // no payment — a ticketed transient (its fee is signed as a $0 payment carrying the + // forgone amount) or a car with no session at all. Admin by default; the owner grants + // it to a role deliberately. Every use is signed, attributed, photographed and on the + // operator's Z-report. Never the entry side. + "barrier:create", ] as const; /** The protected built-in role: non-deletable, non-editable, always = ALL @@ -329,6 +336,11 @@ export interface LedgerPayload { readonly grossMinor?: number; readonly discountMinor?: number; readonly validationIds?: string[]; + /** payment: a FORGIVEN exit (wiki/decisions/forgiven-exit.md). `amountMinor` is 0 — + * nothing was tendered, so cash/card/drawer are untouched — and `forgoneMinor` is the + * fee the car owed and the operator waived. Reported as its own Z-report line, never + * folded into the merchant-validation `discountMinor`. */ + readonly forgoneMinor?: number; /** payment: the per-validation receipt lines as settled (label + amount taken off) — * stamped so the printed receipt reproduces without re-deriving the fold. */ readonly validationLines?: { programId: string; label: string; mode: string; discountMinor: number }[]; @@ -463,6 +475,11 @@ export const REASON_CODES = [ "exit.freeGrace", // manual / human-intervention barrier open "exit.manualOpen", + // forgiven exit: the owner/operator (barrier:create) lets a car out with no money. + // With a ticket → a $0 payment carries the forgone fee; no session → anomaly only. + // See wiki/decisions/forgiven-exit.md. + "exit.forgiven", + "exit.forgiven.noSession", // plate reconciliation: the exiting car's plate is already OPEN under a DIFFERENT // ticket (possible ticket-swap fraud). Suspected = flagged; Override = operator // consciously released it. See wiki/concepts/plate-reconciliation.md. @@ -512,6 +529,8 @@ export const REASON_EN: Record = { "exit.open.failed": "exit recorded, but the barrier did not open — open manually", "exit.freeGrace": "free entry-grace (no charge)", "exit.manualOpen": "manual barrier open (human intervention)", + "exit.forgiven": "forgiven exit by {operator} — fee of {forgone} {currency} waived: {note}", + "exit.forgiven.noSession": "forgiven exit by {operator} — no ticket / no session: {note}", "exit.plateSwapSuspected": "possible ticket swap — plate {plate} is already inside under ticket {otherIdentity}", "exit.plateSwapOverride": "operator {operator} released a suspected ticket-swap exit (plate {plate}, also open under {otherIdentity})", "sub.refused.notFound": "subscription refused — not found", diff --git a/wiki/concepts/booth-exit-flow.md b/wiki/concepts/booth-exit-flow.md index 4b47c8f..f05fcf7 100644 --- a/wiki/concepts/booth-exit-flow.md +++ b/wiki/concepts/booth-exit-flow.md @@ -204,6 +204,17 @@ filter shows a `matched/total` count). No new API — filtering is over data alr segment — **booth** (operator-initiated, `source: manual`) vs **reader** (device-initiated: wiegand/lpr/qr/ticket). Filters are scoped within the current shift window, as the feed already is. +## Forgiven exit — open with NO payment (built 2026-10-08) + +The one human-intervention open that is allowed to skip the payment: an operator holding +**`barrier:create`** (admin by default; the owner grants it per role) lets a car out for free. +Decision + as-built in [[forgiven-exit]]. In short: a ticketed car gets a **$0 `payment` +carrying `forgoneMinor`** (the fee it owed) then the same re-open path as above (anomaly + +`vehicle_exit` with `exit.forgiven`); a car with no session gets an anomaly under a +`forgiven:` ref + the pulse. Reason optional, open shift required, **nothing printed**, +and the forgone amount is its own Z-report line — never inside cash/card ([[shift]]). The +no-unpaid-bypass rule above still holds for everyone without that permission. + ## ⚠ Open question — walk-back grace renews on every payment (voucher overstay) > **Update 2026-06-20 — pricing half resolved; grace-renewal half still open.** The overstay work diff --git a/wiki/concepts/shift.md b/wiki/concepts/shift.md index cf08988..bd87ca3 100644 --- a/wiki/concepts/shift.md +++ b/wiki/concepts/shift.md @@ -113,6 +113,16 @@ no variance gate, no manager override. > shared via `formatStampSq` from [[rongta-printer]]. Consistent with the "[[i18n|printed paper is > always Albanian]]" rule — independent of the operator's UI language. +### Forgiven exits on the Z-report (built 2026-10-08) + +A [[forgiven-exit]] is a signed `payment` with `amountMinor: 0` and `forgoneMinor` = the fee +waived, no tender. It adds **nothing** to cash, card, the ticket bucket or the drawer (the +tender sums add 0), so the shift total is untouched by construction. The Z-report sums +`forgoneMinor` into `forgoneTotalMinor` + `forgoneCount`, stamps them on the signed +`shift_z_report` (only when > 0, so older payloads stay identical) and prints one line +`Dalje të falura (N): X` after the merchant-validation leakage line — a separate figure on +purpose, so the owner can tell "the bar validated it" from "the operator let it out". + ### Shift history UI + permission scoping (2026-06-19) A read-only **shift-history screen** (`GET /api/shifts`) lists completed shifts — each a signed `shift_z_report` folded for its figures (no re-summing), newest-first, expandable to the drawer diff --git a/wiki/decisions/forgiven-exit.md b/wiki/decisions/forgiven-exit.md new file mode 100644 index 0000000..4cbf6e9 --- /dev/null +++ b/wiki/decisions/forgiven-exit.md @@ -0,0 +1,103 @@ +--- +type: decision +tags: [parking, decisions, exit, barrier, threat-model, shift, z-report, permissions] +sources: [] +updated: 2026-10-08 +status: built 2026-10-08 +--- + +# Forgiven exit — the owner opens the EXIT barrier with no payment + +> **Built 2026-10-08** (same day as decided). As-built notes at the end of this page; the +> decisions below are what shipped. + +**The ask (user, 2026-10-08).** The owner/admin sometimes needs to let a car out regardless: +a transient that took a ticket but will not be charged, or a car with no session at all (it +came in while the barriers were up). The open must produce **no money** and must be **flagged** +in the live feed. First floated for both directions; **narrowed the same day to the EXIT +barrier only** — the entry keeps its existing paths ([[operator-issued-entry]] when the button +is broken, barriers physically up otherwise). + +## Why it is safe to give the operator this at all + +This is the exact move the [[threat-model]] worries about (pocket the fee, "lose" the ticket, +let the car out). As with [[operator-issued-entry]], the defence is not to withhold the +capability but to make every use **signed, attributed, photographed and impossible to hide**: +it lands on a named operator's shift, with the fee it forgave, where the owner reads it. + +## Decisions + +1. **Exit only.** Reuses the human-intervention re-open path in `exit-flow.ts` + (`reopenBarrier`: anomaly signed FIRST, then the human-intervention `vehicle_exit`, exit + snapshot, `pulseOpen`). Today that path refuses an unpaid or grace-expired transient; the + feature is a **second authorization branch** on it, behind a dedicated permission. +2. **Accounting: a signed ZERO-amount payment that carries the forgone fee.** The Z-report + ([[shift]]) sums `amountMinor` by tender, so a zero payment adds nothing to cash, card or the + drawer — the shift total is untouched by construction. The fee the car owed is recorded in + its **own field** (`forgoneMinor`, with a reason code), reported as its **own line** + ("forgone exits: N, amount X"), and is NOT the merchant-validation `discountMinor` — the + owner must be able to tell "the bar validated it" from "the operator let it out". + Signing the payment also **closes the ticket**, so it cannot be reused ([[plate-reconciliation]] + ticket-swap). +3. **No session (car has no ticket, e.g. came in with the barriers up):** signed anomaly with + the exit snapshot and the plate read, then the pulse. Nothing to forgive, nothing to close. +4. **Permission:** a new one, **admin only by default**; the owner decides whether operators get + it. Requires an **open shift** (same `requireShift` as the pay routes) so every use is on + someone's report. +5. **Reason text is OPTIONAL** (user, 2026-10-09 — reversed from "mandatory" the day before: + "We don't need to force the user to write a reason"). The accountability is the + signature, the operator name, the snapshot and the Z-report line; an empty note is signed + as "(no reason given)" so the English sentence stays readable. +6. **Print nothing.** No receipt, no slip — there is no payment to receipt (user, 2026-10-08). +7. **Visibility:** warn-level log line, anomaly in the live feed with the snapshot, the Z-report + line. **No cap, no blocking** — blocking the owner at the gate recreates the "lot stuck" + problem; the defence is reporting. +8. **Safety unchanged:** `pulseOpen` only, never a timed close ([[fail-state-safety]]). + +## Not decided / out of scope + +- Entry-side free open: **rejected** for now (the entry has its own paths). +- Whether a forgiven exit should also void an attached car-wash charge line: open; today the + zero payment would carry no charge lines at all. + +## Build sketch (when asked) + +`exit-flow.reopenBarrier(identity, operator, { forgive: { reason } })` → quote the fee as the +pay flow would (PayStation quote), sign `payment { amountMinor: 0, forgoneMinor, reason }`, +then the existing re-open body. Route `POST /api/barrier/forgive` with the new permission + +`requireShift`. Z-report: `forgoneTotalMinor` + `forgoneCount` (old reports → 0), one print +line. Web: a guarded button in the pay/exit modal, reason field optional. Reason codes: +`exit.forgiven`, `exit.forgiven.noSession`. Tests on the no-money invariant (cash/card/drawer +unchanged) and on the ticket being closed. + +## As built (2026-10-08) + +- **Permission `barrier:create`** (new resource `barrier` in the code-defined grid, + `packages/shared`). Admin has it by the all-permissions invariant; the owner grants it to any + role from Setup → Roles — "the owner can give permission to other operators" (user). +- **`PayStation.forgive(identity, { operator, note })`** — quotes the fee as the pay flow + would, signs `payment { amountMinor: 0, forgoneMinor: , operator, reasonCode: + "exit.forgiven", reason: "forgiven exit by X — fee of N CUR waived: " }` with **no + tender** (nothing was tendered), marks the projection paid. Refuses (409) when the quote + carries module charge lines (a wash on the ticket): parking is forgiven, a wash is not. +- **`ExitFlow.reopenBarrier(id, operator, { forgiven })`** — the existing human-intervention + re-open with the walk-back check bypassed for a forgiven call (a 0-minute grace tariff must + not refuse it); the anomaly and the `vehicle_exit` carry `exit.forgiven` + `forgiven: true` + + `forgoneMinor`. **`ExitFlow.forgiveExitNoSession(operator, note)`** — anomaly under a fresh + `forgiven:` identity (so its exit snapshot shows in the feed) + pulse; no payment, no + exit event. Relay driving shared in `#pulseExit` (signed first; a failed pulse is + `ok:true, opened:false` + "open by hand"). +- **Route `POST /api/barrier/forgive { identity?, note? }`** — `barrier:create` + the open-shift + gate (`409 no_shift`); the note is optional; no identity = the no-session path. +- **Z-report**: `forgoneTotalMinor` + `forgoneCount` summed from `forgoneMinor` (never into + cash/card; `discountTotalMinor` untouched), on the signed `shift_z_report` only when > 0, one + print line `Dalje të falura (N): X`, shown in the X-report, the close confirm and history. +- **Web**: in the pay/exit modal a red ghost "Forgive & open" for an OPEN transient that owes + money (unpaid or overstay) → reason box → "Confirm — open exit, no payment"; on the booth + header a "Forgive & open exit" next to the exit lane light for the no-ticket case + (`window.prompt` for the reason — Cancel aborts, empty proceeds). Both only render with + `barrier:create` + own open shift. + Live-feed reason texts in en/sq. **Nothing is printed.** +- Tests: exit-flow (ticketed + no-session), pay-station (`forgive`), shift-service (totals + untouched, own line, history), routes (403 without the permission, 409 no shift, 400 no + note accepted, ledger sequence entry→payment→anomaly→exit, report figures). diff --git a/wiki/index.md b/wiki/index.md index 42bc3cb..eea219e 100644 --- a/wiki/index.md +++ b/wiki/index.md @@ -140,6 +140,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records. - [[vision-service]] — build a host-side ANPR + vehicle-verification service; replaces edge-LPR; scoped AGPL exception. - [[bodytype-classifier-training]] — phase B (SUV vs sedan): `apps/trainer` trains on the collector host (time split, floor, features/finetune modes, feature cache) → report → publish to the Gitea generic package → `models/bodytype.version` pin bakes it into the vision image → TAG bump; sidecar = the preprocessing contract; CPU-only torch on the Xeon E3-1225 v5, Quadro FX 3800 unusable, cloud GPU rejected. Built 2026-09-07; first run waits for labels. - [[device-discovery-roadmap]] — memo (open): how each known device class gets a wizard Scan — SADP + ONVIF for cameras (verified on the lab VLAN), 9100 sweep + fingerprint for printers, Dingtian relay multicast search, Dahua 37810; the reusable method and rules from the DT-008 work. +- [[forgiven-exit]] — decision + as-built (2026-10-08): owner opens the EXIT barrier with no payment — a signed zero-amount payment carrying the forgone fee as its own Z-report line (never in cash/card), exit only, admin permission + open shift, reason optional, prints nothing. - [[vision-service-packaging]] — the vision service lives in this monorepo (apps/vision/), separate process, wired into Turbo via a package.json shim; uv-managed Python. - [[event-streams-split]] — split the signed business ledger (ledger_events) from unsigned device telemetry (device_events). - [[desktop-shell-tauri]] — ✅ Tauri v2 chosen over Electron for the desktop kiosk shell; thin wrapper, server keeps all logic. Best case Ubuntu 26.04 LTS (resolves WebKitGTK); worst case Windows+WSL → kiosk browser, no native shell. Auto-updater mirrors signed releases to public `mca/public_releases` (source repo is private — field appliances have no Gitea creds). diff --git a/wiki/log.md b/wiki/log.md index a9ef436..ee2d6cd 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -3467,3 +3467,26 @@ records one PASS sample per detection (best-framed vehicle of its poll loop → `pass:` + vehicle read with `deviceId`); the Car Wash sampler dedups per camera for 30 s so a ticketed car is not sent twice. Also flushed park-2's 21 backed-off rows (`next_attempt_at = now`) so the reviewer got the day's backlog at once. Pages: [[vision-review-outbox]] §entry stream. + +## [2026-10-08] decision | Forgiven exit (owner opens the exit barrier, no money) + +Discussed, narrowed to EXIT only, pinned as [[forgiven-exit]] (status: decided, not built): +zero-amount signed payment carrying `forgoneMinor` as its own Z-report line so the shift's +cash/card/drawer are untouched by construction; no-session cars get an anomaly + pulse; admin +permission, open shift, mandatory reason, prints nothing, no cap. Entry side rejected. + +## [2026-10-08] ingest | Forgiven exit built (barrier:create) + +"Ok, can we implement that? But the owner can give permission to other operators to do +that." Built per [[forgiven-exit]]: new permission `barrier:create` (grantable per role), +`PayStation.forgive` ($0 payment carrying `forgoneMinor`, no tender, refuses wash charges), +`ExitFlow.reopenBarrier(..., { forgiven })` + `forgiveExitNoSession`, route +`POST /api/barrier/forgive`, Z-report `forgoneTotalMinor`/`forgoneCount` + print line, modal +"Forgive & open" + booth-header "Forgive & open exit" (no ticket), en/sq. Prints nothing. +Pages: [[forgiven-exit]], [[booth-exit-flow]] §Forgiven exit, [[shift]] §Forgiven exits. + +## [2026-10-09] decision | Forgiven exit: reason is optional + +"We don't need to force the user to write a reason." Route no longer 400s without a note; an +empty note is signed as "(no reason given)"; modal confirm enabled with an empty box; booth +prompt: Cancel aborts, empty proceeds; en/sq texts say optional. [[forgiven-exit]] §5 updated.