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
+38
View File
@@ -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:<id> 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 });
+88 -22
View File
@@ -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<BoothReopenResult> {
async reopenBarrier(identity: string, operator?: string, opts?: { forgiven?: ForgivenExit }): Promise<BoothReopenResult> {
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:<id>` ref so the live feed can show its snapshot.
* See wiki/decisions/forgiven-exit.md.
*/
async forgiveExitNoSession(operator: string, note: string): Promise<BoothReopenResult> {
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<Extract<BoothReopenResult, { ok: true }>> {
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<string, string | number> {
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<ReadOutcome> {
@@ -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<void> {
async #signExit(
identity: string,
source: "ticket" | "lpr" | "manual" = "ticket",
reason?: ReturnType<typeof reasonPayload>,
): Promise<void> {
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") : {})),
},
});
}
+18
View File
@@ -28,6 +28,24 @@ async function enter(identity: string, enteredAt: string, payload?: Record<strin
await log.append({ type: "vehicle_entry", direction: "entry", identity, occurredAt: enteredAt, payload: payload ?? null });
}
describe("PayStation.forgive (forgiven exit)", () => {
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);
+48 -1
View File
@@ -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
@@ -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,
+27 -2
View File
@@ -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");
+27
View File
@@ -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}`,