import { eq, ledgerEvents, sessions, type Db } from "@parking/db"; import { reasonPayload } from "@parking/shared"; import type { FastifyBaseLogger } from "fastify"; import type { EventLog } from "./event-log.js"; // Cancel a wrongly-printed transient ticket by appending a SIGNED `void` event that // references the entry. The signed ledger is append-only and hash-chained — the // vehicle_entry is NEVER edited or deleted; the void is a new appended row that the // session projection folds to CLOSE the session (so a voided car stops counting inside // and can't be paid/exited). Fully traceable: the operator + a required reason are signed // into the void payload. A misprinted ticket's car never entered, so voiding opens NO // barrier. See wiki/concepts/append-only-event-chain.md, parking-session.md. export interface VoidResult { readonly ok: boolean; /** English reason on refusal (localized client-side via the reasonCode it mirrors). */ readonly reason?: string; /** The void event's identity on success (= the entry identity). */ readonly identity?: string; } export class VoidFlow { readonly #db: Db; readonly #log: EventLog; readonly #logger: FastifyBaseLogger; /** Serialize concurrent voids of the SAME ticket (double-click / double-scan). */ readonly #inFlight = new Set(); constructor(db: Db, log: EventLog, logger: FastifyBaseLogger) { this.#db = db; this.#log = log; this.#logger = logger; } /** * Void (cancel) a transient ticket. Guards, then appends a signed `void`. Refuses: * unknown ticket, a subscription occurrence (use the subscription flow), an already- * exited or already-voided session, or a session that has a payment (a paid ticket is a * refund situation — out of scope). `reason` is REQUIRED (the route enforces non-empty). */ async voidTicket(args: { identity: string; reason: string; operator: string }): Promise { const identity = args.identity.trim(); const reason = args.reason.trim(); if (!identity) return { ok: false, reason: "missing ticket id" }; if (!reason) return { ok: false, reason: "a cancellation reason is required" }; if (this.#inFlight.has(identity)) return { ok: false, reason: "cancel already in flight" }; this.#inFlight.add(identity); try { return await this.#run(identity, reason, args.operator); } catch (err) { this.#logger.error(`void-flow failed (${identity}): ${(err as Error).message}`); return { ok: false, reason: (err as Error).message }; } finally { this.#inFlight.delete(identity); } } async #run(identity: string, reason: string, operator: string): Promise { const rows = this.#db .select() .from(ledgerEvents) .where(eq(ledgerEvents.identity, identity)) .orderBy(ledgerEvents.index) .all(); const entry = rows.find((r) => r.type === "vehicle_entry"); if (!entry) return { ok: false, reason: "no such ticket (no entry for this id)" }; // Subscriptions are closed via their own flow — ticket-void would double-mean permitId. const entryPl = (entry.payload ?? {}) as { permit?: boolean; permitId?: string }; if (entryPl.permit === true || entryPl.permitId != null) { return { ok: false, reason: "this is a subscription occurrence — cancel it via the subscription, not a ticket void" }; } if (rows.some((r) => r.type === "vehicle_exit")) { return { ok: false, reason: "session already exited — nothing to cancel" }; } if (rows.some((r) => r.type === "void")) { return { ok: false, reason: "ticket already cancelled" }; } // A paid ticket is a refund, not a misprint cancel — out of scope. if (rows.some((r) => r.type === "payment")) { return { ok: false, reason: "ticket already paid — a refund is a separate action, not a cancellation" }; } await this.#log.append({ type: "void", identity, // `sessionRef` + `voidedEntryRef` tie the void to the entry; `voidReason` + `operator` // make it traceable. The reasonCode localizes; the free-text reason is the operator's note. payload: { ...reasonPayload("void.ticketCancelled", { reason }), sessionRef: identity, voidedEntryRef: entry.id, voidReason: reason, operator, }, }); // Best-effort close the projection cache (the ledger fold is the truth either way). try { this.#db .update(sessions) .set({ exitedAt: new Date().toISOString(), state: "voided" }) .where(eq(sessions.id, identity)) .run(); } catch (err) { this.#logger.error(`void session-cache close failed for ${identity}: ${(err as Error).message}`); } this.#logger.info(`ticket ${identity} cancelled by ${operator}: ${reason}`); // NO barrier action — the misprinted ticket's car never entered. return { ok: true, identity }; } }