feat(carwash): Car Wash v1 + per-till shifts + site-level pay-at + till access by module permission
Car Wash — the pilot venue module (wiki/decisions/venue-modules.md): - Master data (categories × services price matrix) at /setup/carwash; the desk at /wash (ticket lookup → order; open queue oldest-first: Done / Paid cash / Paid card / Void; Finished list). Orders freeze names + price; their life is signed (carwash_order, carwash_payment). Migration 0027. - Where money is taken is a SITE setting (carwash_config.pay_at, migration 0028, signed config_change on a flip) — no per-order radio; a stale client is refused (409). - Core seams: PayStation charge providers (a booth-paid wash rides the parking payment as chargeLines) + applyValidation() shared with the merchant route. A bay-paid, done wash signs the $0 parking payment so the exit reader releases the car. - "Parking discount" modes for the wash: free while the wash runs (+ tolerance) and wash price off the fee (floored at 0), resolved at done and anchored at the order's intake (the entry-anchored version comped a 74-day stay); typed-amount and percent hidden for the wash. Long durations render y/d/h/m. Tills — a shift belongs to a till, not the site (wiki/concepts/shift.md §Tills): - TillId booth|carwash; every money event names its till (absent = booth, so the chain re-folds identically). ShiftService is per till: single-open, folds, X/Z-reports, vouchers, carry-forward. A bay payment needs the carwash shift. - Working a till needs that till's module permission (manifest tillPermission; 403 till_forbidden); /api/shift/tills lists only the role's tills. - Web: ShiftButton per till (header = booth, wash desk = carwash); shift hub lists every open shift with till badges + filter; drawer hub switches tills. Modules: landing per module (index route resolves booth → module landing → shifts → profile); guards bounce to "/", /booth needs session:read. Tests: carwash e2e suite (settings, intake, booth/bay paths, modes, void, gate, pay-at policy, till permissions), 6 per-till shift tests; suite green (1 pre-existing flaky backup test under the parallel run). Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
This commit is contained in:
@@ -44,12 +44,12 @@ describe("defaults (no env, nothing activated)", () => {
|
||||
const cfg = await app.inject({ method: "GET", url: "/api/site-config", headers: { cookie } });
|
||||
expect(cfg.statusCode).toBe(200);
|
||||
const body = cfg.json();
|
||||
expect(body.modulesEntitled).toEqual(["parking", "validation"]);
|
||||
expect(body.modulesActivated).toEqual(["parking", "validation"]);
|
||||
expect(body.modules).toEqual(["parking", "validation"]);
|
||||
expect(body.modulesEntitled).toEqual(["parking", "validation", "carwash"]);
|
||||
expect(body.modulesActivated).toEqual(["parking", "validation", "carwash"]);
|
||||
expect(body.modules).toEqual(["parking", "validation", "carwash"]);
|
||||
|
||||
const me = await app.inject({ method: "GET", url: "/api/auth/me", headers: { cookie } });
|
||||
expect(me.json().modules).toEqual(["parking", "validation"]);
|
||||
expect(me.json().modules).toEqual(["parking", "validation", "carwash"]);
|
||||
|
||||
// A module route answers normally while the module is on.
|
||||
const programs = await app.inject({ method: "GET", url: "/api/validation/programs", headers: { cookie } });
|
||||
@@ -107,6 +107,16 @@ describe("activation (site admin)", () => {
|
||||
});
|
||||
|
||||
it("rejects unknown ids with 400", async () => {
|
||||
const { cookie, csrf } = await admin();
|
||||
const put = await app.inject({
|
||||
method: "PUT", url: "/api/site-config",
|
||||
headers: { cookie, "x-csrf-token": csrf },
|
||||
payload: { modules: ["parking", "bar"] },
|
||||
});
|
||||
expect(put.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("dependency rule: carwash cannot be on while validation is off", async () => {
|
||||
const { cookie, csrf } = await admin();
|
||||
const put = await app.inject({
|
||||
method: "PUT", url: "/api/site-config",
|
||||
@@ -114,6 +124,7 @@ describe("activation (site admin)", () => {
|
||||
payload: { modules: ["parking", "carwash"] },
|
||||
});
|
||||
expect(put.statusCode).toBe(400);
|
||||
expect(put.json().error).toMatch(/requires "validation"/);
|
||||
});
|
||||
|
||||
it("a no-op resave signs nothing", async () => {
|
||||
@@ -123,7 +134,7 @@ describe("activation (site admin)", () => {
|
||||
await app.inject({
|
||||
method: "PUT", url: "/api/site-config",
|
||||
headers: { cookie, "x-csrf-token": csrf },
|
||||
payload: { modules: ["parking", "validation"] },
|
||||
payload: { modules: ["parking", "validation", "carwash"] },
|
||||
});
|
||||
const after = await app.inject({ method: "GET", url: "/api/events?limit=50", headers: { cookie } });
|
||||
expect(((after.json().events ?? after.json()) as unknown[]).length).toBe(countBefore);
|
||||
@@ -162,5 +173,6 @@ describe("entitlement (vendor env)", () => {
|
||||
const { cookie } = await admin();
|
||||
const cfg = await app.inject({ method: "GET", url: "/api/site-config", headers: { cookie } });
|
||||
expect(cfg.json().modulesEntitled).toEqual(["parking", "validation"]);
|
||||
expect(cfg.json().modules).toEqual(["parking", "validation"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,9 +3,14 @@ import { eq, siteConfig, type Db } from "@parking/db";
|
||||
import {
|
||||
effectiveModules,
|
||||
isModuleId,
|
||||
isTillId,
|
||||
parseEntitledModules,
|
||||
tillsFor,
|
||||
tillsOf,
|
||||
type ModuleId,
|
||||
type TillId,
|
||||
} from "@parking/shared";
|
||||
import { roleHasPermissions } from "./auth.js";
|
||||
|
||||
// Venue modules — the server side of "entitled ∩ activated" (registry + rules live in
|
||||
// @parking/shared; design in wiki/decisions/venue-modules.md).
|
||||
@@ -46,6 +51,26 @@ export function effectiveModulesFor(db: Db): ModuleId[] {
|
||||
return effectiveModules(entitledModules(), activatedModulesOf(row));
|
||||
}
|
||||
|
||||
/** The tills available at this site right now: the booth, plus each effective
|
||||
* money-taking module's own till (registry order). */
|
||||
export function effectiveTillsFor(db: Db): TillId[] {
|
||||
return tillsOf(effectiveModulesFor(db));
|
||||
}
|
||||
|
||||
/** The tills a role may WORK here (open/close its shift, move its cash): effective
|
||||
* tills whose module permission the role holds. */
|
||||
export function accessibleTillsFor(db: Db, roleId: string): TillId[] {
|
||||
return tillsFor(effectiveModulesFor(db), (p) => roleHasPermissions(roleId, [p]));
|
||||
}
|
||||
|
||||
/** Parse a till from a query/body value. Absent/blank = the booth. Unknown, or a till
|
||||
* whose module is not effective here, → null (the caller answers 400). */
|
||||
export function parseTill(db: Db, raw: unknown): TillId | null {
|
||||
if (raw == null || raw === "") return "booth";
|
||||
if (!isTillId(raw)) return null;
|
||||
return effectiveTillsFor(db).includes(raw) ? raw : null;
|
||||
}
|
||||
|
||||
/** preHandler: reject the call when `id` is not effective at this site. Compose it
|
||||
* BEFORE requirePermission in a preHandler array so a disabled module answers the
|
||||
* same way for every role — 403 with code "module_disabled" — and never reaches
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createTestDb } from "@parking/db/testing";
|
||||
import { type Db } from "@parking/db";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildServer } from "../../server.js";
|
||||
import { login, makeLog, minutesAgo, seedTariff, seedUser } from "../../test-helpers.js";
|
||||
|
||||
// Car Wash module, end to end over the real app (wiki/decisions/venue-modules.md):
|
||||
// settings → intake against an open parking session → done applies the sponsorship
|
||||
// validation → bay payment settles the parking session at zero (what the exit reader
|
||||
// checks) / booth payment carries the wash as a charge line → module off = 403.
|
||||
|
||||
let db: Db;
|
||||
let close: () => void;
|
||||
let app: FastifyInstance;
|
||||
|
||||
beforeEach(async () => {
|
||||
delete process.env.MODULES_ENTITLED;
|
||||
const t = createTestDb();
|
||||
db = t.db;
|
||||
close = t.close;
|
||||
app = await buildServer({ db });
|
||||
await app.ready();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
close();
|
||||
});
|
||||
|
||||
type Auth = { cookie: string; csrf: string };
|
||||
const hdrs = (a: Auth) => ({ cookie: a.cookie, "x-csrf-token": a.csrf });
|
||||
|
||||
async function admin(): Promise<Auth> {
|
||||
const { username, password } = await seedUser(db, { username: "boss", roleId: "admin" });
|
||||
return login(app, username, password);
|
||||
}
|
||||
|
||||
/** An open transient session that has been parked long enough to owe money. */
|
||||
async function openSession(identity: string, enteredMinutesAgo = 90): Promise<void> {
|
||||
await makeLog(db).append({
|
||||
type: "vehicle_entry",
|
||||
source: "manual",
|
||||
identity,
|
||||
occurredAt: minutesAgo(enteredMinutesAgo),
|
||||
payload: { sessionRef: identity, category: "default" },
|
||||
});
|
||||
}
|
||||
|
||||
async function seedSettings(a: Auth) {
|
||||
const res = await app.inject({
|
||||
method: "PUT", url: "/api/carwash/settings", headers: hdrs(a),
|
||||
payload: {
|
||||
categories: [{ name: "Car" }, { name: "SUV" }],
|
||||
services: [{ name: "Standard" }, { name: "Inside" }],
|
||||
prices: [],
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const s = res.json();
|
||||
const car = s.categories.find((c: { name: string }) => c.name === "Car").id;
|
||||
const suv = s.categories.find((c: { name: string }) => c.name === "SUV").id;
|
||||
const std = s.services.find((c: { name: string }) => c.name === "Standard").id;
|
||||
const inside = s.services.find((c: { name: string }) => c.name === "Inside").id;
|
||||
const priced = await app.inject({
|
||||
method: "PUT", url: "/api/carwash/settings", headers: hdrs(a),
|
||||
payload: {
|
||||
categories: s.categories, services: s.services,
|
||||
prices: [
|
||||
{ categoryId: car, serviceId: std, priceMinor: 50000 },
|
||||
{ categoryId: suv, serviceId: std, priceMinor: 70000 },
|
||||
{ categoryId: car, serviceId: inside, priceMinor: 30000 },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(priced.statusCode).toBe(200);
|
||||
expect(priced.json().prices).toHaveLength(3);
|
||||
return { car, suv, std, inside };
|
||||
}
|
||||
|
||||
/** Flip the site's wash-payment policy (Setup → Car wash). */
|
||||
async function setPayAt(a: Auth, payAt: "booth" | "bay") {
|
||||
const res = await app.inject({ method: "PUT", url: "/api/carwash/settings", headers: hdrs(a), payload: { payAt } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().payAt).toBe(payAt);
|
||||
}
|
||||
|
||||
async function seedSponsorship(a: Auth, mode: "comp" | "percent" | "doneTolerance" | "washPrice" = "comp", minutes: number | null = null) {
|
||||
const res = await app.inject({
|
||||
method: "PUT", url: "/api/validation/programs/carwash", headers: hdrs(a),
|
||||
payload: { name: "Lavazh", mode, percent: mode === "percent" ? 50 : null, minutes, active: true, userIds: [] },
|
||||
});
|
||||
expect(res.statusCode).toBeLessThan(300);
|
||||
}
|
||||
|
||||
async function events(a: Auth) {
|
||||
const r = await app.inject({ method: "GET", url: "/api/events?limit=100", headers: { cookie: a.cookie } });
|
||||
return (r.json().events ?? r.json()) as Array<{ id: string; type: string; identity: string | null; payload: Record<string, unknown> }>;
|
||||
}
|
||||
|
||||
describe("settings", () => {
|
||||
it("round-trips categories, services and the price matrix; signs a config_change; unknown pairs are refused", async () => {
|
||||
const a = await admin();
|
||||
const ids = await seedSettings(a);
|
||||
const get = await app.inject({ method: "GET", url: "/api/carwash/settings", headers: { cookie: a.cookie } });
|
||||
expect(get.json().categories.map((c: { name: string }) => c.name)).toEqual(["Car", "SUV"]);
|
||||
expect(get.json().prices.find((p: { categoryId: string; serviceId: string }) => p.categoryId === ids.suv && p.serviceId === ids.std).priceMinor).toBe(70000);
|
||||
const bad = await app.inject({
|
||||
method: "PUT", url: "/api/carwash/settings", headers: hdrs(a),
|
||||
payload: { prices: [{ categoryId: "nope", serviceId: ids.std, priceMinor: 1 }] },
|
||||
});
|
||||
expect(bad.statusCode).toBe(400);
|
||||
const flips = (await events(a)).filter((e) => e.type === "config_change" && e.payload.setting === "carwash.settings");
|
||||
expect(flips.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("orders", () => {
|
||||
it("intake needs an open session and a priced pair; the queue is oldest-first", async () => {
|
||||
const a = await admin();
|
||||
seedTariff(db);
|
||||
const ids = await seedSettings(a);
|
||||
const noSession = await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-NONE", categoryId: ids.car, serviceId: ids.std },
|
||||
});
|
||||
expect(noSession.statusCode).toBe(404);
|
||||
|
||||
await openSession("T-1");
|
||||
const noPrice = await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-1", categoryId: ids.suv, serviceId: ids.inside },
|
||||
});
|
||||
expect(noPrice.statusCode).toBe(409);
|
||||
expect(noPrice.json().code).toBe("no_price");
|
||||
|
||||
const created = await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-1", categoryId: ids.suv, serviceId: ids.std },
|
||||
});
|
||||
expect(created.statusCode).toBe(201);
|
||||
expect(created.json()).toMatchObject({ identity: "T-1", categoryName: "SUV", serviceName: "Standard", priceMinor: 70000, payAt: "booth", status: "open", closed: false });
|
||||
|
||||
await openSession("T-2");
|
||||
await setPayAt(a, "bay");
|
||||
await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-2", categoryId: ids.car, serviceId: ids.std },
|
||||
});
|
||||
const queue = await app.inject({ method: "GET", url: "/api/carwash/orders", headers: { cookie: a.cookie } });
|
||||
expect(queue.json().orders.map((o: { identity: string }) => o.identity)).toEqual(["T-1", "T-2"]);
|
||||
|
||||
const chain = (await events(a)).filter((e) => e.type === "carwash_order");
|
||||
expect(chain).toHaveLength(2);
|
||||
expect(chain[0]!.payload).toMatchObject({ action: "created", operator: "boss" });
|
||||
});
|
||||
|
||||
it("pay at BOOTH: the wash rides the parking quote as a charge line and is marked paid by the booth payment", async () => {
|
||||
const a = await admin();
|
||||
seedTariff(db, { pricePerIncrementMinor: 10000 });
|
||||
const ids = await seedSettings(a);
|
||||
await openSession("T-B");
|
||||
const order = (await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-B", categoryId: ids.car, serviceId: ids.std },
|
||||
})).json();
|
||||
|
||||
const look = await app.inject({ method: "GET", url: "/api/session/T-B", headers: { cookie: a.cookie } });
|
||||
const s = look.json();
|
||||
expect(s.chargeLines).toHaveLength(1);
|
||||
expect(s.chargeLines[0]).toMatchObject({ module: "carwash", ref: order.id, amountMinor: 50000 });
|
||||
expect(s.chargesMinor).toBe(50000);
|
||||
expect(s.amountMinor).toBeGreaterThan(50000); // parking fee + the wash
|
||||
|
||||
await app.inject({ method: "POST", url: "/api/shift/open", headers: hdrs(a) });
|
||||
const pay = await app.inject({ method: "POST", url: "/api/pay", headers: hdrs(a), payload: { identity: "T-B", tender: "cash" } });
|
||||
expect(pay.statusCode).toBeLessThan(300);
|
||||
|
||||
const payment = (await events(a)).find((e) => e.type === "payment" && e.identity === "T-B")!;
|
||||
expect(payment.payload.chargesMinor).toBe(50000);
|
||||
expect((payment.payload.chargeLines as unknown[]).length).toBe(1);
|
||||
expect(payment.payload.amountMinor).toBe((payment.payload.parkingMinor as number) + 50000);
|
||||
|
||||
const recent = await app.inject({ method: "GET", url: "/api/carwash/orders?scope=recent", headers: { cookie: a.cookie } });
|
||||
const o = recent.json().orders.find((x: { id: string }) => x.id === order.id);
|
||||
expect(o.paidAt).toBeTruthy();
|
||||
expect(o.paymentEventId).toBeUndefined(); // not exposed on the view
|
||||
expect(o.tender).toBe("cash");
|
||||
// A second lookup no longer carries the line (it's settled).
|
||||
const again = await app.inject({ method: "GET", url: "/api/session/T-B", headers: { cookie: a.cookie } });
|
||||
expect(again.json().chargeLines).toEqual([]);
|
||||
});
|
||||
|
||||
it("pay at BAY with a comp sponsorship: done applies the validation, bay payment signs carwash_payment and settles parking at zero", async () => {
|
||||
const a = await admin();
|
||||
seedTariff(db, { pricePerIncrementMinor: 10000 });
|
||||
const ids = await seedSettings(a);
|
||||
await seedSponsorship(a, "comp");
|
||||
await openSession("T-Y");
|
||||
await setPayAt(a, "bay");
|
||||
const order = (await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-Y", categoryId: ids.suv, serviceId: ids.std },
|
||||
})).json();
|
||||
|
||||
// Bay money needs an open CARWASH shift — the booth's shift does not count (tills).
|
||||
await app.inject({ method: "POST", url: "/api/shift/open", headers: hdrs(a) });
|
||||
const noShift = await app.inject({ method: "POST", url: `/api/carwash/orders/${order.id}/pay`, headers: hdrs(a), payload: { tender: "cash" } });
|
||||
expect(noShift.statusCode).toBe(409);
|
||||
expect(noShift.json()).toMatchObject({ code: "no_shift", till: "carwash" });
|
||||
const openWash = await app.inject({ method: "POST", url: "/api/shift/open", headers: hdrs(a), payload: { till: "carwash" } });
|
||||
expect(openWash.statusCode).toBe(200);
|
||||
|
||||
const done = await app.inject({ method: "POST", url: `/api/carwash/orders/${order.id}/done`, headers: hdrs(a) });
|
||||
expect(done.statusCode).toBe(200);
|
||||
expect(done.json().status).toBe("done");
|
||||
expect(done.json().validationEventId).toBeTruthy();
|
||||
// Sponsorship applied → the parking quote is now zero-due (comp), but NOT yet paid.
|
||||
const mid = await app.inject({ method: "GET", url: "/api/session/T-Y", headers: { cookie: a.cookie } });
|
||||
expect(mid.json().amountMinor).toBe(0);
|
||||
expect(mid.json().paidAt).toBeNull();
|
||||
|
||||
const paid = await app.inject({ method: "POST", url: `/api/carwash/orders/${order.id}/pay`, headers: hdrs(a), payload: { tender: "card" } });
|
||||
expect(paid.statusCode).toBe(200);
|
||||
expect(paid.json().closed).toBe(true);
|
||||
|
||||
const evs = await events(a);
|
||||
const bay = evs.find((e) => e.type === "carwash_payment")!;
|
||||
expect(bay.payload).toMatchObject({ orderId: order.id, amountMinor: 70000, tender: "card", operator: "boss", till: "carwash" });
|
||||
// The wash Z-report carries the bay money; the booth's carries none of it.
|
||||
const washZ = (await app.inject({ method: "POST", url: "/api/shift/close", headers: hdrs(a), payload: { till: "carwash" } })).json();
|
||||
expect(washZ).toMatchObject({ till: "carwash", cardTotalMinor: 70000, cashTotalMinor: 0, paymentCount: 1 });
|
||||
const boothZ = (await app.inject({ method: "POST", url: "/api/shift/close", headers: hdrs(a) })).json();
|
||||
expect(boothZ.till).toBe("booth");
|
||||
expect(boothZ.cardTotalMinor).toBe(0);
|
||||
expect(boothZ.paymentCount).toBe(1); // the $0 parking settlement is booth money
|
||||
// The $0 parking payment exists → the exit reader's paid+grace check passes.
|
||||
const parkingPay = evs.find((e) => e.type === "payment" && e.identity === "T-Y")!;
|
||||
expect(parkingPay).toBeTruthy();
|
||||
expect(parkingPay.payload.amountMinor).toBe(0);
|
||||
const after = await app.inject({ method: "GET", url: "/api/session/T-Y", headers: { cookie: a.cookie } });
|
||||
expect(after.json().paidAt).toBeTruthy();
|
||||
expect(after.json().withinGrace).toBe(true);
|
||||
|
||||
// The queue is empty (done + paid = closed).
|
||||
const queue = await app.inject({ method: "GET", url: "/api/carwash/orders", headers: { cookie: a.cookie } });
|
||||
expect(queue.json().orders).toEqual([]);
|
||||
});
|
||||
|
||||
it("pay at BAY with a PARTIAL sponsorship leaves the remainder for the booth (no $0 payment)", async () => {
|
||||
const a = await admin();
|
||||
seedTariff(db, { pricePerIncrementMinor: 10000 });
|
||||
const ids = await seedSettings(a);
|
||||
await seedSponsorship(a, "percent");
|
||||
await openSession("T-P");
|
||||
await setPayAt(a, "bay");
|
||||
const order = (await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-P", categoryId: ids.car, serviceId: ids.std },
|
||||
})).json();
|
||||
await app.inject({ method: "POST", url: "/api/shift/open", headers: hdrs(a), payload: { till: "carwash" } });
|
||||
await app.inject({ method: "POST", url: `/api/carwash/orders/${order.id}/pay`, headers: hdrs(a), payload: { tender: "cash" } });
|
||||
await app.inject({ method: "POST", url: `/api/carwash/orders/${order.id}/done`, headers: hdrs(a) });
|
||||
const s = (await app.inject({ method: "GET", url: "/api/session/T-P", headers: { cookie: a.cookie } })).json();
|
||||
expect(s.paidAt).toBeNull();
|
||||
expect(s.amountMinor).toBeGreaterThan(0);
|
||||
expect(s.discountMinor).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("void takes back a live sponsorship; a paid order cannot be voided", async () => {
|
||||
const a = await admin();
|
||||
seedTariff(db);
|
||||
const ids = await seedSettings(a);
|
||||
await seedSponsorship(a, "comp");
|
||||
await openSession("T-V");
|
||||
const order = (await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-V", categoryId: ids.car, serviceId: ids.std },
|
||||
})).json();
|
||||
await app.inject({ method: "POST", url: `/api/carwash/orders/${order.id}/done`, headers: hdrs(a) });
|
||||
const before = (await app.inject({ method: "GET", url: "/api/session/T-V", headers: { cookie: a.cookie } })).json();
|
||||
expect(before.validationLines).toHaveLength(1);
|
||||
|
||||
const voided = await app.inject({ method: "POST", url: `/api/carwash/orders/${order.id}/void`, headers: hdrs(a), payload: { reason: "customer left" } });
|
||||
expect(voided.statusCode).toBe(200);
|
||||
expect(voided.json().status).toBe("void");
|
||||
const after = (await app.inject({ method: "GET", url: "/api/session/T-V", headers: { cookie: a.cookie } })).json();
|
||||
expect(after.validationLines).toEqual([]);
|
||||
expect(after.chargeLines).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("wash-only discount modes", () => {
|
||||
it("doneTolerance credits only the WASH WINDOW (+ tolerance), never the parking before the order", async () => {
|
||||
const a = await admin();
|
||||
// 100.00 per 60-min increment, no entry grace; parked 95 min → 2 increments.
|
||||
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60, gracePeriodEntryMin: 0 });
|
||||
const ids = await seedSettings(a);
|
||||
await seedSponsorship(a, "doneTolerance", 15);
|
||||
await openSession("T-D", 95);
|
||||
await setPayAt(a, "bay");
|
||||
const order = (await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-D", categoryId: ids.car, serviceId: ids.std },
|
||||
})).json();
|
||||
const before = (await app.inject({ method: "GET", url: "/api/session/T-D", headers: { cookie: a.cookie } })).json();
|
||||
expect(before.amountMinor).toBe(20000);
|
||||
// Done right away: the wash window is ~0 min, so the credit is just the tolerance.
|
||||
await app.inject({ method: "POST", url: `/api/carwash/orders/${order.id}/done`, headers: hdrs(a) });
|
||||
const v = (await events(a)).find((e) => e.type === "validation" && e.identity === "T-D")!;
|
||||
expect(v.payload.mode).toBe("timeCredit");
|
||||
expect(v.payload.programMode).toBe("doneTolerance");
|
||||
expect(v.payload.minutes as number).toBeGreaterThanOrEqual(15);
|
||||
expect(v.payload.minutes as number).toBeLessThanOrEqual(17);
|
||||
// 95 − ~15 min still spans 2 increments → the long stay is NOT comped away.
|
||||
const after = (await app.inject({ method: "GET", url: "/api/session/T-D", headers: { cookie: a.cookie } })).json();
|
||||
expect(after.amountMinor).toBe(20000);
|
||||
expect(after.discountMinor).toBe(0);
|
||||
});
|
||||
|
||||
it("doneTolerance with a tolerance that covers the whole stay does comp it (the credit is real)", async () => {
|
||||
const a = await admin();
|
||||
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60, gracePeriodEntryMin: 0 });
|
||||
const ids = await seedSettings(a);
|
||||
await seedSponsorship(a, "doneTolerance", 120);
|
||||
await openSession("T-D2", 95);
|
||||
await setPayAt(a, "bay");
|
||||
const order = (await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-D2", categoryId: ids.car, serviceId: ids.std },
|
||||
})).json();
|
||||
await app.inject({ method: "POST", url: `/api/carwash/orders/${order.id}/done`, headers: hdrs(a) });
|
||||
const after = (await app.inject({ method: "GET", url: "/api/session/T-D2", headers: { cookie: a.cookie } })).json();
|
||||
expect(after.amountMinor).toBe(0);
|
||||
});
|
||||
|
||||
it("washPrice: the wash price comes off the parking fee, floored at zero", async () => {
|
||||
const a = await admin();
|
||||
// 1000.00/h, parked 95 min → 2 increments = 200000 owed. Car·Standard wash = 50000.
|
||||
seedTariff(db, { pricePerIncrementMinor: 100000, incrementMin: 60, gracePeriodEntryMin: 0 });
|
||||
const ids = await seedSettings(a);
|
||||
await seedSponsorship(a, "washPrice");
|
||||
await openSession("T-W", 95);
|
||||
await setPayAt(a, "bay");
|
||||
const order = (await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-W", categoryId: ids.car, serviceId: ids.std },
|
||||
})).json();
|
||||
const before = (await app.inject({ method: "GET", url: "/api/session/T-W", headers: { cookie: a.cookie } })).json();
|
||||
await app.inject({ method: "POST", url: `/api/carwash/orders/${order.id}/done`, headers: hdrs(a) });
|
||||
const after = (await app.inject({ method: "GET", url: "/api/session/T-W", headers: { cookie: a.cookie } })).json();
|
||||
expect(after.discountMinor).toBe(50000);
|
||||
expect(after.amountMinor).toBe(before.amountMinor - 50000);
|
||||
const v = (await events(a)).find((e) => e.type === "validation" && e.identity === "T-W")!;
|
||||
expect(v.payload).toMatchObject({ mode: "fixed", programMode: "washPrice", amountMinor: 50000 });
|
||||
});
|
||||
|
||||
it("a merchant scan cannot apply a wash-only program", async () => {
|
||||
const a = await admin();
|
||||
seedTariff(db);
|
||||
await seedSponsorship(a, "washPrice");
|
||||
// Bind the admin to it so the binding check passes and the MODE check is what refuses.
|
||||
await app.inject({
|
||||
method: "PUT", url: "/api/validation/programs/carwash", headers: hdrs(a),
|
||||
payload: { name: "Lavazh", mode: "washPrice", active: true, userIds: [(await app.inject({ method: "GET", url: "/api/auth/me", headers: { cookie: a.cookie } })).json().id] },
|
||||
});
|
||||
await openSession("T-M");
|
||||
const res = await app.inject({ method: "POST", url: "/api/validation/apply", headers: hdrs(a), payload: { identity: "T-M", programId: "carwash" } });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/car wash order/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("module gate", () => {
|
||||
it("with carwash deactivated every route 403s and the booth quote carries no wash lines", async () => {
|
||||
const a = await admin();
|
||||
seedTariff(db);
|
||||
const ids = await seedSettings(a);
|
||||
await openSession("T-G");
|
||||
await app.inject({
|
||||
method: "POST", url: "/api/carwash/orders", headers: hdrs(a),
|
||||
payload: { identity: "T-G", categoryId: ids.car, serviceId: ids.std },
|
||||
});
|
||||
const off = await app.inject({ method: "PUT", url: "/api/site-config", headers: hdrs(a), payload: { modules: ["parking", "validation"] } });
|
||||
expect(off.json().modules).toEqual(["parking", "validation"]);
|
||||
const q = await app.inject({ method: "GET", url: "/api/carwash/orders", headers: { cookie: a.cookie } });
|
||||
expect(q.statusCode).toBe(403);
|
||||
expect(q.json().code).toBe("module_disabled");
|
||||
const look = (await app.inject({ method: "GET", url: "/api/session/T-G", headers: { cookie: a.cookie } })).json();
|
||||
expect(look.chargeLines).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("where the money is taken is a SITE setting", () => {
|
||||
it("defaults to the booth, persists, signs a config_change, and freezes on each order", async () => {
|
||||
const a = await admin();
|
||||
seedTariff(db);
|
||||
const ids = await seedSettings(a);
|
||||
expect((await app.inject({ method: "GET", url: "/api/carwash/settings", headers: { cookie: a.cookie } })).json().payAt).toBe("booth");
|
||||
await openSession("T-S1");
|
||||
const o1 = (await app.inject({ method: "POST", url: "/api/carwash/orders", headers: hdrs(a), payload: { identity: "T-S1", categoryId: ids.car, serviceId: ids.std } })).json();
|
||||
expect(o1.payAt).toBe("booth");
|
||||
|
||||
await setPayAt(a, "bay");
|
||||
const cfg = (await events(a)).find((e) => e.type === "config_change" && e.payload.setting === "carwash.payAt")!;
|
||||
expect(cfg.payload).toMatchObject({ value: "bay", prev: "booth", operator: "boss" });
|
||||
await openSession("T-S2");
|
||||
const o2 = (await app.inject({ method: "POST", url: "/api/carwash/orders", headers: hdrs(a), payload: { identity: "T-S2", categoryId: ids.car, serviceId: ids.std } })).json();
|
||||
expect(o2.payAt).toBe("bay");
|
||||
expect(o1.payAt).toBe("booth"); // earlier order keeps the policy it was created under
|
||||
|
||||
// A stale client insisting on the other place is refused, never silently overridden.
|
||||
const stale = await app.inject({ method: "POST", url: "/api/carwash/orders", headers: hdrs(a), payload: { identity: "T-S2", categoryId: ids.car, serviceId: ids.std, payAt: "booth" } });
|
||||
expect(stale.statusCode).toBe(409);
|
||||
expect(stale.json().code).toBe("pay_at_policy");
|
||||
const bad = await app.inject({ method: "PUT", url: "/api/carwash/settings", headers: hdrs(a), payload: { payAt: "pocket" } });
|
||||
expect(bad.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tills are gated by the module permission", () => {
|
||||
it("a wash-only role works the carwash till and never the booth's; a booth role the reverse", async () => {
|
||||
const a = await admin();
|
||||
seedTariff(db);
|
||||
await seedSettings(a);
|
||||
const washer = await seedUser(db, {
|
||||
username: "lavazhier", roleId: "washer",
|
||||
permissions: ["carwash:read", "carwash:create", "carwash:update", "shift:read", "shift:create", "drawer:create"],
|
||||
});
|
||||
const w = await login(app, washer.username, washer.password);
|
||||
// What the UI offers: only the wash till.
|
||||
const tills = await app.inject({ method: "GET", url: "/api/shift/tills", headers: { cookie: w.cookie } });
|
||||
expect(tills.json().tills.map((t: { till: string }) => t.till)).toEqual(["carwash"]);
|
||||
// The booth's shift is refused outright (the role lacks session:read).
|
||||
const booth = await app.inject({ method: "POST", url: "/api/shift/open", headers: hdrs(w) });
|
||||
expect(booth.statusCode).toBe(403);
|
||||
expect(booth.json()).toMatchObject({ code: "till_forbidden", till: "booth" });
|
||||
const boothState = await app.inject({ method: "GET", url: "/api/shift/current", headers: { cookie: w.cookie } });
|
||||
expect(boothState.statusCode).toBe(403);
|
||||
const boothCash = await app.inject({ method: "POST", url: "/api/drawer/movement", headers: hdrs(w), payload: { type: "cash_in", amountMinor: 100 } });
|
||||
expect(boothCash.statusCode).toBe(403);
|
||||
// The wash till works.
|
||||
const wash = await app.inject({ method: "POST", url: "/api/shift/open", headers: hdrs(w), payload: { till: "carwash" } });
|
||||
expect(wash.statusCode).toBe(200);
|
||||
expect(wash.json().till).toBe("carwash");
|
||||
const washCash = await app.inject({ method: "POST", url: "/api/drawer/movement", headers: hdrs(w), payload: { type: "cash_in", amountMinor: 100, till: "carwash" } });
|
||||
expect(washCash.statusCode).toBe(200);
|
||||
|
||||
// A booth operator (session:read, no carwash:read) cannot touch the wash till.
|
||||
const booth1 = await seedUser(db, {
|
||||
username: "boothie", roleId: "booth-op",
|
||||
permissions: ["session:read", "payment:create", "shift:read", "shift:create"],
|
||||
});
|
||||
const b = await login(app, booth1.username, booth1.password);
|
||||
const noWash = await app.inject({ method: "POST", url: "/api/shift/close", headers: hdrs(b), payload: { till: "carwash" } });
|
||||
expect(noWash.statusCode).toBe(403);
|
||||
expect((await app.inject({ method: "GET", url: "/api/shift/tills", headers: { cookie: b.cookie } })).json().tills.map((t: { till: string }) => t.till)).toEqual(["booth"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ServerModule } from "../index.js";
|
||||
import { carwashRoutes } from "./routes.js";
|
||||
import { CarwashService } from "./service.js";
|
||||
|
||||
// Car Wash — the pilot venue module (wiki/decisions/venue-modules.md). Everything the
|
||||
// module is lives in this folder: its service (master data, the order queue, the bay
|
||||
// payment, the parking sponsorship + settlement), its routes, and the booth charge
|
||||
// provider it registers with the core's PayStation. The core knows it only through the
|
||||
// registry line in ../index.ts and the manifest in @parking/shared.
|
||||
export const carwashModule: ServerModule = {
|
||||
id: "carwash",
|
||||
async register(app, deps) {
|
||||
const service = new CarwashService(deps, app.log);
|
||||
// A wash ordered with payAt = "booth" is a charge line on the parking settlement;
|
||||
// the core calls back after the payment is signed so the order is marked paid.
|
||||
deps.payStation.registerChargeProvider(service.chargeProvider());
|
||||
await carwashRoutes(app, deps, service);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { FastifyInstance, FastifyReply } from "fastify";
|
||||
import type { Tender } from "@parking/shared";
|
||||
import { requirePermission } from "../../auth.js";
|
||||
import { requireModule } from "../../modules.js";
|
||||
import { NoShiftOpenError } from "../../shift-service.js";
|
||||
import type { ServerModuleDeps } from "../index.js";
|
||||
import { CarwashError, CarwashService, isPayAt, type SettingsBody } from "./service.js";
|
||||
|
||||
// HTTP surface of the Car Wash module. Every route is behind the venue-module gate
|
||||
// FIRST (403 module_disabled), then a permission:
|
||||
// settings (master data) site:read / site:update — the site admin's job
|
||||
// queue / ticket lookup carwash:read — the wash desk
|
||||
// intake carwash:create
|
||||
// done / bay payment / void carwash:update
|
||||
// The sponsorship PROGRAM itself is a validation program row (id "carwash") and is
|
||||
// composed through the existing /api/validation/programs/:id route (site:update).
|
||||
|
||||
function sendError(reply: FastifyReply, err: unknown): FastifyReply {
|
||||
if (err instanceof CarwashError) {
|
||||
return reply.code(err.status).send({ error: err.message, ...(err.code ? { code: err.code } : {}) });
|
||||
}
|
||||
if (err instanceof NoShiftOpenError) {
|
||||
// The bay takes money on the CARWASH till: the wash operator's own shift must be
|
||||
// open (the booth's does not count). The desk shows its shift control on this code.
|
||||
return reply.code(409).send({ error: err.message, code: "no_shift", till: err.till });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
export async function carwashRoutes(app: FastifyInstance, deps: ServerModuleDeps, service: CarwashService): Promise<void> {
|
||||
const moduleOn = requireModule(deps.db, "carwash");
|
||||
const settingsRead = [moduleOn, requirePermission("site:read")];
|
||||
const settingsWrite = [moduleOn, requirePermission("site:update")];
|
||||
const read = [moduleOn, requirePermission("carwash:read")];
|
||||
const create = [moduleOn, requirePermission("carwash:create")];
|
||||
const update = [moduleOn, requirePermission("carwash:update")];
|
||||
|
||||
app.get("/api/carwash/settings", { preHandler: settingsRead }, async () => service.settings());
|
||||
|
||||
app.put<{ Body: SettingsBody }>("/api/carwash/settings", { preHandler: settingsWrite }, async (req, reply) => {
|
||||
try {
|
||||
return await service.saveSettings(req.body ?? {}, req.user.username);
|
||||
} catch (err) {
|
||||
return sendError(reply, err);
|
||||
}
|
||||
});
|
||||
|
||||
app.get<{ Params: { identity: string } }>("/api/carwash/session/:identity", { preHandler: read }, async (req) =>
|
||||
service.lookup(req.params.identity),
|
||||
);
|
||||
|
||||
app.get<{ Querystring: { scope?: string; limit?: string } }>("/api/carwash/orders", { preHandler: read }, async (req) => {
|
||||
if (req.query.scope === "recent") return { orders: service.recentOrders(Number(req.query.limit) || 100) };
|
||||
return { orders: service.openOrders() };
|
||||
});
|
||||
|
||||
app.post<{ Body: { identity?: string; categoryId?: string; serviceId?: string; payAt?: string } }>(
|
||||
"/api/carwash/orders",
|
||||
{ preHandler: create },
|
||||
async (req, reply) => {
|
||||
const b = req.body ?? {};
|
||||
// payAt is a SITE setting now; the desk no longer sends it. Accept it only when it
|
||||
// matches (the service refuses a mismatch) so a stale client cannot pick the till.
|
||||
if (b.payAt !== undefined && !isPayAt(b.payAt)) return reply.code(400).send({ error: "payAt must be booth|bay" });
|
||||
try {
|
||||
const order = await service.createOrder({
|
||||
identity: String(b.identity ?? ""),
|
||||
categoryId: String(b.categoryId ?? ""),
|
||||
serviceId: String(b.serviceId ?? ""),
|
||||
...(b.payAt !== undefined ? { payAt: b.payAt } : {}),
|
||||
actor: req.user.username,
|
||||
});
|
||||
return reply.code(201).send(order);
|
||||
} catch (err) {
|
||||
return sendError(reply, err);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
app.post<{ Params: { id: string } }>("/api/carwash/orders/:id/done", { preHandler: update }, async (req, reply) => {
|
||||
try {
|
||||
return await service.markDone(req.params.id, req.user.username);
|
||||
} catch (err) {
|
||||
return sendError(reply, err);
|
||||
}
|
||||
});
|
||||
|
||||
app.post<{ Params: { id: string }; Body: { tender?: Tender } }>(
|
||||
"/api/carwash/orders/:id/pay",
|
||||
{ preHandler: update },
|
||||
async (req, reply) => {
|
||||
try {
|
||||
return await service.payAtBay(req.params.id, (req.body?.tender ?? "cash") as Tender, req.user.username);
|
||||
} catch (err) {
|
||||
return sendError(reply, err);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
app.post<{ Params: { id: string }; Body: { reason?: string } }>(
|
||||
"/api/carwash/orders/:id/void",
|
||||
{ preHandler: update },
|
||||
async (req, reply) => {
|
||||
try {
|
||||
return await service.voidOrder(req.params.id, String(req.body?.reason ?? "").trim(), req.user.username);
|
||||
} catch (err) {
|
||||
return sendError(reply, err);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
carwashCategories,
|
||||
carwashConfig,
|
||||
carwashOrders,
|
||||
carwashPrices,
|
||||
carwashServices,
|
||||
desc,
|
||||
eq,
|
||||
inArray,
|
||||
isNull,
|
||||
type CarwashOrderRow,
|
||||
type Db,
|
||||
} from "@parking/db";
|
||||
import {
|
||||
CARWASH_PAY_AT,
|
||||
CARWASH_PAY_AT_DEFAULT,
|
||||
CARWASH_PROGRAM_ID,
|
||||
type CarWashPayAt,
|
||||
type CarwashOrderView,
|
||||
type CarwashSettingsView,
|
||||
type ChargeLine,
|
||||
type Tender,
|
||||
type TillId,
|
||||
} from "@parking/shared";
|
||||
import type { EventLog } from "../../event-log.js";
|
||||
import { effectiveModulesFor } from "../../modules.js";
|
||||
import type { ChargeProvider, PayStation } from "../../pay-station.js";
|
||||
import type { ShiftService } from "../../shift-service.js";
|
||||
import { applyValidation, liveValidations } from "../../validations.js";
|
||||
import type { ServerModuleDeps } from "../index.js";
|
||||
|
||||
// Car Wash — the module's whole behaviour (wiki/decisions/venue-modules.md, "Car Wash —
|
||||
// the pilot module" + "v1 answers"). Master data is mutable rows; every order freezes
|
||||
// what it sold (names + price) and signs its life onto the ledger; money at the bay is
|
||||
// a signed `carwash_payment`; money at the booth rides the parking `payment` as a
|
||||
// charge line (ChargeProvider below). The parking sponsorship is the site's "carwash"
|
||||
// VALIDATION program, applied through the shared applyValidation() when a wash is done
|
||||
// — the wash never touches parking code, it talks to the core through ServerModuleDeps.
|
||||
|
||||
/** A refusal the route maps to an HTTP status. */
|
||||
/** The till bay money lands on — declared by the module manifest (MODULES). */
|
||||
const CARWASH_TILL: TillId = "carwash";
|
||||
|
||||
export class CarwashError extends Error {
|
||||
constructor(
|
||||
readonly status: 400 | 404 | 409,
|
||||
message: string,
|
||||
readonly code?: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "CarwashError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface SettingsBody {
|
||||
categories?: { id?: string; name?: string; active?: boolean }[];
|
||||
services?: { id?: string; name?: string; active?: boolean }[];
|
||||
prices?: { categoryId?: string; serviceId?: string; priceMinor?: number }[];
|
||||
/** Where wash money is taken at this site (site-level policy). */
|
||||
payAt?: unknown;
|
||||
}
|
||||
|
||||
export interface CreateOrderInput {
|
||||
identity: string;
|
||||
categoryId: string;
|
||||
serviceId: string;
|
||||
/** Optional — the SITE policy decides; a stale client that sends a different value
|
||||
* is refused (409 pay_at_policy) rather than silently overridden. */
|
||||
payAt?: CarWashPayAt;
|
||||
actor: string;
|
||||
}
|
||||
|
||||
export interface TicketLookup {
|
||||
identity: string;
|
||||
found: boolean;
|
||||
open: boolean;
|
||||
subscription: boolean;
|
||||
plate: string | null;
|
||||
enteredAt: string | null;
|
||||
currency: string | null;
|
||||
orders: CarwashOrderView[];
|
||||
}
|
||||
|
||||
const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
||||
|
||||
/** Stable slug for a new master-data row: from the name, else a random id. */
|
||||
function slugify(name: string): string {
|
||||
const s = name
|
||||
.toLowerCase()
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 40);
|
||||
return s || randomUUID();
|
||||
}
|
||||
|
||||
export class CarwashService {
|
||||
readonly #db: Db;
|
||||
readonly #log: EventLog;
|
||||
readonly #pay: PayStation;
|
||||
readonly #shift: ShiftService;
|
||||
readonly #logger: FastifyBaseLogger;
|
||||
|
||||
constructor(deps: ServerModuleDeps, logger: FastifyBaseLogger) {
|
||||
this.#db = deps.db;
|
||||
this.#log = deps.eventLog;
|
||||
this.#pay = deps.payStation;
|
||||
this.#shift = deps.shiftService;
|
||||
this.#logger = logger;
|
||||
}
|
||||
|
||||
#enabled(): boolean {
|
||||
return effectiveModulesFor(this.#db).includes("carwash");
|
||||
}
|
||||
|
||||
// --- Settings (master data) -------------------------------------------------
|
||||
|
||||
settings(): CarwashSettingsView {
|
||||
const categories = this.#db
|
||||
.select()
|
||||
.from(carwashCategories)
|
||||
.where(isNull(carwashCategories.deletedAt))
|
||||
.orderBy(asc(carwashCategories.sortOrder), asc(carwashCategories.name))
|
||||
.all()
|
||||
.map((r) => ({ id: r.id, name: r.name, sortOrder: r.sortOrder, active: r.active }));
|
||||
const services = this.#db
|
||||
.select()
|
||||
.from(carwashServices)
|
||||
.where(isNull(carwashServices.deletedAt))
|
||||
.orderBy(asc(carwashServices.sortOrder), asc(carwashServices.name))
|
||||
.all()
|
||||
.map((r) => ({ id: r.id, name: r.name, sortOrder: r.sortOrder, active: r.active }));
|
||||
const live = new Set([...categories.map((c) => c.id), ...services.map((s) => s.id)]);
|
||||
const prices = this.#db
|
||||
.select()
|
||||
.from(carwashPrices)
|
||||
.all()
|
||||
.filter((p) => live.has(p.categoryId) && live.has(p.serviceId))
|
||||
.map((p) => ({ categoryId: p.categoryId, serviceId: p.serviceId, priceMinor: p.priceMinor }));
|
||||
return { categories, services, prices, currency: this.#currency(), payAt: this.payAt() };
|
||||
}
|
||||
|
||||
/** The site's wash-payment policy (Setup → Car wash). Missing row = the default. */
|
||||
payAt(): CarWashPayAt {
|
||||
const row = this.#db.select().from(carwashConfig).where(eq(carwashConfig.id, 1)).get();
|
||||
return row?.payAt ?? CARWASH_PAY_AT_DEFAULT;
|
||||
}
|
||||
|
||||
/** The site's currency = the active tariff's (the wash is priced in the same money
|
||||
* the booth takes). null when no tariff is published yet. */
|
||||
#currency(): string | null {
|
||||
try {
|
||||
// Any open session's quote carries it; without one, fall back to the tariff table.
|
||||
const row = this.#db.select().from(carwashOrders).orderBy(desc(carwashOrders.createdAt)).limit(1).get();
|
||||
if (row) return row.currency;
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return this.#pay.activeCurrency();
|
||||
}
|
||||
|
||||
/** Full-replacement save of the three lists. Rows missing from the body are
|
||||
* soft-deleted (orders already reference names + prices by value, so nothing
|
||||
* historical changes). Signs one config_change. */
|
||||
async saveSettings(body: SettingsBody, actor: string): Promise<CarwashSettingsView> {
|
||||
const now = new Date().toISOString();
|
||||
const upsertList = (
|
||||
table: typeof carwashCategories | typeof carwashServices,
|
||||
items: { id?: string; name?: string; active?: boolean }[] | undefined,
|
||||
label: string,
|
||||
): string[] => {
|
||||
if (items === undefined) {
|
||||
return this.#db.select({ id: table.id }).from(table).where(isNull(table.deletedAt)).all().map((r) => r.id);
|
||||
}
|
||||
if (!Array.isArray(items)) throw new CarwashError(400, `${label} must be an array`);
|
||||
const keep: string[] = [];
|
||||
let sort = 0;
|
||||
const seen = new Set<string>();
|
||||
for (const it of items) {
|
||||
const name = String(it?.name ?? "").trim();
|
||||
if (!name) throw new CarwashError(400, `${label}: every item needs a name`);
|
||||
let id = typeof it.id === "string" && it.id.trim() ? it.id.trim() : slugify(name);
|
||||
if (!ID_RE.test(id)) throw new CarwashError(400, `${label}: bad id "${id}"`);
|
||||
// Two new items slugging to the same id → disambiguate rather than merge.
|
||||
while (seen.has(id)) id = `${id}-${sort}`;
|
||||
seen.add(id);
|
||||
const active = it.active !== false;
|
||||
const existing = this.#db.select().from(table).where(eq(table.id, id)).get();
|
||||
if (existing) {
|
||||
this.#db.update(table).set({ name, sortOrder: sort, active, deletedAt: null, deletedBy: null }).where(eq(table.id, id)).run();
|
||||
} else {
|
||||
this.#db.insert(table).values({ id, name, sortOrder: sort, active }).run();
|
||||
}
|
||||
keep.push(id);
|
||||
sort += 1;
|
||||
}
|
||||
const live = this.#db.select({ id: table.id }).from(table).where(isNull(table.deletedAt)).all();
|
||||
for (const r of live) {
|
||||
if (!keep.includes(r.id)) {
|
||||
this.#db.update(table).set({ deletedAt: now, deletedBy: actor }).where(eq(table.id, r.id)).run();
|
||||
}
|
||||
}
|
||||
return keep;
|
||||
};
|
||||
|
||||
const categoryIds = upsertList(carwashCategories, body.categories, "categories");
|
||||
const serviceIds = upsertList(carwashServices, body.services, "services");
|
||||
|
||||
if (body.prices !== undefined) {
|
||||
if (!Array.isArray(body.prices)) throw new CarwashError(400, "prices must be an array");
|
||||
const rows: { categoryId: string; serviceId: string; priceMinor: number }[] = [];
|
||||
for (const p of body.prices) {
|
||||
const categoryId = String(p?.categoryId ?? "");
|
||||
const serviceId = String(p?.serviceId ?? "");
|
||||
const priceMinor = p?.priceMinor;
|
||||
if (!categoryIds.includes(categoryId)) throw new CarwashError(400, `prices: unknown category "${categoryId}"`);
|
||||
if (!serviceIds.includes(serviceId)) throw new CarwashError(400, `prices: unknown service "${serviceId}"`);
|
||||
if (!Number.isInteger(priceMinor) || (priceMinor as number) < 0) {
|
||||
throw new CarwashError(400, "prices: priceMinor must be a non-negative integer");
|
||||
}
|
||||
rows.push({ categoryId, serviceId, priceMinor: priceMinor as number });
|
||||
}
|
||||
this.#db.delete(carwashPrices).run();
|
||||
for (const r of rows) this.#db.insert(carwashPrices).values(r).run();
|
||||
}
|
||||
|
||||
await this.#log.append({
|
||||
type: "config_change",
|
||||
source: "manual",
|
||||
identity: "module:carwash",
|
||||
payload: {
|
||||
setting: "carwash.settings",
|
||||
value: { categories: categoryIds.length, services: serviceIds.length, prices: body.prices?.length ?? null },
|
||||
operator: actor,
|
||||
},
|
||||
});
|
||||
|
||||
// Where the money is taken — a site policy, signed on its own when it flips (it
|
||||
// decides which till the cash lands on and whether the booth barrier or the exit
|
||||
// reader releases the car; fraud-relevant, so it is attributed like other config).
|
||||
if (body.payAt !== undefined) {
|
||||
if (!isPayAt(body.payAt)) throw new CarwashError(400, "payAt must be booth|bay");
|
||||
const prev = this.payAt();
|
||||
if (body.payAt !== prev) {
|
||||
this.#db
|
||||
.insert(carwashConfig)
|
||||
.values({ id: 1, payAt: body.payAt, updatedAt: now, updatedBy: actor })
|
||||
.onConflictDoUpdate({ target: carwashConfig.id, set: { payAt: body.payAt, updatedAt: now, updatedBy: actor } })
|
||||
.run();
|
||||
await this.#log.append({
|
||||
type: "config_change",
|
||||
source: "manual",
|
||||
identity: "module:carwash",
|
||||
payload: { setting: "carwash.payAt", value: body.payAt, prev, operator: actor },
|
||||
});
|
||||
}
|
||||
}
|
||||
return this.settings();
|
||||
}
|
||||
|
||||
// --- Orders ---------------------------------------------------------------------
|
||||
|
||||
#view(r: CarwashOrderRow): CarwashOrderView {
|
||||
return {
|
||||
id: r.id,
|
||||
identity: r.identity,
|
||||
plate: r.plate,
|
||||
categoryId: r.categoryId,
|
||||
categoryName: r.categoryName,
|
||||
serviceId: r.serviceId,
|
||||
serviceName: r.serviceName,
|
||||
priceMinor: r.priceMinor,
|
||||
currency: r.currency,
|
||||
payAt: r.payAt,
|
||||
status: r.status,
|
||||
createdAt: r.createdAt,
|
||||
createdBy: r.createdBy,
|
||||
doneAt: r.doneAt,
|
||||
doneBy: r.doneBy,
|
||||
paidAt: r.paidAt,
|
||||
paidBy: r.paidBy,
|
||||
tender: (r.tender as Tender | null) ?? null,
|
||||
closed: r.status === "void" || (r.status === "done" && r.paidAt != null),
|
||||
validationEventId: r.validationEventId,
|
||||
voidBy: r.voidBy,
|
||||
voidReason: r.voidReason,
|
||||
};
|
||||
}
|
||||
|
||||
#row(id: string): CarwashOrderRow {
|
||||
const r = this.#db.select().from(carwashOrders).where(eq(carwashOrders.id, id)).get();
|
||||
if (!r) throw new CarwashError(404, "order not found");
|
||||
return r;
|
||||
}
|
||||
|
||||
/** The desk's queue: every order still needing something, oldest first. */
|
||||
openOrders(): CarwashOrderView[] {
|
||||
return this.#db
|
||||
.select()
|
||||
.from(carwashOrders)
|
||||
.where(inArray(carwashOrders.status, ["open", "done"]))
|
||||
.orderBy(asc(carwashOrders.createdAt))
|
||||
.all()
|
||||
.map((r) => this.#view(r))
|
||||
.filter((o) => !o.closed);
|
||||
}
|
||||
|
||||
/** Recent history (closed included), newest first. */
|
||||
recentOrders(limit = 100): CarwashOrderView[] {
|
||||
return this.#db
|
||||
.select()
|
||||
.from(carwashOrders)
|
||||
.orderBy(desc(carwashOrders.createdAt))
|
||||
.limit(Math.min(Math.max(limit, 1), 500))
|
||||
.all()
|
||||
.map((r) => this.#view(r));
|
||||
}
|
||||
|
||||
#ordersFor(identity: string): CarwashOrderView[] {
|
||||
return this.#db
|
||||
.select()
|
||||
.from(carwashOrders)
|
||||
.where(eq(carwashOrders.identity, identity))
|
||||
.orderBy(asc(carwashOrders.createdAt))
|
||||
.all()
|
||||
.map((r) => this.#view(r));
|
||||
}
|
||||
|
||||
/** Ticket → session facts the desk needs (the parking ticket IS the customer). */
|
||||
lookup(identity: string): TicketLookup {
|
||||
const id = identity.trim();
|
||||
const s = this.#pay.lookup(id);
|
||||
return {
|
||||
identity: id,
|
||||
found: s.found,
|
||||
open: s.open,
|
||||
subscription: s.subscription,
|
||||
plate: s.plate,
|
||||
enteredAt: s.enteredAt,
|
||||
currency: s.currency,
|
||||
orders: this.#ordersFor(id),
|
||||
};
|
||||
}
|
||||
|
||||
async createOrder(input: CreateOrderInput): Promise<CarwashOrderView> {
|
||||
const identity = input.identity.trim();
|
||||
if (!identity) throw new CarwashError(400, "identity (ticket) required");
|
||||
|
||||
const s = this.#pay.lookup(identity);
|
||||
if (!s.found) throw new CarwashError(404, "no session for ticket");
|
||||
if (!s.open) throw new CarwashError(409, "session is closed");
|
||||
if (s.subscription) throw new CarwashError(409, "subscription sessions: order the wash with payAt=bay", "subscription");
|
||||
|
||||
const category = this.#db
|
||||
.select()
|
||||
.from(carwashCategories)
|
||||
.where(and(eq(carwashCategories.id, input.categoryId), isNull(carwashCategories.deletedAt)))
|
||||
.get();
|
||||
if (!category || !category.active) throw new CarwashError(404, "category not found or inactive");
|
||||
const service = this.#db
|
||||
.select()
|
||||
.from(carwashServices)
|
||||
.where(and(eq(carwashServices.id, input.serviceId), isNull(carwashServices.deletedAt)))
|
||||
.get();
|
||||
if (!service || !service.active) throw new CarwashError(404, "service not found or inactive");
|
||||
const price = this.#db
|
||||
.select()
|
||||
.from(carwashPrices)
|
||||
.where(and(eq(carwashPrices.categoryId, category.id), eq(carwashPrices.serviceId, service.id)))
|
||||
.get();
|
||||
if (!price) throw new CarwashError(409, `no price for ${category.name} · ${service.name}`, "no_price");
|
||||
// The SITE decides where wash money is taken (Setup → Car wash); the order freezes
|
||||
// the policy in force. A client that still sends a different value is stale.
|
||||
const payAt = this.payAt();
|
||||
if (input.payAt !== undefined && input.payAt !== payAt) {
|
||||
throw new CarwashError(409, `this site takes wash money at the ${payAt === "bay" ? "bay" : "booth"}`, "pay_at_policy");
|
||||
}
|
||||
const currency = s.currency ?? this.#pay.activeCurrency();
|
||||
if (!currency) throw new CarwashError(409, "no active tariff (currency unknown)", "no_tariff");
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const row: CarwashOrderRow = {
|
||||
id: randomUUID(),
|
||||
identity,
|
||||
plate: s.plate,
|
||||
categoryId: category.id,
|
||||
categoryName: category.name,
|
||||
serviceId: service.id,
|
||||
serviceName: service.name,
|
||||
priceMinor: price.priceMinor,
|
||||
currency,
|
||||
payAt,
|
||||
status: "open",
|
||||
createdAt: now,
|
||||
createdBy: input.actor,
|
||||
doneAt: null,
|
||||
doneBy: null,
|
||||
paidAt: null,
|
||||
paidBy: null,
|
||||
tender: null,
|
||||
paymentEventId: null,
|
||||
validationEventId: null,
|
||||
voidAt: null,
|
||||
voidBy: null,
|
||||
voidReason: null,
|
||||
};
|
||||
this.#db.insert(carwashOrders).values(row).run();
|
||||
await this.#log.append({
|
||||
type: "carwash_order",
|
||||
source: "manual",
|
||||
identity,
|
||||
payload: {
|
||||
sessionRef: identity,
|
||||
orderId: row.id,
|
||||
action: "created",
|
||||
categoryName: row.categoryName,
|
||||
serviceName: row.serviceName,
|
||||
priceMinor: row.priceMinor,
|
||||
currency,
|
||||
payAt: row.payAt,
|
||||
operator: input.actor,
|
||||
},
|
||||
});
|
||||
return this.#view(row);
|
||||
}
|
||||
|
||||
/** The wash is finished: apply the site's sponsorship program to the parking session
|
||||
* (if one is configured and active), then — for a bay order already paid — settle
|
||||
* the parking session so the exit reader opens. */
|
||||
async markDone(id: string, actor: string): Promise<CarwashOrderView> {
|
||||
const r = this.#row(id);
|
||||
if (r.status === "void") throw new CarwashError(409, "order is void");
|
||||
if (r.status === "done") throw new CarwashError(409, "order is already done");
|
||||
const now = new Date().toISOString();
|
||||
|
||||
let validationEventId: string | null = null;
|
||||
// Wash context for the wash-only discount modes: the WASH WINDOW in minutes — from
|
||||
// the order's intake to now (= done) — and the order's frozen price. NOT the time
|
||||
// since entry: a car parked for hours before it asks for a wash still pays for those
|
||||
// hours (found 2026-09-05 on a long-open ticket that would have been fully comped).
|
||||
// The credit lands at the start of the billed period (that is how timeCredit
|
||||
// folds), so for a flat tariff the money is identical; a stepped/daily-cap tariff
|
||||
// may differ by an increment. See applyValidation().
|
||||
const washMinutes = Math.max(0, Math.ceil((Date.now() - Date.parse(r.createdAt)) / 60_000));
|
||||
const applied = await applyValidation(this.#db, this.#log, {
|
||||
programId: CARWASH_PROGRAM_ID,
|
||||
identity: r.identity,
|
||||
actor,
|
||||
wash: { washMinutes, priceMinor: r.priceMinor },
|
||||
});
|
||||
if (applied.ok) validationEventId = applied.eventId;
|
||||
else if (applied.status !== 404 && !/already applied/.test(applied.error)) {
|
||||
// A real refusal (session closed, daily cap …) — the wash is still done; the
|
||||
// customer simply gets no sponsorship. Keep it visible in the log.
|
||||
this.#logger.warn(`carwash sponsorship not applied for ${r.identity}: ${applied.error}`);
|
||||
}
|
||||
|
||||
this.#db
|
||||
.update(carwashOrders)
|
||||
.set({ status: "done", doneAt: now, doneBy: actor, validationEventId })
|
||||
.where(eq(carwashOrders.id, id))
|
||||
.run();
|
||||
await this.#log.append({
|
||||
type: "carwash_order",
|
||||
source: "manual",
|
||||
identity: r.identity,
|
||||
payload: {
|
||||
sessionRef: r.identity,
|
||||
orderId: id,
|
||||
action: "done",
|
||||
categoryName: r.categoryName,
|
||||
serviceName: r.serviceName,
|
||||
priceMinor: r.priceMinor,
|
||||
currency: r.currency,
|
||||
payAt: r.payAt,
|
||||
...(validationEventId ? { validationEventId } : {}),
|
||||
operator: actor,
|
||||
},
|
||||
});
|
||||
const updated = this.#row(id);
|
||||
if (updated.payAt === "bay" && updated.paidAt != null) await this.#settleParkingIfFree(updated, actor);
|
||||
return this.#view(updated);
|
||||
}
|
||||
|
||||
/** Money taken AT THE BAY. Needs an open CARWASH shift (it is the wash operator's
|
||||
* drawer money, never the booth's — wiki/concepts/shift.md "Tills"); signs a
|
||||
* carwash_payment on that till; then, if the wash is also done, settles the
|
||||
* parking session. */
|
||||
async payAtBay(id: string, tender: Tender, actor: string): Promise<CarwashOrderView> {
|
||||
const r = this.#row(id);
|
||||
if (r.status === "void") throw new CarwashError(409, "order is void");
|
||||
if (r.payAt !== "bay") throw new CarwashError(409, "this order is paid at the booth", "pay_at_booth");
|
||||
if (r.paidAt != null) throw new CarwashError(409, "order is already paid");
|
||||
if (tender !== "cash" && tender !== "card") throw new CarwashError(400, "tender must be cash|card");
|
||||
this.#shift.requireOpenShift(CARWASH_TILL);
|
||||
|
||||
const ev = await this.#log.append({
|
||||
type: "carwash_payment",
|
||||
source: "manual",
|
||||
identity: r.identity,
|
||||
payload: {
|
||||
sessionRef: r.identity,
|
||||
orderId: id,
|
||||
amountMinor: r.priceMinor,
|
||||
currency: r.currency,
|
||||
tender,
|
||||
till: CARWASH_TILL,
|
||||
categoryName: r.categoryName,
|
||||
serviceName: r.serviceName,
|
||||
operator: actor,
|
||||
},
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
this.#db
|
||||
.update(carwashOrders)
|
||||
.set({ paidAt: now, paidBy: actor, tender, paymentEventId: ev.id })
|
||||
.where(eq(carwashOrders.id, id))
|
||||
.run();
|
||||
const updated = this.#row(id);
|
||||
if (updated.status === "done") await this.#settleParkingIfFree(updated, actor, tender);
|
||||
return this.#view(updated);
|
||||
}
|
||||
|
||||
/** A bay-paid, done wash: if the sponsorship made the parking session zero-due, sign
|
||||
* the $0 parking payment now — that is what the exit READER checks (a validation
|
||||
* alone opens nothing; see exit-flow.ts). A remaining balance stays for the booth. */
|
||||
async #settleParkingIfFree(r: CarwashOrderRow, actor: string, tender: Tender = "cash"): Promise<void> {
|
||||
try {
|
||||
const s = this.#pay.lookup(r.identity);
|
||||
if (!s.open || s.subscription || s.paidAt != null) return;
|
||||
const q = this.#pay.quote(r.identity);
|
||||
if (q.amountMinor !== 0) return;
|
||||
await this.#pay.pay(r.identity, tender);
|
||||
this.#logger.info(`carwash: parking session ${r.identity} settled at zero after bay payment (by ${actor})`);
|
||||
} catch (err) {
|
||||
this.#logger.warn(`carwash: could not settle parking for ${r.identity}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async voidOrder(id: string, reason: string, actor: string): Promise<CarwashOrderView> {
|
||||
const r = this.#row(id);
|
||||
if (r.status === "void") throw new CarwashError(409, "order is already void");
|
||||
if (r.paidAt != null) throw new CarwashError(409, "a paid order cannot be voided", "paid");
|
||||
const now = new Date().toISOString();
|
||||
// Take back the sponsorship if it is still live (not consumed by a payment).
|
||||
if (r.validationEventId) {
|
||||
const live = liveValidations(this.#db, r.identity).find((v) => v.eventId === r.validationEventId);
|
||||
if (live) {
|
||||
await this.#log.append({
|
||||
type: "validation",
|
||||
source: "manual",
|
||||
identity: r.identity,
|
||||
payload: {
|
||||
sessionRef: r.identity,
|
||||
refId: r.validationEventId,
|
||||
programId: live.programId,
|
||||
programLabel: live.label,
|
||||
operator: actor,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
this.#db
|
||||
.update(carwashOrders)
|
||||
.set({ status: "void", voidAt: now, voidBy: actor, voidReason: reason || null })
|
||||
.where(eq(carwashOrders.id, id))
|
||||
.run();
|
||||
await this.#log.append({
|
||||
type: "carwash_order",
|
||||
source: "manual",
|
||||
identity: r.identity,
|
||||
payload: {
|
||||
sessionRef: r.identity,
|
||||
orderId: id,
|
||||
action: "void",
|
||||
categoryName: r.categoryName,
|
||||
serviceName: r.serviceName,
|
||||
priceMinor: r.priceMinor,
|
||||
currency: r.currency,
|
||||
payAt: r.payAt,
|
||||
reason: reason || undefined,
|
||||
operator: actor,
|
||||
},
|
||||
});
|
||||
return this.#view(this.#row(id));
|
||||
}
|
||||
|
||||
// --- Booth settlement hook ------------------------------------------------------
|
||||
|
||||
/** Orders with payAt = "booth" ride the parking payment as charge lines; the core
|
||||
* calls back after the payment is signed so they are marked paid. Off = no lines. */
|
||||
chargeProvider(): ChargeProvider {
|
||||
return {
|
||||
lines: (identity) => {
|
||||
if (!this.#enabled()) return [];
|
||||
return this.#db
|
||||
.select()
|
||||
.from(carwashOrders)
|
||||
.where(and(eq(carwashOrders.identity, identity), eq(carwashOrders.payAt, "booth"), isNull(carwashOrders.paidAt)))
|
||||
.all()
|
||||
.filter((r) => r.status !== "void")
|
||||
.map((r) => ({
|
||||
module: "carwash" as const,
|
||||
ref: r.id,
|
||||
label: `Lavazh — ${r.categoryName} · ${r.serviceName}`,
|
||||
amountMinor: r.priceMinor,
|
||||
}));
|
||||
},
|
||||
onPaid: async (_identity, lines, payment) => {
|
||||
const now = new Date().toISOString();
|
||||
for (const l of lines) {
|
||||
if (l.module !== "carwash") continue;
|
||||
this.#db
|
||||
.update(carwashOrders)
|
||||
.set({ paidAt: now, paidBy: payment.operator ?? "booth", tender: payment.tender, paymentEventId: payment.eventId })
|
||||
.where(and(eq(carwashOrders.id, l.ref), isNull(carwashOrders.paidAt)))
|
||||
.run();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Type guard for the void body etc. */
|
||||
export function isPayAt(v: unknown): v is CarWashPayAt {
|
||||
return typeof v === "string" && (CARWASH_PAY_AT as readonly string[]).includes(v);
|
||||
}
|
||||
@@ -2,7 +2,10 @@ import type { FastifyInstance } from "fastify";
|
||||
import type { Db } from "@parking/db";
|
||||
import { MODULES, parseEntitledModules, type ModuleId } from "@parking/shared";
|
||||
import type { EventLog } from "../event-log.js";
|
||||
import type { PayStation } from "../pay-station.js";
|
||||
import type { ShiftService } from "../shift-service.js";
|
||||
import { effectiveModulesFor } from "../modules.js";
|
||||
import { carwashModule } from "./carwash/index.js";
|
||||
import { validationModule } from "./validation/index.js";
|
||||
|
||||
// The server-side module registry. A module's routes live in its own folder
|
||||
@@ -15,9 +18,15 @@ import { validationModule } from "./validation/index.js";
|
||||
// the flat list in server.ts. That is deliberate — the seam is drawn, the code moves
|
||||
// across it subsystem by subsystem as each is touched, not in one big move.
|
||||
|
||||
/** What the core hands a module at registration. Modules reach the core ONLY through
|
||||
* these (never by importing another module): the DB, the signed ledger, the booth
|
||||
* settlement (to fold charges in / settle a session — PayStation.registerChargeProvider,
|
||||
* quote, pay) and the shift service (money needs an open shift). */
|
||||
export interface ServerModuleDeps {
|
||||
db: Db;
|
||||
eventLog: EventLog;
|
||||
payStation: PayStation;
|
||||
shiftService: ShiftService;
|
||||
}
|
||||
|
||||
export interface ServerModule {
|
||||
@@ -27,6 +36,7 @@ export interface ServerModule {
|
||||
|
||||
const SERVER_MODULES: Partial<Record<ModuleId, ServerModule>> = {
|
||||
validation: validationModule,
|
||||
carwash: carwashModule,
|
||||
};
|
||||
|
||||
/** Register every folder-based module in registry order, then log what this site
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { desc, eq, ledgerEvents, sessions, subscriptions, tariffVersions, tariffs, type Db } from "@parking/db";
|
||||
import { priceSession, type TariffStructure, type Tender, type ValidationLine } from "@parking/shared";
|
||||
import { BOOTH_TILL, priceSession, 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";
|
||||
@@ -29,6 +29,18 @@ export class NoTariffError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A module that folds its own charges into a booth settlement (venue-modules.md):
|
||||
* `lines(identity)` returns the open charges for the session (e.g. wash orders with
|
||||
* payAt = "booth"); after the `payment` is signed, `onPaid` lets the module mark them
|
||||
* settled. Registered by the module at boot (registerChargeProvider) — PayStation
|
||||
* never imports a module.
|
||||
*/
|
||||
export interface ChargeProvider {
|
||||
lines(identity: string): ChargeLine[];
|
||||
onPaid(identity: string, lines: ChargeLine[], payment: { eventId: string; tender: Tender; operator?: string }): Promise<void>;
|
||||
}
|
||||
|
||||
export interface Quote {
|
||||
readonly identity: string;
|
||||
/** Vehicle entry time (the session's original entry; for display/audit). */
|
||||
@@ -39,8 +51,14 @@ export interface Quote {
|
||||
* is priced as a fresh stay from there → now, with its own daily-cap ladder, NOT
|
||||
* "full stay minus paid" (which a daily cap collapses toward zero). */
|
||||
readonly periodStart: string;
|
||||
/** Amount owed now: the fee for [periodStart → now], NET of merchant validations. */
|
||||
/** Amount owed now: the parking fee for [periodStart → now] NET of merchant
|
||||
* validations, PLUS any module charge lines (a wash paid at the booth). */
|
||||
readonly amountMinor: number;
|
||||
/** The parking-only net (amountMinor − chargesMinor). */
|
||||
readonly parkingMinor: number;
|
||||
/** Non-parking charges folded in by modules (see ChargeProvider). */
|
||||
readonly chargeLines: ChargeLine[];
|
||||
readonly chargesMinor: number;
|
||||
/** The pre-validation fee (= amountMinor when no validations apply). */
|
||||
readonly grossMinor: number;
|
||||
/** Total the merchant validations took off (gross − net). */
|
||||
@@ -133,12 +151,16 @@ export interface SessionLookup {
|
||||
readonly grossMinor: number | null;
|
||||
readonly discountMinor: number | null;
|
||||
readonly validationLines: ValidationLine[];
|
||||
/** Module charge lines folded into `amountMinor` (e.g. a wash paid at the booth). */
|
||||
readonly chargeLines: ChargeLine[];
|
||||
readonly chargesMinor: number | null;
|
||||
}
|
||||
|
||||
export class PayStation {
|
||||
readonly #db: Db;
|
||||
readonly #log: EventLog;
|
||||
readonly #logger: FastifyBaseLogger;
|
||||
readonly #chargeProviders: ChargeProvider[] = [];
|
||||
|
||||
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger) {
|
||||
this.#db = db;
|
||||
@@ -146,6 +168,30 @@ export class PayStation {
|
||||
this.#logger = logger;
|
||||
}
|
||||
|
||||
/** Let a module fold its charges into booth settlements (see ChargeProvider). */
|
||||
registerChargeProvider(p: ChargeProvider): void {
|
||||
this.#chargeProviders.push(p);
|
||||
}
|
||||
|
||||
/** The currency of the tariff in force right now (null = none published). Modules
|
||||
* price their own goods in the same money the booth takes. */
|
||||
activeCurrency(): string | null {
|
||||
return this.#tariffVersionFor(new Date().toISOString())?.currency ?? null;
|
||||
}
|
||||
|
||||
#chargeLines(identity: string): ChargeLine[] {
|
||||
const out: ChargeLine[] = [];
|
||||
for (const p of this.#chargeProviders) {
|
||||
try {
|
||||
out.push(...p.lines(identity));
|
||||
} catch (err) {
|
||||
// A module's fault must never block a parking settlement — log and price without it.
|
||||
this.#logger.error(`charge provider failed for ${identity}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Price an open session. Normally the period is entry→now. But for an OVERSTAY — a
|
||||
* paid session whose walk-back grace has lapsed (the car re-parked, or a new period
|
||||
* began) — the customer is billed for a FRESH period from grace-expiry→now, with its
|
||||
@@ -184,11 +230,16 @@ export class PayStation {
|
||||
category,
|
||||
validations,
|
||||
);
|
||||
const chargeLines = this.#chargeLines(identity);
|
||||
const chargesMinor = chargeLines.reduce((sum, l) => sum + l.amountMinor, 0);
|
||||
return {
|
||||
identity,
|
||||
enteredAt: entry.occurredAt,
|
||||
periodStart: p.periodStart,
|
||||
amountMinor: p.amountMinor,
|
||||
amountMinor: p.amountMinor + chargesMinor,
|
||||
parkingMinor: p.amountMinor,
|
||||
chargeLines,
|
||||
chargesMinor,
|
||||
grossMinor: p.grossMinor,
|
||||
discountMinor: p.discountMinor,
|
||||
validationLines: p.validationLines,
|
||||
@@ -246,6 +297,7 @@ export class PayStation {
|
||||
amountMinor,
|
||||
currency: subWindow.currency ?? undefined,
|
||||
tender,
|
||||
till: BOOTH_TILL,
|
||||
...(subWindow.tariffVersionId ? { tariffVersionId: subWindow.tariffVersionId } : {}),
|
||||
subscriptionWindowCharge: true,
|
||||
...(overrideMinor != null ? { reason: "operator-set amount", quotedMinor: subWindow.dueMinor } : {}),
|
||||
@@ -258,7 +310,7 @@ export class PayStation {
|
||||
const q = this.quote(identity);
|
||||
const amountMinor = overrideMinor ?? q.amountMinor;
|
||||
|
||||
await this.#log.append({
|
||||
const paymentEvent = await this.#log.append({
|
||||
type: "payment",
|
||||
source: "manual",
|
||||
identity,
|
||||
@@ -267,7 +319,19 @@ export class PayStation {
|
||||
amountMinor,
|
||||
currency: q.currency,
|
||||
tender,
|
||||
// Parking money is BOOTH money (a wash paid at the booth rides along as
|
||||
// chargeLines, so it is booth money too). See wiki/concepts/shift.md "Tills".
|
||||
till: BOOTH_TILL,
|
||||
tariffVersionId: q.tariffVersionId,
|
||||
// Module charges (e.g. a wash paid at the booth): frozen as lines so the
|
||||
// receipt reproduces and reporting can split parking from the rest.
|
||||
...(q.chargeLines.length
|
||||
? {
|
||||
chargeLines: q.chargeLines.map((l) => ({ ...l })),
|
||||
chargesMinor: q.chargesMinor,
|
||||
parkingMinor: q.parkingMinor,
|
||||
}
|
||||
: {}),
|
||||
// The exit flow reads graceExitMin off the payment to validate the
|
||||
// walk-back window without re-resolving the tariff.
|
||||
graceExitMin: q.graceExitMin,
|
||||
@@ -294,6 +358,17 @@ export class PayStation {
|
||||
this.#logger.error(`session-cache mark-paid failed for ${identity}: ${(err as Error).message}`);
|
||||
}
|
||||
|
||||
// Let each module mark the charge lines it contributed as settled by this payment.
|
||||
if (q.chargeLines.length) {
|
||||
for (const p of this.#chargeProviders) {
|
||||
try {
|
||||
await p.onPaid(identity, q.chargeLines, { eventId: paymentEvent.id, tender });
|
||||
} catch (err) {
|
||||
this.#logger.error(`charge provider onPaid failed for ${identity}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.#logger.info(`payment ${amountMinor} ${q.currency} (${tender}) for ${identity}`);
|
||||
return { amountMinor, currency: q.currency };
|
||||
}
|
||||
@@ -320,6 +395,7 @@ export class PayStation {
|
||||
withinGrace: false, graceExpiresAt: null,
|
||||
overstay: false, subscription: false, subscriptionId: null, subscriptionHolder: null, plate: null,
|
||||
grossMinor: null, discountMinor: null, validationLines: [],
|
||||
chargeLines: [], chargesMinor: null,
|
||||
};
|
||||
}
|
||||
// Subscription occurrence? The entry payload carries permit:true + permitId.
|
||||
@@ -360,6 +436,8 @@ export class PayStation {
|
||||
let grossMinor: number | null = null;
|
||||
let discountMinor: number | null = null;
|
||||
let validationLines: ValidationLine[] = [];
|
||||
let chargeLines: ChargeLine[] = [];
|
||||
let chargesMinor: number | null = null;
|
||||
if (open && !isSubscription) {
|
||||
try {
|
||||
const q = this.quote(id);
|
||||
@@ -368,6 +446,8 @@ export class PayStation {
|
||||
grossMinor = q.grossMinor;
|
||||
discountMinor = q.discountMinor;
|
||||
validationLines = q.validationLines;
|
||||
chargeLines = q.chargeLines;
|
||||
chargesMinor = q.chargesMinor;
|
||||
} catch {
|
||||
/* no active tariff — leave null; modal shows session without a price */
|
||||
}
|
||||
@@ -389,6 +469,7 @@ export class PayStation {
|
||||
subscriptionHolder: this.#holderOf(subscriptionId),
|
||||
plate: plateForIdentity(this.#db, id)?.plate ?? null,
|
||||
grossMinor, discountMinor, validationLines,
|
||||
chargeLines, chargesMinor,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { Db } from "@parking/db";
|
||||
import { requirePermission, roleHasPermissions } from "../auth.js";
|
||||
import { accessibleTillsFor, parseTill } from "../modules.js";
|
||||
import { InvalidCashMovementError, type MovementStatus, type ShiftService } from "../shift-service.js";
|
||||
|
||||
// Drawer cash movements (manned mode). Redesigned 2026-07-01: an operator RECORDS a
|
||||
@@ -14,6 +16,8 @@ import { InvalidCashMovementError, type MovementStatus, type ShiftService } from
|
||||
// amount that carries across shifts).
|
||||
// The drawer BALANCE math is unchanged — a movement counts immediately; a denial is a
|
||||
// judgment about the operator settled outside the app, never a cash reversal.
|
||||
// TILLS: a movement names the drawer it moved in/out of (`till`, default booth); the
|
||||
// balance and the list take a `till` filter. See wiki/concepts/shift.md "Tills".
|
||||
|
||||
interface MovementBody {
|
||||
/** Direction is the document TYPE, not a sign: cash_in = Mandat Arkëtimi (pay-IN),
|
||||
@@ -23,6 +27,8 @@ interface MovementBody {
|
||||
amountMinor: number;
|
||||
reason?: string;
|
||||
currency?: string;
|
||||
/** Which drawer (default: the booth). */
|
||||
till?: string;
|
||||
}
|
||||
|
||||
interface ReviewBody {
|
||||
@@ -36,9 +42,11 @@ interface ReviewBody {
|
||||
interface MovementsQuery {
|
||||
/** Reviewers only: filter to pending/authorized/denied. Ignored for non-reviewers. */
|
||||
status?: MovementStatus;
|
||||
/** Filter to one till; absent = every till. */
|
||||
till?: string;
|
||||
}
|
||||
|
||||
export async function drawerRoutes(app: FastifyInstance, shift: ShiftService): Promise<void> {
|
||||
export async function drawerRoutes(app: FastifyInstance, db: Db, shift: ShiftService): Promise<void> {
|
||||
const createGuard = requirePermission("drawer:create");
|
||||
const reviewGuard = requirePermission("drawer:review");
|
||||
const readGuard = requirePermission("shift:read");
|
||||
@@ -49,6 +57,12 @@ export async function drawerRoutes(app: FastifyInstance, shift: ShiftService): P
|
||||
if (b.type !== "cash_in" && b.type !== "cash_out") {
|
||||
return reply.code(400).send({ error: "type must be cash_in or cash_out" });
|
||||
}
|
||||
const till = parseTill(db, b.till);
|
||||
if (!till) return reply.code(400).send({ error: "unknown till", code: "bad_till" });
|
||||
// Moving a till's cash needs that till's module permission (see routes/shift.ts).
|
||||
if (!accessibleTillsFor(db, req.user.roleId).includes(till)) {
|
||||
return reply.code(403).send({ error: `your role cannot work the ${till} till`, code: "till_forbidden", till });
|
||||
}
|
||||
try {
|
||||
return await shift.recordVoucher({
|
||||
type: b.type,
|
||||
@@ -56,6 +70,7 @@ export async function drawerRoutes(app: FastifyInstance, shift: ShiftService): P
|
||||
amountMinor: b.amountMinor,
|
||||
reason: b.reason ?? "",
|
||||
currency: b.currency,
|
||||
till,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof InvalidCashMovementError) return reply.code(400).send({ error: err.message });
|
||||
@@ -65,20 +80,27 @@ export async function drawerRoutes(app: FastifyInstance, shift: ShiftService): P
|
||||
|
||||
// List movements + review status. Operators are hard-scoped to their OWN movements; a
|
||||
// reviewer sees ALL and may filter by status (the pending review queue).
|
||||
app.get<{ Querystring: MovementsQuery }>("/api/drawer/movements", { preHandler: readGuard }, async (req) => {
|
||||
app.get<{ Querystring: MovementsQuery }>("/api/drawer/movements", { preHandler: readGuard }, async (req, reply) => {
|
||||
const canReview = roleHasPermissions(req.user.roleId, ["drawer:review"]);
|
||||
const q = req.query ?? {};
|
||||
const status = canReview && ["pending", "authorized", "denied"].includes(q.status ?? "") ? q.status : undefined;
|
||||
const till = q.till?.trim() ? parseTill(db, q.till.trim()) : undefined;
|
||||
if (till === null) return reply.code(400).send({ error: "unknown till", code: "bad_till" });
|
||||
const movements = shift.movementsWithStatus({
|
||||
operator: canReview ? undefined : req.user.username,
|
||||
status,
|
||||
till,
|
||||
});
|
||||
return { movements, scope: canReview ? "all" : "self" };
|
||||
});
|
||||
|
||||
// The physical drawer balance now. Same visibility as the open shift's X-report
|
||||
// (shift:read) — the drawer is a single site-wide till, not per-operator data.
|
||||
app.get("/api/drawer/balance", { preHandler: readGuard }, async () => shift.drawerBalance());
|
||||
// A till's physical drawer balance now. Same visibility as the open shift's X-report
|
||||
// (shift:read) — a drawer is a shared till, not per-operator data.
|
||||
app.get<{ Querystring: { till?: string } }>("/api/drawer/balance", { preHandler: readGuard }, async (req, reply) => {
|
||||
const till = parseTill(db, req.query?.till);
|
||||
if (!till) return reply.code(400).send({ error: "unknown till", code: "bad_till" });
|
||||
return { till, ...shift.drawerBalance(till) };
|
||||
});
|
||||
|
||||
// Admin AUTHORIZES or DENIES a recorded movement. A flag only — no cash reversal.
|
||||
app.post<{ Body: ReviewBody }>("/api/drawer/review", { preHandler: reviewGuard }, async (req, reply) => {
|
||||
|
||||
@@ -142,7 +142,7 @@ describe("drawer balance (the till NOW)", () => {
|
||||
const { cookie } = await login(app, viewer.username, viewer.password);
|
||||
const ok = await app.inject({ method: "GET", url: "/api/drawer/balance", headers: { cookie } });
|
||||
expect(ok.statusCode).toBe(200);
|
||||
expect(ok.json()).toEqual({ balanceMinor: 0, currency: null });
|
||||
expect(ok.json()).toEqual({ till: "booth", balanceMinor: 0, currency: null });
|
||||
|
||||
const outsider = await seedUser(db, { username: "noshift", roleId: "noshift", permissions: ["site:read"] });
|
||||
const other = await login(app, outsider.username, outsider.password);
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { FastifyInstance, FastifyReply } from "fastify";
|
||||
import type { Db } from "@parking/db";
|
||||
import type { TillId } from "@parking/shared";
|
||||
import { requirePermission, roleHasPermissions } from "../auth.js";
|
||||
import { accessibleTillsFor, effectiveTillsFor, parseTill } from "../modules.js";
|
||||
import { NoOpenShiftError, ShiftAlreadyOpenError, type ShiftService } from "../shift-service.js";
|
||||
|
||||
interface ShiftsQuery {
|
||||
@@ -8,43 +11,85 @@ interface ShiftsQuery {
|
||||
/** ISO window over shift START time. */
|
||||
from?: string;
|
||||
to?: string;
|
||||
/** Filter to one till; absent = every till. */
|
||||
till?: string;
|
||||
}
|
||||
|
||||
interface TillQuery {
|
||||
/** Which till (default: the booth). */
|
||||
till?: string;
|
||||
}
|
||||
interface TillBody {
|
||||
till?: string;
|
||||
}
|
||||
|
||||
// Shift endpoints (manned mode). The operator is the logged-in user; a shift is
|
||||
// opened/closed explicitly (not time-based — see wiki/concepts/shift.md and
|
||||
// local-jwt-auth.md "until logout"). End Shift signs a shift_z_report + prints it.
|
||||
//
|
||||
// TILLS: every endpoint takes a `till` (query on GET, body on POST; default booth).
|
||||
// A till is addressable only when the module that declares it is effective here
|
||||
// (400 otherwise) — the wash desk's shift control passes till=carwash. WORKING a till
|
||||
// (open/close, its state) additionally needs the role to hold that till's module
|
||||
// permission (booth: session:read; carwash: carwash:read) — 403 `till_forbidden` — so a
|
||||
// wash operator's role can never open the booth's shift, nor a booth operator the
|
||||
// wash's. History (`/api/shifts`) stays scoped by shift:read/cash, not by till.
|
||||
|
||||
export async function shiftRoutes(app: FastifyInstance, shift: ShiftService): Promise<void> {
|
||||
export async function shiftRoutes(app: FastifyInstance, db: Db, shift: ShiftService): Promise<void> {
|
||||
// Reading the shift state vs. opening/closing one's own shift.
|
||||
const readGuard = requirePermission("shift:read");
|
||||
const guard = requirePermission("shift:create");
|
||||
|
||||
// The SITE-WIDE shift state (at most one shift open at a time). The UI uses this
|
||||
// to render the header control: no shift → "Open"; my shift → "Close" (enabled);
|
||||
// someone else's shift → disabled. Also returns the live drawer balance.
|
||||
// - open: the open shift { startedAt, operator } or null (site-wide)
|
||||
// - isMine: true iff the open shift belongs to the requesting operator
|
||||
// - operator: the requesting user (for the UI's own identity)
|
||||
app.get("/api/shift/current", { preHandler: readGuard }, async (req) => {
|
||||
const me = req.user.username;
|
||||
const open = shift.currentOpenShift();
|
||||
const badTill = (reply: FastifyReply) => reply.code(400).send({ error: "unknown till", code: "bad_till" });
|
||||
const forbidden = (reply: FastifyReply, till: TillId) =>
|
||||
reply.code(403).send({ error: `your role cannot work the ${till} till`, code: "till_forbidden", till });
|
||||
const mayWork = (roleId: string, till: TillId) => accessibleTillsFor(db, roleId).includes(till);
|
||||
|
||||
const statusOf = (till: TillId, me: string) => {
|
||||
const open = shift.currentOpenShift(till);
|
||||
const heldBy = open?.identity ?? null;
|
||||
const drawer = shift.drawerBalance();
|
||||
const drawer = shift.drawerBalance(till);
|
||||
return {
|
||||
operator: me,
|
||||
till,
|
||||
open: open ? { startedAt: open.occurredAt, operator: heldBy } : null,
|
||||
isMine: open != null && heldBy === me,
|
||||
drawerMinor: drawer.balanceMinor,
|
||||
currency: drawer.currency,
|
||||
};
|
||||
};
|
||||
|
||||
// The shift state of ONE till (at most one shift open per till). The UI uses this
|
||||
// to render a till's control: no shift → "Open"; my shift → "Close" (enabled);
|
||||
// someone else's shift → disabled. Also returns the live drawer balance.
|
||||
// - till: which till this describes
|
||||
// - open: the open shift { startedAt, operator } or null
|
||||
// - isMine: true iff the open shift belongs to the requesting operator
|
||||
// - operator: the requesting user (for the UI's own identity)
|
||||
// - tills: every till THIS ROLE may work (the booth + effective modules' tills it
|
||||
// holds the permission for) — what the UI offers controls for
|
||||
app.get<{ Querystring: TillQuery }>("/api/shift/current", { preHandler: readGuard }, async (req, reply) => {
|
||||
const till = parseTill(db, req.query?.till);
|
||||
if (!till) return badTill(reply);
|
||||
if (!mayWork(req.user.roleId, till)) return forbidden(reply, till);
|
||||
return { operator: req.user.username, tills: accessibleTillsFor(db, req.user.roleId), ...statusOf(till, req.user.username) };
|
||||
});
|
||||
|
||||
// The state of every till this role may work, in one read — the shift hub lists
|
||||
// each open shift and offers "start" for the idle ones.
|
||||
app.get("/api/shift/tills", { preHandler: readGuard }, async (req) => {
|
||||
const me = req.user.username;
|
||||
return { operator: me, tills: accessibleTillsFor(db, req.user.roleId).map((t) => statusOf(t, me)) };
|
||||
});
|
||||
|
||||
// Mid-shift X-report: a READ-ONLY "so far" snapshot of the OPEN shift's takings +
|
||||
// drawer (opening float, cash/card taken, pay-ins/outs, expected drawer), computed
|
||||
// as of now. Appends nothing — it's not an accountability mark, just a projection
|
||||
// (the Z-report at close is the signed record). 204 when no shift is open.
|
||||
app.get("/api/shift/report", { preHandler: readGuard }, async (_req, reply) => {
|
||||
const report = shift.currentReport();
|
||||
app.get<{ Querystring: TillQuery }>("/api/shift/report", { preHandler: readGuard }, async (req, reply) => {
|
||||
const till = parseTill(db, req.query?.till);
|
||||
if (!till) return badTill(reply);
|
||||
if (!mayWork(req.user.roleId, till)) return forbidden(reply, till);
|
||||
const report = shift.currentReport(till);
|
||||
if (!report) return reply.code(204).send();
|
||||
return report;
|
||||
});
|
||||
@@ -54,36 +99,49 @@ export async function shiftRoutes(app: FastifyInstance, shift: ShiftService): Pr
|
||||
// - `shift:cash` (admin-grade) → all operators, optionally filtered by
|
||||
// `operator` and a `from`/`to` time window over each shift's START.
|
||||
// This keeps one operator from reading another's takings while letting admins
|
||||
// reconcile across the site. The data is the signed shift_z_report chain.
|
||||
app.get<{ Querystring: ShiftsQuery }>("/api/shifts", { preHandler: readGuard }, async (req) => {
|
||||
// reconcile across the site. The data is the signed shift_z_report chain. Both
|
||||
// scopes may filter by `till`.
|
||||
app.get<{ Querystring: ShiftsQuery }>("/api/shifts", { preHandler: readGuard }, async (req, reply) => {
|
||||
const canSeeAll = roleHasPermissions(req.user.roleId, ["shift:cash"]);
|
||||
const q = req.query ?? {};
|
||||
// Non-admins are hard-scoped to themselves regardless of any operator param.
|
||||
const operator = canSeeAll ? (q.operator?.trim() || undefined) : req.user.username;
|
||||
const from = canSeeAll ? q.from?.trim() || undefined : undefined;
|
||||
const to = canSeeAll ? q.to?.trim() || undefined : undefined;
|
||||
const shifts = shift.listShifts({ operator, from, to });
|
||||
let till: TillId | undefined;
|
||||
if (q.till?.trim()) {
|
||||
const parsed = parseTill(db, q.till.trim());
|
||||
if (!parsed) return badTill(reply);
|
||||
till = parsed;
|
||||
}
|
||||
const shifts = shift.listShifts({ operator, from, to, till });
|
||||
// Admins also get the distinct operator list (unfiltered) for the filter
|
||||
// dropdown — operators don't see other names, so it's scope-gated.
|
||||
if (canSeeAll) return { shifts, scope: "all", operators: shift.listOperators() };
|
||||
return { shifts, scope: "self" };
|
||||
if (canSeeAll) return { shifts, scope: "all", operators: shift.listOperators(), tills: effectiveTillsFor(db) };
|
||||
return { shifts, scope: "self", tills: effectiveTillsFor(db) };
|
||||
});
|
||||
|
||||
// NB: drawer cash movements (record/review) moved to routes/drawer.ts (2026-07-01) — the
|
||||
// feature is no longer part of the shift route. See wiki/concepts/shift.md.
|
||||
|
||||
app.post("/api/shift/open", { preHandler: guard }, async (req, reply) => {
|
||||
app.post<{ Body: TillBody }>("/api/shift/open", { preHandler: guard }, async (req, reply) => {
|
||||
const till = parseTill(db, req.body?.till);
|
||||
if (!till) return badTill(reply);
|
||||
if (!mayWork(req.user.roleId, till)) return forbidden(reply, till);
|
||||
try {
|
||||
return await shift.open(req.user.username);
|
||||
return await shift.open(req.user.username, till);
|
||||
} catch (err) {
|
||||
if (err instanceof ShiftAlreadyOpenError) return reply.code(409).send({ error: err.message });
|
||||
return reply.code(500).send({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/shift/close", { preHandler: guard }, async (req, reply) => {
|
||||
app.post<{ Body: TillBody }>("/api/shift/close", { preHandler: guard }, async (req, reply) => {
|
||||
const till = parseTill(db, req.body?.till);
|
||||
if (!till) return badTill(reply);
|
||||
if (!mayWork(req.user.roleId, till)) return forbidden(reply, till);
|
||||
try {
|
||||
return await shift.close(req.user.username);
|
||||
return await shift.close(req.user.username, till);
|
||||
} catch (err) {
|
||||
if (err instanceof NoOpenShiftError) return reply.code(409).send({ error: err.message });
|
||||
return reply.code(500).send({ error: (err as Error).message });
|
||||
|
||||
@@ -2,7 +2,7 @@ import { randomBytes, randomUUID } from "node:crypto";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { and, eq, isNull, devices, subscriptionCredentials, subscriptionPlans, subscriptionPlates, subscriptions, type Db } from "@parking/db";
|
||||
import { NoPrinterAvailableError } from "@parking/devices";
|
||||
import type { SubscriptionPlan, SubscriptionQuote, Tender } from "@parking/shared";
|
||||
import { BOOTH_TILL, type SubscriptionPlan, type SubscriptionQuote, type Tender } from "@parking/shared";
|
||||
import { requirePermission, roleHasPermissions } from "../auth.js";
|
||||
import { softDelete } from "../recycle-bin.js";
|
||||
import { invalidateHolder } from "../event-enrich.js";
|
||||
@@ -381,6 +381,7 @@ export async function subscriptionRoutes(
|
||||
amountMinor,
|
||||
currency,
|
||||
tender,
|
||||
till: BOOTH_TILL,
|
||||
operator,
|
||||
// Flags this `payment` as a subscription SALE (not a parking payment) so the
|
||||
// live feed / activity log can label it distinctly. plan + periods for audit
|
||||
|
||||
@@ -10,11 +10,11 @@ import {
|
||||
validationPrograms,
|
||||
type Db,
|
||||
} from "@parking/db";
|
||||
import { VALIDATION_MODES, type ValidationMode } from "@parking/shared";
|
||||
import { MERCHANT_VALIDATION_MODES, VALIDATION_MODES, type ValidationMode } from "@parking/shared";
|
||||
import { requirePermission } from "../auth.js";
|
||||
import { requireModule } from "../modules.js";
|
||||
import type { EventLog } from "../event-log.js";
|
||||
import { liveValidations, sessionValidations } from "../validations.js";
|
||||
import { applyValidation, liveValidations, sessionValidations } from "../validations.js";
|
||||
|
||||
// Merchant validations (bar / lavazh). The merchant is VALIDATION-ONLY: they scan the
|
||||
// customer's ticket on their own device and apply their program — all money and paper
|
||||
@@ -64,12 +64,18 @@ function validateProgram(b: ProgramBody): string | null {
|
||||
if (!b.name || !String(b.name).trim()) return "name is required";
|
||||
if (!VALIDATION_MODES.includes(b.mode as ValidationMode)) return "mode must be comp|timeCredit|fixed|percent";
|
||||
const intOrNull = (v: unknown) => v == null || (Number.isInteger(v) && (v as number) > 0);
|
||||
if (!intOrNull(b.minutes)) return "minutes must be a positive integer";
|
||||
// doneTolerance's minutes is a TOLERANCE — zero is a legitimate "free until done, not a
|
||||
// minute more"; every other minutes use is a positive credit.
|
||||
const minutesOk = b.mode === "doneTolerance"
|
||||
? b.minutes == null || (Number.isInteger(b.minutes) && (b.minutes as number) >= 0)
|
||||
: intOrNull(b.minutes);
|
||||
if (!minutesOk) return b.mode === "doneTolerance" ? "minutes must be a non-negative integer" : "minutes must be a positive integer";
|
||||
if (!intOrNull(b.maxAmountMinor)) return "maxAmountMinor must be a positive integer";
|
||||
if (!intOrNull(b.maxPerDay)) return "maxPerDay must be a positive integer";
|
||||
if (b.percent != null && (!Number.isInteger(b.percent) || b.percent < 1 || b.percent > 100))
|
||||
return "percent must be 1..100";
|
||||
if (b.mode === "timeCredit" && b.minutes == null) return "timeCredit needs minutes";
|
||||
if (b.mode === "doneTolerance" && b.minutes == null) return "doneTolerance needs minutes (the tolerance; 0 allowed)";
|
||||
if (b.mode === "percent" && b.percent == null) return "percent mode needs percent";
|
||||
if (b.mode === "fixed" && b.maxAmountMinor == null) return "fixed mode needs maxAmountMinor";
|
||||
return null;
|
||||
@@ -247,88 +253,21 @@ export async function validationRoutes(app: FastifyInstance, db: Db, eventLog: E
|
||||
if (!boundUserIds(programId).includes(req.user.sub)) {
|
||||
return reply.code(403).send({ error: "you are not bound to this program" });
|
||||
}
|
||||
|
||||
// Session state — an open transient (subscriptions are prepaid; nothing to discount).
|
||||
const rows = db
|
||||
.select({ type: ledgerEvents.type, payload: ledgerEvents.payload })
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.identity, identity))
|
||||
.orderBy(ledgerEvents.index)
|
||||
.all();
|
||||
const entry = rows.find((r) => r.type === "vehicle_entry");
|
||||
if (!entry) return reply.code(404).send({ error: "no session for ticket" });
|
||||
const entryPl = (entry.payload ?? {}) as { permit?: boolean; permitId?: string };
|
||||
if (entryPl.permit === true || entryPl.permitId != null) {
|
||||
return reply.code(409).send({ error: "subscription sessions cannot be validated" });
|
||||
}
|
||||
if (rows.some((r) => r.type === "vehicle_exit" || r.type === "void")) {
|
||||
return reply.code(409).send({ error: "session is closed" });
|
||||
}
|
||||
if (liveValidations(db, identity).some((v) => v.programId === programId)) {
|
||||
return reply.code(409).send({ error: "this program is already applied to the ticket" });
|
||||
if (!MERCHANT_VALIDATION_MODES.includes(program.mode)) {
|
||||
return reply.code(400).send({ error: "this program's discount is resolved by a car wash order, not at scan" });
|
||||
}
|
||||
|
||||
// Per-day cap: unvoided applications of this program since LOCAL midnight (the
|
||||
// appliance runs in site time).
|
||||
if (program.maxPerDay != null) {
|
||||
const midnight = new Date();
|
||||
midnight.setHours(0, 0, 0, 0);
|
||||
const todays = db
|
||||
.select({ id: ledgerEvents.id, occurredAt: ledgerEvents.occurredAt, payload: ledgerEvents.payload, type: ledgerEvents.type })
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.type, "validation"))
|
||||
.all()
|
||||
.filter((r) => Date.parse(r.occurredAt) >= midnight.getTime());
|
||||
const voidedIds = new Set(
|
||||
todays.map((r) => (r.payload as { refId?: string } | null)?.refId).filter(Boolean) as string[],
|
||||
);
|
||||
const count = todays.filter((r) => {
|
||||
const p = (r.payload ?? {}) as { programId?: string; refId?: string };
|
||||
return p.programId === programId && !p.refId && !voidedIds.has(r.id);
|
||||
}).length;
|
||||
if (count >= program.maxPerDay) {
|
||||
return reply.code(409).send({ error: "daily cap reached for this program" });
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the values off the program row (frozen into the signed event).
|
||||
let amountMinor: number | undefined;
|
||||
if (program.mode === "fixed") {
|
||||
const a = req.body?.amountMinor;
|
||||
if (a == null || !Number.isInteger(a) || a <= 0) {
|
||||
return reply.code(400).send({ error: "amountMinor (positive integer) required for this program" });
|
||||
}
|
||||
if (program.maxAmountMinor != null && a > program.maxAmountMinor) {
|
||||
return reply.code(400).send({ error: `amount exceeds the program cap (${program.maxAmountMinor})` });
|
||||
}
|
||||
amountMinor = a;
|
||||
}
|
||||
|
||||
const ev = await eventLog.append({
|
||||
type: "validation",
|
||||
source: "manual",
|
||||
identity,
|
||||
payload: {
|
||||
sessionRef: identity,
|
||||
programId,
|
||||
programLabel: program.name,
|
||||
mode: program.mode,
|
||||
...(program.mode === "timeCredit" && program.minutes != null ? { minutes: program.minutes } : {}),
|
||||
...(program.mode === "percent" && program.percent != null ? { percent: program.percent } : {}),
|
||||
...(amountMinor != null ? { amountMinor } : {}),
|
||||
operator: req.user.username,
|
||||
},
|
||||
});
|
||||
return reply.code(201).send({
|
||||
ok: true,
|
||||
eventId: ev.id,
|
||||
// The decision chain + the signed append live in ../validations.ts (applyValidation)
|
||||
// — shared with the Car Wash module, which applies its own sponsorship program with
|
||||
// no user binding. Only the binding check above is merchant-specific.
|
||||
const result = await applyValidation(db, eventLog, {
|
||||
programId,
|
||||
label: program.name,
|
||||
mode: program.mode,
|
||||
minutes: program.mode === "timeCredit" ? program.minutes : undefined,
|
||||
percent: program.mode === "percent" ? program.percent : undefined,
|
||||
amountMinor,
|
||||
identity,
|
||||
actor: req.user.username,
|
||||
amountMinor: req.body?.amountMinor,
|
||||
});
|
||||
if (!result.ok) return reply.code(result.status).send({ error: result.error });
|
||||
return reply.code(201).send(result);
|
||||
});
|
||||
|
||||
// VOID my own UNUSED validation (fat-fingered amount / wrong ticket). Append-only:
|
||||
|
||||
@@ -286,9 +286,9 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
||||
await subscriptionPlanRoutes(app, db);
|
||||
|
||||
// Shift open/close (shiftService constructed above).
|
||||
await shiftRoutes(app, shiftService);
|
||||
await shiftRoutes(app, db, shiftService);
|
||||
// Drawer cash movements — operator records, admin reviews (routes/drawer.ts).
|
||||
await drawerRoutes(app, shiftService);
|
||||
await drawerRoutes(app, db, shiftService);
|
||||
// Operator-issued entry (broken physical button) — flagged mint, presence-gated.
|
||||
await entryRoutes(app, entryFlow, laneStatus, shiftService);
|
||||
|
||||
@@ -301,7 +301,7 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
||||
// validations for the Bar; the booth settlement folds applied validations into its
|
||||
// quote, pay-station.ts). `parking` is in the registry too but its routes are still
|
||||
// the flat list above; they move behind the seam subsystem by subsystem.
|
||||
await registerModules(app, { db, eventLog });
|
||||
await registerModules(app, { db, eventLog, payStation, shiftService });
|
||||
|
||||
// Application logs: ingest frontend errors (POST /api/logs, any signed-in user) +
|
||||
// read the store (GET /api/logs, log:read). See wiki/concepts/app-logs.md.
|
||||
|
||||
@@ -242,3 +242,93 @@ describe("close signs a Z-report; listShifts reads it back", () => {
|
||||
expect(shift.listOperators()).toEqual(["alice", "bob"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tills: one shift per till, one drawer per till", () => {
|
||||
/** A bay payment as the Car Wash module signs it (till = carwash). */
|
||||
async function bayPayment(amountMinor: number, tender: "cash" | "card" = "cash") {
|
||||
await log.append({
|
||||
type: "carwash_payment", source: "manual", identity: "T",
|
||||
payload: { sessionRef: "T", orderId: "o1", amountMinor, currency: "ALL", tender, till: "carwash" },
|
||||
});
|
||||
}
|
||||
|
||||
it("the booth and the carwash till can both be open at once, by different operators", async () => {
|
||||
await shift.open("alice");
|
||||
await expect(shift.open("wanda", "carwash")).resolves.toMatchObject({ till: "carwash" });
|
||||
expect(shift.currentOpenShift()?.identity).toBe("alice");
|
||||
expect(shift.currentOpenShift("carwash")?.identity).toBe("wanda");
|
||||
// Each till keeps its own single-open rule.
|
||||
await expect(shift.open("bob", "carwash")).rejects.toBeInstanceOf(ShiftAlreadyOpenError);
|
||||
await expect(shift.open("bob")).rejects.toBeInstanceOf(ShiftAlreadyOpenError);
|
||||
});
|
||||
|
||||
it("requireOpenShift is per till: a booth shift does not cover the bay", async () => {
|
||||
await shift.open("alice");
|
||||
expect(() => shift.requireOpenShift("carwash")).toThrow(NoShiftOpenError);
|
||||
await shift.open("wanda", "carwash");
|
||||
expect(shift.requireOpenShift("carwash").identity).toBe("wanda");
|
||||
});
|
||||
|
||||
it("money folds into ITS till only: bay cash is the wash operator's, not the booth's", async () => {
|
||||
await shift.open("alice");
|
||||
await shift.open("wanda", "carwash");
|
||||
await payment(10000); // booth (payment events carry till=booth or nothing)
|
||||
await bayPayment(70000);
|
||||
await bayPayment(20000, "card");
|
||||
|
||||
const booth = shift.currentReport()!;
|
||||
expect(booth.till).toBe("booth");
|
||||
expect(booth.cashTotalMinor).toBe(10000);
|
||||
expect(booth.paymentCount).toBe(1);
|
||||
expect(booth.expectedDrawerMinor).toBe(10000);
|
||||
|
||||
const wash = shift.currentReport("carwash")!;
|
||||
expect(wash.till).toBe("carwash");
|
||||
expect(wash.cashTotalMinor).toBe(70000);
|
||||
expect(wash.cardTotalMinor).toBe(20000);
|
||||
expect(wash.paymentCount).toBe(2);
|
||||
expect(wash.expectedDrawerMinor).toBe(70000);
|
||||
|
||||
expect(shift.drawerBalance().balanceMinor).toBe(10000);
|
||||
expect(shift.drawerBalance("carwash").balanceMinor).toBe(70000);
|
||||
});
|
||||
|
||||
it("vouchers name their till; each till's expected drawer carries forward on its own", async () => {
|
||||
await shift.open("alice");
|
||||
await shift.open("wanda", "carwash");
|
||||
await shift.recordVoucher({ type: "cash_in", operator: "wanda", amountMinor: 5000, reason: "float", till: "carwash" });
|
||||
await shift.recordVoucher({ type: "cash_in", operator: "alice", amountMinor: 100000, reason: "float" });
|
||||
await bayPayment(70000);
|
||||
expect(shift.movementsWithStatus({ till: "carwash" }).map((m) => m.amountMinor)).toEqual([5000]);
|
||||
|
||||
const washZ = await shift.close("wanda", "carwash");
|
||||
expect(washZ).toMatchObject({ till: "carwash", cashAddedMinor: 5000, cashTotalMinor: 70000, expectedDrawerMinor: 75000 });
|
||||
const boothZ = await shift.close("alice");
|
||||
expect(boothZ).toMatchObject({ till: "booth", cashAddedMinor: 100000, cashTotalMinor: 0, expectedDrawerMinor: 100000 });
|
||||
|
||||
// Next shift on each till inherits that till's drawer only.
|
||||
expect((await shift.open("wanda", "carwash")).openingFloatMinor).toBe(75000);
|
||||
expect((await shift.open("bob")).openingFloatMinor).toBe(100000);
|
||||
});
|
||||
|
||||
it("close is per till: closing the booth never closes the wash desk", async () => {
|
||||
await shift.open("alice");
|
||||
await shift.open("alice", "carwash");
|
||||
await shift.close("alice");
|
||||
expect(shift.currentOpenShift()).toBeNull();
|
||||
expect(shift.currentOpenShift("carwash")?.identity).toBe("alice");
|
||||
await expect(shift.close("alice")).rejects.toBeInstanceOf(NoOpenShiftError);
|
||||
});
|
||||
|
||||
it("history lists both tills, filterable; pre-till reports read as booth", async () => {
|
||||
await shift.open("alice");
|
||||
await shift.open("wanda", "carwash");
|
||||
await shift.close("wanda", "carwash");
|
||||
await shift.close("alice");
|
||||
const all = shift.listShifts();
|
||||
expect(all.map((s) => s.till).sort()).toEqual(["booth", "carwash"]);
|
||||
expect(shift.listShifts({ till: "carwash" }).map((s) => s.operator)).toEqual(["wanda"]);
|
||||
expect(shift.listShifts({ till: "booth" }).map((s) => s.operator)).toEqual(["alice"]);
|
||||
expect(shift.listOperators("carwash")).toEqual(["wanda"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { eq, devices, ledgerEvents, type Db } from "@parking/db";
|
||||
import { eq, devices, ledgerEvents, type Db, inArray } from "@parking/db";
|
||||
import { registry, formatStampSq as zStamp, type PrinterDevice } from "@parking/devices";
|
||||
import type { LedgerPayload } from "@parking/shared";
|
||||
import { BOOTH_TILL, tillOf, type LedgerPayload, type TillId } from "@parking/shared";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import type { EventLog } from "./event-log.js";
|
||||
|
||||
@@ -8,33 +8,46 @@ import type { EventLog } from "./event-log.js";
|
||||
// delimited by EXPLICIT marks — not a clock. Represented entirely as signed ledger
|
||||
// events (no mutable table): `shift_open` … `shift_z_report`. At close, sum the
|
||||
// `payment` events taken during the shift by tender and print a Z-report.
|
||||
//
|
||||
// TILLS (2026-09-05): a shift is opened ON A TILL — the booth, or a money-taking
|
||||
// module's own desk (Car Wash → "carwash"). One shift may be open PER TILL, each with
|
||||
// its own operator, opening float, expected drawer and Z-report. Every money event
|
||||
// names its till (`payload.till`; absent = booth, which is what every pre-till event
|
||||
// is), and every fold in this file filters by it. Every public method takes the till,
|
||||
// defaulting to the booth so the parking paths read as they always did.
|
||||
// See wiki/concepts/shift.md.
|
||||
|
||||
export class ShiftAlreadyOpenError extends Error {
|
||||
/** The operator who currently holds the open shift (may be someone else). */
|
||||
readonly heldBy: string;
|
||||
constructor(operator: string, heldBy: string) {
|
||||
constructor(operator: string, heldBy: string, till: TillId = BOOTH_TILL) {
|
||||
super(
|
||||
heldBy === operator
|
||||
? `operator ${operator} already has an open shift`
|
||||
: `another operator (${heldBy}) has an open shift; only one shift may be open at a time`,
|
||||
? `operator ${operator} already has an open ${till} shift`
|
||||
: `another operator (${heldBy}) has an open ${till} shift; only one shift may be open per till`,
|
||||
);
|
||||
this.name = "ShiftAlreadyOpenError";
|
||||
this.heldBy = heldBy;
|
||||
}
|
||||
}
|
||||
export class NoOpenShiftError extends Error {
|
||||
constructor(operator: string) {
|
||||
super(`operator ${operator} has no open shift`);
|
||||
constructor(operator: string, till: TillId = BOOTH_TILL) {
|
||||
super(`operator ${operator} has no open ${till} shift`);
|
||||
this.name = "NoOpenShiftError";
|
||||
}
|
||||
}
|
||||
/** Thrown by the booth money path when NO shift is open site-wide — an operator
|
||||
* must open a shift before any payment/exit can be attributed to a shift. */
|
||||
/** Thrown by a money path when NO shift is open on its till — an operator must open
|
||||
* a shift there before any payment/exit can be attributed to one. */
|
||||
export class NoShiftOpenError extends Error {
|
||||
constructor() {
|
||||
super("no shift is open — open a shift before processing tickets");
|
||||
readonly till: TillId;
|
||||
constructor(till: TillId = BOOTH_TILL) {
|
||||
super(
|
||||
till === BOOTH_TILL
|
||||
? "no shift is open — open a shift before processing tickets"
|
||||
: `no ${till} shift is open — open one before taking money there`,
|
||||
);
|
||||
this.name = "NoShiftOpenError";
|
||||
this.till = till;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +57,8 @@ export class NoShiftOpenError extends Error {
|
||||
export interface ShiftSummary {
|
||||
readonly id: string;
|
||||
readonly index: number;
|
||||
/** The till this shift reconciled (booth for every pre-till report). */
|
||||
readonly till: TillId;
|
||||
readonly operator: string;
|
||||
readonly startedAt: string;
|
||||
readonly endedAt: string;
|
||||
@@ -63,6 +78,7 @@ export interface ShiftSummary {
|
||||
}
|
||||
|
||||
export interface ShiftReport {
|
||||
readonly till: TillId;
|
||||
readonly operator: string;
|
||||
readonly startedAt: string;
|
||||
readonly endedAt: string;
|
||||
@@ -102,6 +118,8 @@ export type MovementStatus = "pending" | "authorized" | "denied";
|
||||
export interface DrawerMovement {
|
||||
readonly id: string;
|
||||
readonly type: "cash_in" | "cash_out";
|
||||
/** Which drawer the cash moved in/out of. */
|
||||
readonly till: TillId;
|
||||
/** Positive magnitude; direction is the `type`. */
|
||||
readonly amountMinor: number;
|
||||
readonly currency: string | null;
|
||||
@@ -122,6 +140,9 @@ export class InvalidCashMovementError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** Printed (Albanian) name of a till on Z-reports and voucher slips. */
|
||||
const TILL_PRINT_LABEL: Record<TillId, string> = { booth: "Kabina", carwash: "Lavazhi" };
|
||||
|
||||
export class ShiftService {
|
||||
readonly #db: Db;
|
||||
readonly #log: EventLog;
|
||||
@@ -133,41 +154,42 @@ export class ShiftService {
|
||||
this.#logger = logger;
|
||||
}
|
||||
|
||||
/** Current physical drawer balance (cash payments + cash_movements, by time). For
|
||||
* the UI to show "inherited / in the drawer now". */
|
||||
drawerBalance(): { balanceMinor: number; currency: string | null } {
|
||||
return this.#drawerBalanceAt(new Date().toISOString());
|
||||
/** Current physical drawer balance of a till (cash payments + cash_movements, by
|
||||
* time). For the UI to show "inherited / in the drawer now". */
|
||||
drawerBalance(till: TillId = BOOTH_TILL): { balanceMinor: number; currency: string | null } {
|
||||
return this.#drawerBalanceAt(new Date().toISOString(), till);
|
||||
}
|
||||
|
||||
/** Is there an open shift for this operator? Returns the open `shift_open` row or null. */
|
||||
openShiftFor(operator: string) {
|
||||
// Scan shift events for this operator; the shift is open if the most recent
|
||||
// shift event for them is a `shift_open` (not yet closed by a z_report).
|
||||
const rows = this.#db
|
||||
/** The shift-boundary events (shift_open / shift_z_report) of ONE till, chain order. */
|
||||
#shiftEvents(till: TillId) {
|
||||
return this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.identity, operator))
|
||||
.where(inArray(ledgerEvents.type, ["shift_open", "shift_z_report"]))
|
||||
.orderBy(ledgerEvents.index)
|
||||
.all()
|
||||
.filter((r) => r.type === "shift_open" || r.type === "shift_z_report");
|
||||
.filter((r) => tillOf(r.payload as LedgerPayload | null) === till);
|
||||
}
|
||||
|
||||
/** Is there an open shift for this operator on this till? Returns the open
|
||||
* `shift_open` row or null. */
|
||||
openShiftFor(operator: string, till: TillId = BOOTH_TILL) {
|
||||
// The shift is open if the operator's most recent shift event on the till is a
|
||||
// `shift_open` (not yet closed by a z_report).
|
||||
const rows = this.#shiftEvents(till).filter((r) => r.identity === operator);
|
||||
const last = rows[rows.length - 1];
|
||||
return last && last.type === "shift_open" ? last : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The SINGLE site-wide open shift, or null. A shift is a site-wide accountability
|
||||
* period: at most ONE may be open at a time (so booth takings are unambiguously
|
||||
* attributed to one operator). It's open iff the most recent shift event on the
|
||||
* whole chain is a `shift_open` (the matching `shift_z_report` hasn't been
|
||||
* appended yet). Returns that row so callers can read its operator/startedAt.
|
||||
* The SINGLE open shift of a till, or null. A shift is the till's accountability
|
||||
* period: at most ONE may be open per till at a time (so its takings are
|
||||
* unambiguously attributed to one operator). It's open iff the till's most recent
|
||||
* shift event is a `shift_open` (the matching `shift_z_report` hasn't been appended
|
||||
* yet). Returns that row so callers can read its operator/startedAt.
|
||||
*/
|
||||
currentOpenShift() {
|
||||
const rows = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.orderBy(ledgerEvents.index)
|
||||
.all()
|
||||
.filter((r) => r.type === "shift_open" || r.type === "shift_z_report");
|
||||
currentOpenShift(till: TillId = BOOTH_TILL) {
|
||||
const rows = this.#shiftEvents(till);
|
||||
const last = rows[rows.length - 1];
|
||||
return last && last.type === "shift_open" ? last : null;
|
||||
}
|
||||
@@ -186,24 +208,25 @@ export class ShiftService {
|
||||
* distinct + sorted — feeds the admin filter dropdown so it can only ever ask
|
||||
* for an operator that exists (the filter is an exact username match).
|
||||
*/
|
||||
listOperators(): string[] {
|
||||
listOperators(till?: TillId): string[] {
|
||||
const rows = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.type, "shift_z_report"))
|
||||
.all();
|
||||
.where(inArray(ledgerEvents.type, ["shift_z_report", "shift_open"]))
|
||||
.all()
|
||||
.filter((r) => till == null || tillOf(r.payload as LedgerPayload | null) === till);
|
||||
// Every operator with a closed report, plus the holder of each open shift (an
|
||||
// open shift is the last shift_open on its till — but any shift_open's operator
|
||||
// has or had a shift, which is all the dropdown needs).
|
||||
const names = new Set<string>();
|
||||
for (const r of rows) {
|
||||
const op = ((r.payload ?? {}) as { operator?: string }).operator ?? r.identity;
|
||||
if (op) names.add(op);
|
||||
}
|
||||
const open = this.currentOpenShift();
|
||||
const openOp = open ? (((open.payload ?? {}) as { operator?: string }).operator ?? open.identity) : null;
|
||||
if (openOp) names.add(openOp);
|
||||
return [...names].sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
listShifts(opts: { operator?: string; from?: string; to?: string } = {}): ShiftSummary[] {
|
||||
listShifts(opts: { operator?: string; from?: string; to?: string; till?: TillId } = {}): ShiftSummary[] {
|
||||
const rows = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
@@ -232,12 +255,15 @@ export class ShiftService {
|
||||
};
|
||||
const operator = pl.operator ?? r.identity ?? "?";
|
||||
const startedAt = pl.startedAt ?? r.occurredAt;
|
||||
const till = tillOf(pl);
|
||||
if (opts.till && till !== opts.till) continue;
|
||||
if (opts.operator && operator !== opts.operator) continue;
|
||||
if (opts.from && startedAt < opts.from) continue;
|
||||
if (opts.to && startedAt > opts.to) continue;
|
||||
out.push({
|
||||
id: r.id,
|
||||
index: r.index,
|
||||
till,
|
||||
operator,
|
||||
startedAt,
|
||||
endedAt: pl.endedAt ?? r.occurredAt,
|
||||
@@ -267,10 +293,10 @@ export class ShiftService {
|
||||
return out.reverse();
|
||||
}
|
||||
|
||||
/** Require an open shift for the booth money path; returns it or throws. */
|
||||
requireOpenShift() {
|
||||
const open = this.currentOpenShift();
|
||||
if (!open) throw new NoShiftOpenError();
|
||||
/** Require an open shift on a till for its money path; returns it or throws. */
|
||||
requireOpenShift(till: TillId = BOOTH_TILL) {
|
||||
const open = this.currentOpenShift(till);
|
||||
if (!open) throw new NoShiftOpenError(till);
|
||||
return open;
|
||||
}
|
||||
|
||||
@@ -283,9 +309,10 @@ export class ShiftService {
|
||||
* - `cash_out` (Mandat Pagese): − amountMinor (positive magnitude)
|
||||
* - `cash_movement` (legacy, pre-2026-06-20): a SIGNED amountMinor (+ load / −
|
||||
* removal) — historical chain events that still fold in unchanged.
|
||||
* This is what carries across shifts.
|
||||
* This is what carries across shifts. ONE till: every money event is filtered by
|
||||
* `tillOf(payload)` (absent = booth).
|
||||
*/
|
||||
#drawerBalanceAt(at: string): { balanceMinor: number; currency: string | null } {
|
||||
#drawerBalanceAt(at: string, till: TillId): { balanceMinor: number; currency: string | null } {
|
||||
const rows = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
@@ -295,16 +322,20 @@ export class ShiftService {
|
||||
(r) =>
|
||||
r.occurredAt <= at &&
|
||||
(r.type === "payment" ||
|
||||
// Car Wash module: money taken at the bay (cash adds to the drawer, card
|
||||
// never does — same tender rule as a parking payment).
|
||||
r.type === "carwash_payment" ||
|
||||
r.type === "cash_in" ||
|
||||
r.type === "cash_out" ||
|
||||
r.type === "cash_movement"),
|
||||
r.type === "cash_movement") &&
|
||||
tillOf(r.payload as LedgerPayload | null) === till,
|
||||
);
|
||||
let balanceMinor = 0;
|
||||
let currency: string | null = null;
|
||||
for (const r of rows) {
|
||||
const pl = (r.payload ?? {}) as LedgerPayload;
|
||||
const amt = typeof pl.amountMinor === "number" ? pl.amountMinor : 0;
|
||||
if (r.type === "payment") {
|
||||
if (r.type === "payment" || r.type === "carwash_payment") {
|
||||
// Only CASH enters the till; card settles to the bank.
|
||||
if (pl.tender !== "card") balanceMinor += amt;
|
||||
} else if (r.type === "cash_in") {
|
||||
@@ -347,8 +378,11 @@ export class ShiftService {
|
||||
amountMinor: number;
|
||||
reason: string;
|
||||
currency?: string;
|
||||
}): Promise<{ type: "cash_in" | "cash_out"; amountMinor: number; voucherNo: string; balanceMinor: number; printed: boolean }> {
|
||||
/** Which drawer the cash moved in/out of (default: the booth). */
|
||||
till?: TillId;
|
||||
}): Promise<{ type: "cash_in" | "cash_out"; till: TillId; amountMinor: number; voucherNo: string; balanceMinor: number; printed: boolean }> {
|
||||
const { type, operator, reason } = args;
|
||||
const till = args.till ?? BOOTH_TILL;
|
||||
if (!Number.isInteger(args.amountMinor) || args.amountMinor <= 0) {
|
||||
throw new InvalidCashMovementError("amountMinor must be a positive integer (minor units)");
|
||||
}
|
||||
@@ -365,15 +399,16 @@ export class ShiftService {
|
||||
...(args.currency ? { currency: args.currency } : {}),
|
||||
operator,
|
||||
voucherNo,
|
||||
till,
|
||||
},
|
||||
occurredAt: now,
|
||||
});
|
||||
const { balanceMinor, currency } = this.#drawerBalanceAt(now);
|
||||
const printed = await this.#printVoucher({ type, voucherNo, amountMinor, reason, operator, currency, at: now });
|
||||
const { balanceMinor, currency } = this.#drawerBalanceAt(now, till);
|
||||
const printed = await this.#printVoucher({ type, voucherNo, amountMinor, reason, operator, currency, at: now, till });
|
||||
this.#logger.info(
|
||||
`${type} ${voucherNo} ${amountMinor} by ${operator} (${reason || "no reason"}) → drawer ${balanceMinor}`,
|
||||
`${type} ${voucherNo} ${amountMinor} by ${operator} on ${till} (${reason || "no reason"}) → drawer ${balanceMinor}`,
|
||||
);
|
||||
return { type, amountMinor, voucherNo, balanceMinor, printed };
|
||||
return { type, till, amountMinor, voucherNo, balanceMinor, printed };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -431,7 +466,7 @@ export class ShiftService {
|
||||
* review queue. `operator` (optional) scopes to one operator's movements (an operator
|
||||
* sees only their own; a reviewer sees all). See wiki/concepts/shift.md.
|
||||
*/
|
||||
movementsWithStatus(filter?: { operator?: string; status?: MovementStatus }): DrawerMovement[] {
|
||||
movementsWithStatus(filter?: { operator?: string; status?: MovementStatus; till?: TillId }): DrawerMovement[] {
|
||||
const rows = this.#db.select().from(ledgerEvents).orderBy(ledgerEvents.index).all();
|
||||
// Latest review decision per movement id.
|
||||
const reviewByRef = new Map<string, { decision: "authorize" | "deny"; reviewedBy: string; note?: string; at: string }>();
|
||||
@@ -452,12 +487,15 @@ export class ShiftService {
|
||||
const pl = (r.payload ?? {}) as LedgerPayload;
|
||||
const operator = (typeof pl.operator === "string" ? pl.operator : null) ?? r.identity ?? "";
|
||||
if (filter?.operator && operator !== filter.operator) continue;
|
||||
const till = tillOf(pl);
|
||||
if (filter?.till && till !== filter.till) continue;
|
||||
const review = reviewByRef.get(r.id);
|
||||
const status: MovementStatus = review ? (review.decision === "authorize" ? "authorized" : "denied") : "pending";
|
||||
if (filter?.status && status !== filter.status) continue;
|
||||
out.push({
|
||||
id: r.id,
|
||||
type: r.type,
|
||||
till,
|
||||
amountMinor: typeof pl.amountMinor === "number" ? Math.abs(pl.amountMinor) : 0,
|
||||
currency: pl.currency ?? null,
|
||||
reason: pl.reason ?? null,
|
||||
@@ -474,27 +512,28 @@ export class ShiftService {
|
||||
return out.sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : 0));
|
||||
}
|
||||
|
||||
/** Open a shift for the operator (explicit start). The opening float is auto-
|
||||
* inherited from the chain = the drawer balance at the start instant. */
|
||||
async open(operator: string): Promise<{ startedAt: string; openingFloatMinor: number }> {
|
||||
// Site-wide single-open invariant: refuse if ANY shift is open — whether this
|
||||
// operator's own (double-open) or another operator's (handover not done). Only
|
||||
// one accountability period at a time.
|
||||
const current = this.currentOpenShift();
|
||||
if (current) throw new ShiftAlreadyOpenError(operator, current.identity ?? operator);
|
||||
/** Open a shift for the operator on a till (explicit start). The opening float is
|
||||
* auto-inherited from the chain = that till's drawer balance at the start instant. */
|
||||
async open(operator: string, till: TillId = BOOTH_TILL): Promise<{ startedAt: string; till: TillId; openingFloatMinor: number }> {
|
||||
// Single-open-per-till invariant: refuse if a shift is open ON THIS TILL — whether
|
||||
// this operator's own (double-open) or another operator's (handover not done).
|
||||
// One accountability period per drawer at a time. (Another till's shift is
|
||||
// independent: the booth and the wash desk run side by side.)
|
||||
const current = this.currentOpenShift(till);
|
||||
if (current) throw new ShiftAlreadyOpenError(operator, current.identity ?? operator, till);
|
||||
const startedAt = new Date().toISOString();
|
||||
const { balanceMinor: openingFloatMinor } = this.#drawerBalanceAt(startedAt);
|
||||
const { balanceMinor: openingFloatMinor } = this.#drawerBalanceAt(startedAt, till);
|
||||
await this.#log.append({
|
||||
type: "shift_open",
|
||||
source: "manual",
|
||||
identity: operator, // the shift's operator; `identity` keys the shift to them
|
||||
// Record the inherited opening float on the shift_open so it's reproducible
|
||||
// and the next operator's handover figure is fixed in the chain.
|
||||
payload: { operator, openingFloatMinor },
|
||||
payload: { operator, openingFloatMinor, till },
|
||||
occurredAt: startedAt,
|
||||
});
|
||||
this.#logger.info(`shift opened for ${operator} (opening float ${openingFloatMinor})`);
|
||||
return { startedAt, openingFloatMinor };
|
||||
this.#logger.info(`${till} shift opened for ${operator} (opening float ${openingFloatMinor})`);
|
||||
return { startedAt, till, openingFloatMinor };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -510,15 +549,22 @@ export class ShiftService {
|
||||
): Omit<ShiftReport, "printed"> {
|
||||
const operator = open.identity ?? "?";
|
||||
const startedAt = open.occurredAt;
|
||||
const till = tillOf(open.payload as LedgerPayload | null);
|
||||
|
||||
// All payments taken in [startedAt, asOf], summed by tender. Payment time =
|
||||
// the operator who handled the money (decision: sum by payment time).
|
||||
// All payments taken ON THIS TILL in [startedAt, asOf], summed by tender. Payment
|
||||
// time = the operator who handled the money (decision: sum by payment time).
|
||||
const payments = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.type, "payment"))
|
||||
// Parking payments + Car Wash bay payments (a wash paid at the BOOTH is inside the
|
||||
// parking payment's amount already, as chargeLines). Both fold into the cash/card
|
||||
// tender totals so the expected drawer is right; a separate wash bucket on the
|
||||
// Z-report is a follow-up (venue-modules.md).
|
||||
.where(inArray(ledgerEvents.type, ["payment", "carwash_payment"]))
|
||||
.all()
|
||||
.filter((r) => r.occurredAt >= startedAt && r.occurredAt <= asOf);
|
||||
.filter(
|
||||
(r) => r.occurredAt >= startedAt && r.occurredAt <= asOf && tillOf(r.payload as LedgerPayload | null) === till,
|
||||
);
|
||||
|
||||
let cashTotalMinor = 0;
|
||||
let cardTotalMinor = 0;
|
||||
@@ -557,7 +603,7 @@ export class ShiftService {
|
||||
const openingFloatMinor =
|
||||
typeof openPl.openingFloatMinor === "number"
|
||||
? openPl.openingFloatMinor
|
||||
: this.#drawerBalanceAt(startedAt).balanceMinor;
|
||||
: this.#drawerBalanceAt(startedAt, till).balanceMinor;
|
||||
|
||||
// Drawer movements within the window, split into added (+) and removed (−).
|
||||
// Three side-by-side types: cash_in (+), cash_out (−), and the legacy signed-±
|
||||
@@ -570,7 +616,8 @@ export class ShiftService {
|
||||
(r) =>
|
||||
(r.type === "cash_in" || r.type === "cash_out" || r.type === "cash_movement") &&
|
||||
r.occurredAt >= startedAt &&
|
||||
r.occurredAt <= asOf,
|
||||
r.occurredAt <= asOf &&
|
||||
tillOf(r.payload as LedgerPayload | null) === till,
|
||||
);
|
||||
let cashAddedMinor = 0;
|
||||
let cashRemovedMinor = 0;
|
||||
@@ -589,6 +636,7 @@ export class ShiftService {
|
||||
const expectedDrawerMinor = openingFloatMinor + cashTotalMinor + cashAddedMinor - cashRemovedMinor;
|
||||
|
||||
return {
|
||||
till,
|
||||
operator,
|
||||
startedAt,
|
||||
endedAt: asOf,
|
||||
@@ -615,17 +663,18 @@ export class ShiftService {
|
||||
* projection the Z-report prints, so the operator sees exactly what their close
|
||||
* will show. See wiki/concepts/shift.md.
|
||||
*/
|
||||
currentReport(): (Omit<ShiftReport, "printed"> & { asOf: string }) | null {
|
||||
const open = this.currentOpenShift();
|
||||
currentReport(till: TillId = BOOTH_TILL): (Omit<ShiftReport, "printed"> & { asOf: string }) | null {
|
||||
const open = this.currentOpenShift(till);
|
||||
if (!open) return null;
|
||||
const asOf = new Date().toISOString();
|
||||
return { ...this.#summariseWindow(open, asOf), asOf };
|
||||
}
|
||||
|
||||
/** Close the operator's open shift: sum payments in the window, sign + print the Z-report. */
|
||||
async close(operator: string): Promise<ShiftReport> {
|
||||
const open = this.openShiftFor(operator);
|
||||
if (!open) throw new NoOpenShiftError(operator);
|
||||
/** Close the operator's open shift on a till: sum its payments in the window, sign +
|
||||
* print the Z-report. */
|
||||
async close(operator: string, till: TillId = BOOTH_TILL): Promise<ShiftReport> {
|
||||
const open = this.openShiftFor(operator, till);
|
||||
if (!open) throw new NoOpenShiftError(operator, till);
|
||||
const endedAt = new Date().toISOString();
|
||||
|
||||
const report = this.#summariseWindow(open, endedAt);
|
||||
@@ -652,6 +701,7 @@ export class ShiftService {
|
||||
identity: operator,
|
||||
payload: {
|
||||
operator,
|
||||
till,
|
||||
startedAt,
|
||||
endedAt,
|
||||
cashTotalMinor,
|
||||
@@ -673,7 +723,7 @@ export class ShiftService {
|
||||
const printed = await this.#printZReport(report);
|
||||
|
||||
this.#logger.info(
|
||||
`shift closed for ${operator}: cash ${cashTotalMinor} card ${cardTotalMinor} (${paymentCount} payments); ` +
|
||||
`${till} shift closed for ${operator}: cash ${cashTotalMinor} card ${cardTotalMinor} (${paymentCount} payments); ` +
|
||||
`drawer open ${openingFloatMinor} +${cashAddedMinor} −${cashRemovedMinor} → expected ${expectedDrawerMinor}`,
|
||||
);
|
||||
return { ...report, printed };
|
||||
@@ -692,6 +742,9 @@ export class ShiftService {
|
||||
// Customer/operator-facing print is Albanian (see i18n.md — printed slips are not
|
||||
// governed by the UI language), with human dates "19 Qershor 2026 10:48:25".
|
||||
const lines = [
|
||||
// Which drawer this report reconciles — only printed off the booth, so booth
|
||||
// slips stay byte-identical to before tills existed.
|
||||
...(r.till !== BOOTH_TILL ? [`Arka: ${TILL_PRINT_LABEL[r.till]}`] : []),
|
||||
`Operatori: ${r.operator}`,
|
||||
`Nga: ${zStamp(r.startedAt)}`,
|
||||
`Deri: ${zStamp(r.endedAt)}`,
|
||||
@@ -737,6 +790,7 @@ export class ShiftService {
|
||||
operator: string;
|
||||
currency: string | null;
|
||||
at: string;
|
||||
till: TillId;
|
||||
}): Promise<boolean> {
|
||||
const printer = await this.#boothPrinter();
|
||||
if (!printer) {
|
||||
@@ -748,6 +802,7 @@ export class ShiftService {
|
||||
const title = v.type === "cash_in" ? "MANDAT ARKËTIMI" : "MANDAT PAGESE";
|
||||
const lines = [
|
||||
`Mandat Nr.: ${v.voucherNo}`,
|
||||
...(v.till !== BOOTH_TILL ? [`Arka: ${TILL_PRINT_LABEL[v.till]}`] : []),
|
||||
`Data: ${zStamp(v.at)}`,
|
||||
"",
|
||||
`Shuma: ${money(v.amountMinor)} ${cur}`,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { eq, ledgerEvents, type Db } from "@parking/db";
|
||||
import { eq, ledgerEvents, type Db, and, isNull, validationPrograms } from "@parking/db";
|
||||
import type { EventLog } from "./event-log.js";
|
||||
import type { SessionValidation, ValidationMode } from "@parking/shared";
|
||||
|
||||
// Merchant-validation ledger folds. A validation is a SIGNED, appended event on the
|
||||
@@ -86,3 +87,170 @@ export function sessionValidations(db: Db, identity: string): AppliedValidation[
|
||||
export function liveValidations(db: Db, identity: string): AppliedValidation[] {
|
||||
return sessionValidations(db, identity).filter((v) => !v.voided && v.consumedBy == null);
|
||||
}
|
||||
|
||||
// --- Apply (shared by the merchant route and the Car Wash module) ----------------
|
||||
|
||||
export interface ApplyValidationInput {
|
||||
programId: string;
|
||||
identity: string;
|
||||
/** Username recorded as the applying operator. */
|
||||
actor: string;
|
||||
/** fixed mode only: the amount the operator grants (minor units, ≤ maxAmountMinor). */
|
||||
amountMinor?: number;
|
||||
/** Car Wash context — required by the wash-only modes (doneTolerance / washPrice), which
|
||||
* are RESOLVED here into a plain timeCredit / fixed event the pricing fold already
|
||||
* understands: `washMinutes` = the wash window (order intake → done), NOT the whole
|
||||
* stay; `priceMinor` = the wash price. */
|
||||
wash?: { washMinutes: number; priceMinor: number };
|
||||
}
|
||||
|
||||
export type ApplyValidationResult =
|
||||
| {
|
||||
ok: true;
|
||||
eventId: string;
|
||||
programId: string;
|
||||
label: string;
|
||||
mode: string;
|
||||
minutes?: number | null;
|
||||
percent?: number | null;
|
||||
amountMinor?: number;
|
||||
}
|
||||
| { ok: false; status: 400 | 404 | 409; error: string };
|
||||
|
||||
/**
|
||||
* Apply a validation program to an open transient session and append the signed
|
||||
* `validation` event with the RESOLVED values. The decision chain, in order: program
|
||||
* live + active → open TRANSIENT session → not already carrying a live application of
|
||||
* this program → per-day cap → fixed-amount bounds. The merchant route adds its own
|
||||
* program↔user BINDING check before calling this; a module applying its own program
|
||||
* (Car Wash sponsorship) has no binding — the actor is attributed on the event instead.
|
||||
* Returns a result object rather than throwing so each caller maps to its own HTTP
|
||||
* shape. See wiki/concepts/validation-discounts.md.
|
||||
*/
|
||||
export async function applyValidation(
|
||||
db: Db,
|
||||
eventLog: EventLog,
|
||||
input: ApplyValidationInput,
|
||||
): Promise<ApplyValidationResult> {
|
||||
const { programId, identity, actor } = input;
|
||||
const program = db
|
||||
.select()
|
||||
.from(validationPrograms)
|
||||
.where(and(eq(validationPrograms.id, programId), isNull(validationPrograms.deletedAt)))
|
||||
.get();
|
||||
if (!program || !program.active) return { ok: false, status: 404, error: "program not found or inactive" };
|
||||
|
||||
const rows = db
|
||||
.select({ type: ledgerEvents.type, payload: ledgerEvents.payload })
|
||||
.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, status: 404, error: "no session for ticket" };
|
||||
const entryPl = (entry.payload ?? {}) as { permit?: boolean; permitId?: string };
|
||||
if (entryPl.permit === true || entryPl.permitId != null) {
|
||||
return { ok: false, status: 409, error: "subscription sessions cannot be validated" };
|
||||
}
|
||||
if (rows.some((r) => r.type === "vehicle_exit" || r.type === "void")) {
|
||||
return { ok: false, status: 409, error: "session is closed" };
|
||||
}
|
||||
if (liveValidations(db, identity).some((v) => v.programId === programId)) {
|
||||
return { ok: false, status: 409, error: "this program is already applied to the ticket" };
|
||||
}
|
||||
|
||||
// Per-day cap: unvoided applications of this program since LOCAL midnight (the
|
||||
// appliance runs in site time).
|
||||
if (program.maxPerDay != null) {
|
||||
const midnight = new Date();
|
||||
midnight.setHours(0, 0, 0, 0);
|
||||
const todays = db
|
||||
.select({ id: ledgerEvents.id, occurredAt: ledgerEvents.occurredAt, payload: ledgerEvents.payload, type: ledgerEvents.type })
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.type, "validation"))
|
||||
.all()
|
||||
.filter((r) => Date.parse(r.occurredAt) >= midnight.getTime());
|
||||
const voidedIds = new Set(
|
||||
todays.map((r) => (r.payload as { refId?: string } | null)?.refId).filter(Boolean) as string[],
|
||||
);
|
||||
const count = todays.filter((r) => {
|
||||
const p = (r.payload ?? {}) as { programId?: string; refId?: string };
|
||||
return p.programId === programId && !p.refId && !voidedIds.has(r.id);
|
||||
}).length;
|
||||
if (count >= program.maxPerDay) return { ok: false, status: 409, error: "daily cap reached for this program" };
|
||||
}
|
||||
|
||||
// Resolve the program into the event's (mode, minutes/percent/amount). The wash-only
|
||||
// modes become the plain modes the pricing fold knows; `programMode` keeps the original
|
||||
// on the signed event for audit.
|
||||
let mode: "comp" | "timeCredit" | "fixed" | "percent";
|
||||
let minutes: number | undefined;
|
||||
let percent: number | undefined;
|
||||
let amountMinor: number | undefined;
|
||||
switch (program.mode) {
|
||||
case "comp":
|
||||
mode = "comp";
|
||||
break;
|
||||
case "timeCredit":
|
||||
mode = "timeCredit";
|
||||
minutes = program.minutes ?? undefined;
|
||||
break;
|
||||
case "percent":
|
||||
mode = "percent";
|
||||
percent = program.percent ?? undefined;
|
||||
break;
|
||||
case "fixed": {
|
||||
const a = input.amountMinor;
|
||||
if (a == null || !Number.isInteger(a) || a <= 0) {
|
||||
return { ok: false, status: 400, error: "amountMinor (positive integer) required for this program" };
|
||||
}
|
||||
if (program.maxAmountMinor != null && a > program.maxAmountMinor) {
|
||||
return { ok: false, status: 400, error: `amount exceeds the program cap (${program.maxAmountMinor})` };
|
||||
}
|
||||
mode = "fixed";
|
||||
amountMinor = a;
|
||||
break;
|
||||
}
|
||||
case "doneTolerance": {
|
||||
if (!input.wash) return { ok: false, status: 400, error: "this program needs a car wash order (done time)" };
|
||||
mode = "timeCredit";
|
||||
minutes = Math.max(0, input.wash.washMinutes) + Math.max(0, program.minutes ?? 0);
|
||||
break;
|
||||
}
|
||||
case "washPrice": {
|
||||
if (!input.wash) return { ok: false, status: 400, error: "this program needs a car wash order (price)" };
|
||||
mode = "fixed";
|
||||
amountMinor = Math.max(0, input.wash.priceMinor);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return { ok: false, status: 400, error: `unknown program mode ${String(program.mode)}` };
|
||||
}
|
||||
|
||||
const ev = await eventLog.append({
|
||||
type: "validation",
|
||||
source: "manual",
|
||||
identity,
|
||||
payload: {
|
||||
sessionRef: identity,
|
||||
programId,
|
||||
programLabel: program.name,
|
||||
mode,
|
||||
...(program.mode !== mode ? { programMode: program.mode } : {}),
|
||||
...(minutes != null ? { minutes } : {}),
|
||||
...(percent != null ? { percent } : {}),
|
||||
...(amountMinor != null ? { amountMinor } : {}),
|
||||
operator: actor,
|
||||
},
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
eventId: ev.id,
|
||||
programId,
|
||||
label: program.name,
|
||||
mode,
|
||||
minutes,
|
||||
percent,
|
||||
amountMinor,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user