feat(exit): forgiven exit — open the exit barrier with no payment (barrier:create)
Build & push images / images (push) Successful in 3m23s
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:
@@ -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") : {})),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user