Compare commits
77 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d0536da3d7 | |||
| ae736a9e3e | |||
| 1b54775b4d | |||
| f2734641b2 | |||
| de858e91f4 | |||
| 294ca85ded | |||
| eafbc3ddbb | |||
| 36f30d39ff | |||
| 488dcb5e4e | |||
| c64457020f | |||
| ff04ec10be | |||
| e0e218fa61 | |||
| 21bd0f6227 | |||
| 53e1e7b25c | |||
| fd4608a8f1 | |||
| 052da8c3a7 | |||
| cb68cbafdb | |||
| 2835f78635 | |||
| a20400c2c5 | |||
| cdb55a8652 | |||
| b0c9ba0f8c | |||
| 9a1feeeb20 | |||
| cc507f490f | |||
| 3d02134711 | |||
| a4712774ab | |||
| 918f76fbef | |||
| 9ec644811a | |||
| ecaaefd899 | |||
| 4af8b56dda | |||
| 540b333b06 | |||
| 7e086ff0d7 | |||
| 236cbfecab | |||
| 17fdf3d482 | |||
| 4833b4373d | |||
| 5cedcaefe1 | |||
| 6933406ae3 | |||
| ee28b7302f | |||
| e4827c9651 | |||
| c0a775818b | |||
| 30e7fe85de | |||
| bfb6ab0b36 | |||
| 0074e82a2a | |||
| bbf61c48df | |||
| 00f3d141b6 | |||
| f31e57b4ae | |||
| 040c0ff4ca | |||
| 8444bf34c3 | |||
| 808fb26ab6 | |||
| ef0ecadff9 | |||
| d0841c8601 | |||
| d71ba82999 | |||
| 9c9f777784 | |||
| 486f8deae6 | |||
| 3e6773a6d5 | |||
| cf1ff5676d | |||
| 91cc79b14e | |||
| dfa76346d6 | |||
| c9a2ef81a9 | |||
| b8ddda86e7 | |||
| bba988c4e8 | |||
| 5697137c52 | |||
| ca8c7f2fa2 | |||
| f87e4c0d6b | |||
| 4e2e4feedb | |||
| 48660d3ec8 | |||
| 14c83e182a | |||
| 445bca0bf6 | |||
| 062feeae2f | |||
| 50a3095ef3 | |||
| eb3dc18e67 | |||
| 06dab1e790 | |||
| 9956488fd5 | |||
| 49df2015c8 | |||
| c2f06a5d2a | |||
| 58d8f06ba0 | |||
| 71aaad03b9 | |||
| 727c62da90 |
@@ -1,24 +1,5 @@
|
|||||||
{
|
{
|
||||||
"hooks": {
|
"hooks": {
|
||||||
"PreToolUse": [
|
"PreToolUse": []
|
||||||
{
|
|
||||||
"matcher": "Bash",
|
|
||||||
"hooks": [
|
|
||||||
{
|
|
||||||
"type": "command",
|
|
||||||
"command": "CMD=$(python3 -c \"import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',d).get('command',''))\" 2>/dev/null || true); case \"$CMD\" in *grep*|*rg\\ *|*ripgrep*|*find\\ *|*fd\\ *|*ack\\ *|*ag\\ *) [ -f graphify-out/graph.json ] && echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"MANDATORY: graphify-out/graph.json exists. You MUST run `graphify query \\\"<question>\\\"` before grepping raw files. Only grep after graphify has oriented you, or to modify/debug specific lines.\"}}' || true ;; esac"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"matcher": "Read|Glob",
|
|
||||||
"hooks": [
|
|
||||||
{
|
|
||||||
"type": "command",
|
|
||||||
"command": "HIT=$(python3 -c \"import json,sys;d=json.load(sys.stdin);t=d.get('tool_input',d);s=(str(t.get('file_path') or '')+' '+str(t.get('pattern') or '')+' '+str(t.get('path') or '')).lower().replace(chr(92),'/');exts=('.py','.js','.ts','.tsx','.jsx','.go','.rs','.java','.rb','.c','.h','.cpp','.hpp','.cc','.cs','.kt','.swift','.php','.scala','.lua','.sh','.md','.rst','.txt','.mdx');sys.stdout.write('1' if 'graphify-out/' not in s and any(e in s for e in exts) else '')\" 2>/dev/null || true); if [ \"$HIT\" = 1 ] && [ -f graphify-out/graph.json ]; then echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"MANDATORY: graphify-out/graph.json exists. You MUST run graphify before reading source files. Use: `graphify query \\\"<question>\\\"` (scoped subgraph), `graphify explain \\\"<concept>\\\"`, or `graphify path \\\"<A>\\\" \\\"<B>\\\"`. Only read raw files after graphify has oriented you, or to modify/debug specific lines. This rule applies to subagents too \u2014 include it in every subagent prompt involving code exploration.\"}}'; fi || true"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,6 +11,8 @@ dist/
|
|||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
|
# Committed (non-secret): the desktop/prod build's backend origin — see apps/web/.env.production
|
||||||
|
!.env.production
|
||||||
|
|
||||||
# Editor/OS
|
# Editor/OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
@@ -24,3 +26,4 @@ dist/
|
|||||||
|
|
||||||
# Graphify knowledge-graph output (dev tool; generated, not committed)
|
# Graphify knowledge-graph output (dev tool; generated, not committed)
|
||||||
graphify-out/
|
graphify-out/
|
||||||
|
parking.sqlite*.bak-*
|
||||||
@@ -17,7 +17,8 @@ parking-system/
|
|||||||
├── turbo.json
|
├── turbo.json
|
||||||
├── apps/
|
├── apps/
|
||||||
│ ├── server/ # Fastify backend (device drivers, API, auth); serves the SPA
|
│ ├── server/ # Fastify backend (device drivers, API, auth); serves the SPA
|
||||||
│ └── web/ # React + Vite SPA (operator UI)
|
│ ├── web/ # React + Vite SPA (operator UI)
|
||||||
|
│ └── vision/ # Python/FastAPI ANPR service (planned; separate process, Turbo shim — see wiki/decisions/vision-service-packaging.md)
|
||||||
├── packages/
|
├── packages/
|
||||||
│ ├── db/ # Drizzle ORM schema + migrations (SQLite local; PostgreSQL sync target)
|
│ ├── db/ # Drizzle ORM schema + migrations (SQLite local; PostgreSQL sync target)
|
||||||
│ ├── devices/ # device adapters behind shared interfaces (reader/printer/relay)
|
│ ├── devices/ # device adapters behind shared interfaces (reader/printer/relay)
|
||||||
@@ -86,13 +87,3 @@ For the full reasoning behind each, follow the links from `wiki/overview.md`.
|
|||||||
|
|
||||||
- TypeScript throughout. Match the style of surrounding code.
|
- TypeScript throughout. Match the style of surrounding code.
|
||||||
- Confirm before destructive or outward-facing actions. Commit/push only when asked.
|
- Confirm before destructive or outward-facing actions. Commit/push only when asked.
|
||||||
|
|
||||||
## graphify
|
|
||||||
|
|
||||||
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
|
|
||||||
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
|
|
||||||
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
|
|
||||||
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
|
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Desktop (Tauri) build — the @parking/web SPA needs to know where Fastify is.
|
||||||
|
#
|
||||||
|
# In a BROWSER (dev via the Vite proxy, or prod where Fastify serves the SPA),
|
||||||
|
# leave VITE_API_BASE UNSET — requests stay relative/same-origin.
|
||||||
|
#
|
||||||
|
# For the DESKTOP build, the bundled SPA loads from tauri://localhost and has no
|
||||||
|
# proxy, so point it at the appliance's Fastify origin. This is read at WEB build
|
||||||
|
# time, so export it before `pnpm --filter @parking/desktop build` (or put it in
|
||||||
|
# apps/web/.env.production).
|
||||||
|
VITE_API_BASE=http://127.0.0.1:3000
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Rust / Tauri build artifacts
|
||||||
|
src-tauri/target/
|
||||||
|
src-tauri/gen/
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# @parking/desktop — Tauri v2 kiosk shell
|
||||||
|
|
||||||
|
A **thin native desktop window** over the `@parking/web` SPA. It contains **no UI and no business
|
||||||
|
logic** of its own: the window renders the *same* web app the browser does, so the desktop and the
|
||||||
|
browser stay identical and never drift. Device/auth/ledger logic stays in `@parking/server`. See
|
||||||
|
`wiki/decisions/desktop-shell-tauri.md`.
|
||||||
|
|
||||||
|
## How the "same look & functionality" guarantee works
|
||||||
|
|
||||||
|
| | Source of the UI |
|
||||||
|
| --- | --- |
|
||||||
|
| **Dev** (`tauri dev`) | the window loads `http://localhost:5173` — the **`@parking/web` Vite dev server**. Edit a component in `apps/web` → HMR updates the desktop window live. |
|
||||||
|
| **Prod** (`tauri build`) | the window bundles `apps/web`'s built `dist/`. `beforeBuildCommand` rebuilds the SPA first. |
|
||||||
|
|
||||||
|
There is only one UI codebase (`apps/web`); this package just wraps it.
|
||||||
|
|
||||||
|
## Backend connection
|
||||||
|
|
||||||
|
The SPA talks to Fastify over HTTP/WS. In a browser that's same-origin (relative `/api`). In the
|
||||||
|
desktop build the bundled assets load from `tauri://localhost`, so set **`VITE_API_BASE`** (read at
|
||||||
|
web build time — see `.env.example`) to the appliance's Fastify origin, e.g.
|
||||||
|
`http://127.0.0.1:3000`. The CSP `connect-src` in `tauri.conf.json` is already allowed for that
|
||||||
|
origin, and the backend must include the Tauri origin in `WS_ALLOWED_ORIGINS` for the live feed.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm --filter @parking/desktop dev # native window over the web dev server (HMR)
|
||||||
|
pnpm --filter @parking/desktop bundle # build the SPA + bundle the desktop app (.deb/.rpm/.AppImage)
|
||||||
|
```
|
||||||
|
|
||||||
|
> `build` is a **no-op** in this package so `turbo run build` stays fast — the real desktop bundle
|
||||||
|
> (compiles Rust, minutes long) is the explicit `bundle` script above.
|
||||||
|
|
||||||
|
Requires the Rust toolchain and (on Linux) WebKitGTK 4.1 + libsoup-3 dev libraries. Under WSL2 the
|
||||||
|
window needs a display (WSLg or an X server).
|
||||||
|
|
||||||
|
## Not here (deliberately)
|
||||||
|
|
||||||
|
Kiosk lockdown (fullscreen/no-decorations), auto-update, code signing, and launching Fastify from
|
||||||
|
the shell are out of scope for the scaffold — on the appliance Fastify runs as its own service and
|
||||||
|
this shell connects to it.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"name": "@parking/desktop",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"//": "Tauri v2 desktop shell — a THIN native window over the @parking/web SPA. No business logic lives here (device/auth/ledger stay in @parking/server); see wiki/decisions/desktop-shell-tauri.md. Dev loads the web dev server (HMR); build bundles the web app's dist/, so the desktop UI and the browser UI are the SAME codebase and never drift.",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tauri dev",
|
||||||
|
"build": "echo 'no-op in the Turbo graph — the real desktop bundle is a deliberate `pnpm --filter @parking/desktop bundle` (compiles Rust + packages installers, minutes long)'",
|
||||||
|
"bundle": "tauri build",
|
||||||
|
"tauri": "tauri",
|
||||||
|
"lint": "echo 'no JS lint (Tauri shell; Rust checked via cargo)'"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tauri-apps/cli": "^2.9.1"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@tauri-apps/plugin-process": "^2.3.1",
|
||||||
|
"@tauri-apps/plugin-updater": "^2.10.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
[package]
|
||||||
|
name = "parking-desktop"
|
||||||
|
version = "0.0.0"
|
||||||
|
description = "Parking System — desktop kiosk shell"
|
||||||
|
edition = "2021"
|
||||||
|
rust-version = "1.77"
|
||||||
|
|
||||||
|
# Thin Tauri v2 shell. Deliberately holds NO business logic — it loads the
|
||||||
|
# @parking/web SPA and lets it talk to the local Fastify server. Device/auth/
|
||||||
|
# ledger stay server-side. See wiki/decisions/desktop-shell-tauri.md.
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "parking_desktop_lib"
|
||||||
|
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
tauri-build = { version = "2", features = [] }
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tauri = { version = "2", features = [] }
|
||||||
|
serde_json = "1"
|
||||||
|
# Auto-update: prompt the operator, download a signed update, relaunch.
|
||||||
|
tauri-plugin-updater = "2"
|
||||||
|
tauri-plugin-process = "2"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
# Used by `tauri dev`/CLI for hot-reload of the Rust side.
|
||||||
|
custom-protocol = ["tauri/custom-protocol"]
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
fn main() {
|
||||||
|
tauri_build::build()
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
|
"identifier": "default",
|
||||||
|
"description": "Minimal capability set for the kiosk shell. The window only needs to render the SPA; it is granted NOTHING that touches the filesystem, shell, or devices — those stay server-side. Add a named permission here only when a concrete need arises (deny-by-default). See wiki/decisions/desktop-shell-tauri.md.",
|
||||||
|
"windows": ["main"],
|
||||||
|
"permissions": [
|
||||||
|
"core:default",
|
||||||
|
"updater:default",
|
||||||
|
"process:default"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 953 B |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 552 B |
|
After Width: | Height: | Size: 745 B |
|
After Width: | Height: | Size: 891 B |
|
After Width: | Height: | Size: 1016 B |
|
After Width: | Height: | Size: 997 B |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 562 B |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 643 B |
|
After Width: | Height: | Size: 748 B |
|
After Width: | Height: | Size: 838 B |
|
After Width: | Height: | Size: 706 B |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
@@ -0,0 +1,21 @@
|
|||||||
|
// Parking System desktop shell — entry point.
|
||||||
|
//
|
||||||
|
// Intentionally minimal: build the default Tauri app and run it. The window
|
||||||
|
// config (kiosk, fullscreen, which URL/assets to load) lives in tauri.conf.json.
|
||||||
|
// No custom commands are registered — the renderer (the @parking/web SPA) reaches
|
||||||
|
// the backend over HTTP to the local Fastify server, NOT through Tauri IPC. This
|
||||||
|
// keeps the shell a thin presentation wrapper with a deny-by-default native
|
||||||
|
// surface (see wiki/decisions/desktop-shell-tauri.md).
|
||||||
|
|
||||||
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||||
|
pub fn run() {
|
||||||
|
tauri::Builder::default()
|
||||||
|
// Auto-update: the JS side (apps/web) checks on launch, prompts the
|
||||||
|
// operator, and installs + relaunches on confirm. These plugins expose
|
||||||
|
// the update check/install and the relaunch to that flow. The updater
|
||||||
|
// endpoint + signing pubkey live in tauri.conf.json.
|
||||||
|
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||||
|
.plugin(tauri_plugin_process::init())
|
||||||
|
.run(tauri::generate_context!())
|
||||||
|
.expect("error while running the Parking System desktop shell");
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Prevents an extra console window on Windows in release.
|
||||||
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
parking_desktop_lib::run()
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
|
"productName": "Parking System",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"identifier": "com.parking.desktop",
|
||||||
|
"build": {
|
||||||
|
"devUrl": "http://localhost:5173",
|
||||||
|
"frontendDist": "../../web/dist",
|
||||||
|
"beforeDevCommand": "pnpm --filter @parking/web dev",
|
||||||
|
"beforeBuildCommand": "pnpm --filter @parking/web build"
|
||||||
|
},
|
||||||
|
"app": {
|
||||||
|
"windows": [
|
||||||
|
{
|
||||||
|
"label": "main",
|
||||||
|
"title": "Parking System",
|
||||||
|
"width": 1280,
|
||||||
|
"height": 800,
|
||||||
|
"minWidth": 1024,
|
||||||
|
"minHeight": 640,
|
||||||
|
"resizable": true,
|
||||||
|
"maximized": true,
|
||||||
|
"fullscreen": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"security": {
|
||||||
|
"csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; connect-src 'self' http://127.0.0.1:3000 http://localhost:3000 ws://127.0.0.1:3000 ws://localhost:3000"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"bundle": {
|
||||||
|
"active": true,
|
||||||
|
"targets": "all",
|
||||||
|
"createUpdaterArtifacts": true,
|
||||||
|
"icon": [
|
||||||
|
"icons/32x32.png",
|
||||||
|
"icons/128x128.png",
|
||||||
|
"icons/128x128@2x.png",
|
||||||
|
"icons/icon.icns",
|
||||||
|
"icons/icon.ico"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"plugins": {
|
||||||
|
"updater": {
|
||||||
|
"endpoints": [
|
||||||
|
"https://UPDATES.EXAMPLE.invalid/parking/{{target}}/{{arch}}/{{current_version}}"
|
||||||
|
],
|
||||||
|
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDgxNzg5RUQ1QkM0Q0FDRjYKUldUMnJFeTgxWjU0Z1RlNmhneDVZQlVVTVZZdGhJTkUxTGdDeGYwQSttZmNKVVp5WEdVMWlBb1YK"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://turbo.build/schema.json",
|
||||||
|
"extends": ["//"],
|
||||||
|
"//": "Tauri shell as a first-class Turbo node. build outputs [] so `turbo run build` doesn't try to cache/compile the Rust bundle on every pass (a real desktop bundle is a deliberate `pnpm --filter @parking/desktop build`).",
|
||||||
|
"tasks": {
|
||||||
|
"build": {
|
||||||
|
"outputs": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,13 @@
|
|||||||
# Generate one with: openssl rand -hex 32
|
# Generate one with: openssl rand -hex 32
|
||||||
JWT_SECRET=
|
JWT_SECRET=
|
||||||
|
|
||||||
|
# Dedicated HMAC key for signing the append-only event ledger (>=16 chars).
|
||||||
|
# Generate with: openssl rand -hex 32
|
||||||
|
# If unset, the server falls back to JWT_SECRET (logged as a warning) — fine for
|
||||||
|
# dev, but set a dedicated key before production. Events store the key that signed
|
||||||
|
# them (keyId), so verifyChain still validates a chain that spans a key change.
|
||||||
|
EVENT_SIGNING_KEY=
|
||||||
|
|
||||||
# Optional ----------------------------------------------------------------
|
# Optional ----------------------------------------------------------------
|
||||||
# PORT=3000
|
# PORT=3000
|
||||||
# HOST=0.0.0.0 # interface to bind. 127.0.0.1 = loopback only.
|
# HOST=0.0.0.0 # interface to bind. 127.0.0.1 = loopback only.
|
||||||
@@ -18,3 +25,18 @@ JWT_SECRET=
|
|||||||
# First admin (seed once): pnpm --filter @parking/server seed-admin
|
# First admin (seed once): pnpm --filter @parking/server seed-admin
|
||||||
# ADMIN_USER=admin
|
# ADMIN_USER=admin
|
||||||
# ADMIN_PASS=
|
# ADMIN_PASS=
|
||||||
|
|
||||||
|
# Comma-separated extra origins allowed to open the booth WebSocket (/api/ws).
|
||||||
|
# In dev, set the Vite SPA origin. Same-origin is always allowed without this.
|
||||||
|
WS_ALLOWED_ORIGINS=http://localhost:5173
|
||||||
|
|
||||||
|
# Vision / ANPR (optional) -------------------------------------------------
|
||||||
|
# OFF by default. The Node SERVER's view of the vision microservice (apps/vision),
|
||||||
|
# which runs as a separate process with its OWN apps/vision/.env. Both sides share the
|
||||||
|
# VISION_ prefix but are different processes — keep the two .env files separate.
|
||||||
|
# See wiki/entities/opencv-anpr-service.md "Configuration".
|
||||||
|
# ANPR rides the entry/exit snapshot (button / QR / RFID triggers it) — no polling.
|
||||||
|
# VISION_ENABLED=1 # master switch — nothing runs without it
|
||||||
|
# VISION_URL=http://127.0.0.1:8089 # must match apps/vision VISION_HOST:VISION_PORT
|
||||||
|
# VISION_TIMEOUT_MS=1500 # per-request cap so a slow call can't hang the lane
|
||||||
|
# VISION_MIN_CONFIDENCE=0.5 # confidence floor; keep in sync with the service
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
"@fastify/cors": "11.2.0",
|
"@fastify/cors": "11.2.0",
|
||||||
"@fastify/jwt": "10.1.0",
|
"@fastify/jwt": "10.1.0",
|
||||||
"@fastify/static": "9.1.3",
|
"@fastify/static": "9.1.3",
|
||||||
|
"@fastify/websocket": "^11.2.0",
|
||||||
"@parking/db": "workspace:*",
|
"@parking/db": "workspace:*",
|
||||||
"@parking/devices": "workspace:*",
|
"@parking/devices": "workspace:*",
|
||||||
"@parking/shared": "workspace:*",
|
"@parking/shared": "workspace:*",
|
||||||
|
|||||||
@@ -62,14 +62,14 @@ if (existing && process.env.FORCE !== "1") {
|
|||||||
const passwordHash = await bcrypt.hash(password, 12);
|
const passwordHash = await bcrypt.hash(password, 12);
|
||||||
|
|
||||||
if (existing) {
|
if (existing) {
|
||||||
await db.update(users).set({ passwordHash, role: "admin" }).where(eq(users.id, existing.id));
|
await db.update(users).set({ passwordHash, roleId: "admin" }).where(eq(users.id, existing.id));
|
||||||
console.log(`reset password for admin "${username}"`);
|
console.log(`reset password for admin "${username}"`);
|
||||||
} else {
|
} else {
|
||||||
await db.insert(users).values({
|
await db.insert(users).values({
|
||||||
id: randomUUID(),
|
id: randomUUID(),
|
||||||
username,
|
username,
|
||||||
passwordHash,
|
passwordHash,
|
||||||
role: "admin",
|
roleId: "admin",
|
||||||
});
|
});
|
||||||
console.log(`created admin "${username}"`);
|
console.log(`created admin "${username}"`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,22 @@
|
|||||||
import { randomBytes } from "node:crypto";
|
import { randomBytes } from "node:crypto";
|
||||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||||
import type { Role } from "@parking/shared";
|
import { eq, rolePermissions, type Db } from "@parking/db";
|
||||||
|
import { ADMIN_ROLE_ID, PERMISSIONS, type Permission } from "@parking/shared";
|
||||||
|
|
||||||
// Local JWT auth helpers — fully local, no external identity provider
|
// Local JWT auth helpers — fully local, no external identity provider
|
||||||
// (offline-first). The JWT is carried in an HttpOnly cookie (JS can't read it);
|
// (offline-first). The JWT is carried in an HttpOnly cookie (JS can't read it);
|
||||||
// a separate readable CSRF cookie + matching header defends mutations
|
// a separate readable CSRF cookie + matching header defends mutations
|
||||||
// (double-submit). See wiki/entities/local-jwt-auth.md.
|
// (double-submit). See wiki/entities/local-jwt-auth.md.
|
||||||
|
//
|
||||||
|
// Authorization is DYNAMIC RBAC: the token carries the user's `roleId`, and each
|
||||||
|
// guarded route resolves that role's PERMISSION SET (cached in memory) and checks
|
||||||
|
// the permission it requires. Editing a role takes effect on the next request —
|
||||||
|
// no re-login, no token bloat, no stale perms. See @parking/shared PERMISSIONS.
|
||||||
|
|
||||||
declare module "@fastify/jwt" {
|
declare module "@fastify/jwt" {
|
||||||
interface FastifyJWT {
|
interface FastifyJWT {
|
||||||
payload: { sub: string; username: string; role: Role; csrf: string };
|
payload: { sub: string; username: string; roleId: string; csrf: string };
|
||||||
user: { sub: string; username: string; role: Role; csrf: string };
|
user: { sub: string; username: string; roleId: string; csrf: string };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,17 +102,84 @@ function assertCsrf(req: FastifyRequest): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Permission resolution + cache -------------------------------------------
|
||||||
|
// A role's permission set is read from `role_permissions` and cached in memory.
|
||||||
|
// SQLite is single-writer/single-process here, so a module-level Map is a correct
|
||||||
|
// cache: every role / role-permission mutation calls bumpPermsCache() to clear it,
|
||||||
|
// and the next request re-reads. The built-in `admin` role always resolves to the
|
||||||
|
// FULL permission set in code (never trusts the DB rows for it), so administration
|
||||||
|
// can't be accidentally narrowed.
|
||||||
|
|
||||||
|
const ADMIN_PERMS: ReadonlySet<Permission> = new Set(PERMISSIONS);
|
||||||
|
const permsCache = new Map<string, ReadonlySet<Permission>>();
|
||||||
|
|
||||||
|
// The DB handle the permission resolver reads from. Set ONCE at startup via
|
||||||
|
// initAuth() so route guards don't each have to thread `db` (several route
|
||||||
|
// modules only receive a monitor/service, not the db). Single-process server.
|
||||||
|
let authDb: Db | null = null;
|
||||||
|
|
||||||
|
/** Wire the permission resolver to the app's DB. Call once in buildServer(). */
|
||||||
|
export function initAuth(db: Db): void {
|
||||||
|
authDb = db;
|
||||||
|
permsCache.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clear the permission cache. Call after ANY write to roles / role_permissions
|
||||||
|
* (or a user's roleId) so the change takes effect on the next request. */
|
||||||
|
export function bumpPermsCache(): void {
|
||||||
|
permsCache.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The permission set for a role id, cached. `admin` is always the full set. */
|
||||||
|
export function permissionsFor(roleId: string): ReadonlySet<Permission> {
|
||||||
|
if (roleId === ADMIN_ROLE_ID) return ADMIN_PERMS;
|
||||||
|
const hit = permsCache.get(roleId);
|
||||||
|
if (hit) return hit;
|
||||||
|
if (!authDb) throw new Error("auth not initialised (call initAuth)");
|
||||||
|
const rows = authDb
|
||||||
|
.select({ permission: rolePermissions.permission })
|
||||||
|
.from(rolePermissions)
|
||||||
|
.where(eq(rolePermissions.roleId, roleId))
|
||||||
|
.all();
|
||||||
|
const set = new Set(rows.map((r) => r.permission as Permission));
|
||||||
|
permsCache.set(roleId, set);
|
||||||
|
return set;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True if the role grants every listed permission. */
|
||||||
|
export function roleHasPermissions(
|
||||||
|
roleId: string,
|
||||||
|
required: readonly Permission[],
|
||||||
|
): boolean {
|
||||||
|
const granted = permissionsFor(roleId);
|
||||||
|
return required.every((p) => granted.has(p));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* preHandler role guard. Verifies the JWT (from the HttpOnly cookie), enforces
|
* preHandler permission guard. Verifies the JWT (from the HttpOnly cookie),
|
||||||
* CSRF on mutations, then checks the role. Authorization is a simple per-route
|
* enforces CSRF on mutations, then requires the user's role to grant ALL of the
|
||||||
* role check — no Casbin/RBAC engine needed at this scale.
|
* listed permissions. Authorization is a per-route permission check against the
|
||||||
|
* dynamic, admin-composed role grid — no Casbin/RBAC engine needed at this scale.
|
||||||
*/
|
*/
|
||||||
export function requireRole(...allowed: Role[]) {
|
export function requirePermission(...required: Permission[]) {
|
||||||
return async (req: FastifyRequest, _reply: FastifyReply) => {
|
return async (req: FastifyRequest, _reply: FastifyReply) => {
|
||||||
await req.jwtVerify(); // reads the token cookie (configured in server.ts)
|
await req.jwtVerify(); // reads the token cookie (configured in server.ts)
|
||||||
assertCsrf(req);
|
assertCsrf(req);
|
||||||
if (!req.user || !allowed.includes(req.user.role)) {
|
if (!req.user || !roleHasPermissions(req.user.roleId, required)) {
|
||||||
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* preHandler that requires a valid signed-in session but NO specific permission —
|
||||||
|
* for "about me" routes (/me, change own language) every authenticated user may
|
||||||
|
* call regardless of role. Still enforces CSRF on mutations.
|
||||||
|
*/
|
||||||
|
export async function requireAuth(
|
||||||
|
req: FastifyRequest,
|
||||||
|
_reply: FastifyReply,
|
||||||
|
): Promise<void> {
|
||||||
|
await req.jwtVerify();
|
||||||
|
assertCsrf(req);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,192 @@
|
|||||||
|
import { eq, ledgerEvents, siteConfig, type Db } from "@parking/db";
|
||||||
|
import {
|
||||||
|
formatStampSq,
|
||||||
|
printWithFailover,
|
||||||
|
registry,
|
||||||
|
type PrinterDevice,
|
||||||
|
type PrinterInstance,
|
||||||
|
type ReceiptData,
|
||||||
|
type TicketHeader,
|
||||||
|
} from "@parking/devices";
|
||||||
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
import { devicesByDirection } from "./device-resolve.js";
|
||||||
|
|
||||||
|
// Booth-side printing for the EXIT VOUCHER ("biletë dalje"). When the booth is far
|
||||||
|
// from the exit, the customer pays at the booth and walks a printed voucher to the
|
||||||
|
// exit, where they self-scan it. The voucher reprints the SAME ticket id as a
|
||||||
|
// Code128 barcode (now a paid session) — so the exit reader runs the normal exit
|
||||||
|
// validation and opens. See wiki/concepts/booth-exit-flow.md, ticket-encoding.md.
|
||||||
|
//
|
||||||
|
// This mirrors the entry flow's printer selection + header build, but prints on the
|
||||||
|
// BOOTH printer (role "booth-receipt") since that's where the operator stands.
|
||||||
|
|
||||||
|
/** Park identity for the voucher header, from site_config (all fields optional). */
|
||||||
|
function ticketHeader(db: Db): TicketHeader | undefined {
|
||||||
|
const row = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||||
|
if (!row) return undefined;
|
||||||
|
return {
|
||||||
|
parkName: row.parkName,
|
||||||
|
operatorName: row.operatorName,
|
||||||
|
nius: row.nius,
|
||||||
|
address: row.address,
|
||||||
|
phone: row.phone,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build live printer instances for failover selection (entry direction covers the
|
||||||
|
* booth-receipt role too — the booth printer is configured on the entry side). */
|
||||||
|
function loadPrinters(db: Db): PrinterInstance[] {
|
||||||
|
const rows = devicesByDirection(db, "printer", "entry");
|
||||||
|
const out: PrinterInstance[] = [];
|
||||||
|
for (const row of rows) {
|
||||||
|
const driver = registry.get(row.driverId);
|
||||||
|
if (!driver) continue;
|
||||||
|
const cfg = row.config as Record<string, unknown>;
|
||||||
|
const role = cfg.role === "booth-receipt" ? "booth-receipt" : "entry-dispenser";
|
||||||
|
try {
|
||||||
|
out.push({
|
||||||
|
id: row.id,
|
||||||
|
role,
|
||||||
|
failoverRank: typeof cfg.failoverRank === "number" ? cfg.failoverRank : 0,
|
||||||
|
device: driver.create(cfg as never) as PrinterDevice,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// skip a printer whose config won't build
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The receipt figures for a paid session, folded from the SIGNED ledger
|
||||||
|
* (authoritative). Null if there's no entry or no payment for this id — the
|
||||||
|
* caller should have validated paid + open before printing. */
|
||||||
|
function receiptFigures(
|
||||||
|
db: Db,
|
||||||
|
ticketId: string,
|
||||||
|
): Omit<ReceiptData, "voucher" | "header"> | null {
|
||||||
|
const rows = db
|
||||||
|
.select()
|
||||||
|
.from(ledgerEvents)
|
||||||
|
.where(eq(ledgerEvents.identity, ticketId))
|
||||||
|
.orderBy(ledgerEvents.index)
|
||||||
|
.all();
|
||||||
|
const entry = rows.find((r) => r.type === "vehicle_entry");
|
||||||
|
if (!entry) return null;
|
||||||
|
// The LATEST payment is the one we receipt (an overstay top-up re-pays).
|
||||||
|
let payment: (typeof rows)[number] | undefined;
|
||||||
|
for (const r of rows) if (r.type === "payment") payment = r;
|
||||||
|
if (!payment) return null;
|
||||||
|
const p = (payment.payload ?? {}) as {
|
||||||
|
amountMinor?: number;
|
||||||
|
currency?: string;
|
||||||
|
tender?: "cash" | "card";
|
||||||
|
graceExitMin?: number;
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
ticketId,
|
||||||
|
enteredAt: entry.occurredAt,
|
||||||
|
paidAt: payment.occurredAt,
|
||||||
|
amountMinor: typeof p.amountMinor === "number" ? p.amountMinor : 0,
|
||||||
|
currency: p.currency ?? "ALL",
|
||||||
|
tender: p.tender === "card" ? "card" : "cash",
|
||||||
|
graceExitMin: typeof p.graceExitMin === "number" ? p.graceExitMin : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Print a PAYMENT RECEIPT for a paid session on the booth printer (failing over
|
||||||
|
* to the entry dispenser). The receipt is the customer's transparency record:
|
||||||
|
* entry time, payment time, duration, amount + tender — folded from the signed
|
||||||
|
* ledger. In VOUCHER mode it also carries the scannable ticket-id barcode + the
|
||||||
|
* walk-back grace, so the one slip both proves payment AND self-exits at a
|
||||||
|
* distant exit reader (this replaces the old barcode-only voucher). In standalone
|
||||||
|
* mode (`voucher:false`) it is detail-only, printed at payment when the booth is
|
||||||
|
* at the exit. Returns the id of the printer that printed it.
|
||||||
|
* Throws NoPrinterAvailableError if none can; throws if the session isn't payable.
|
||||||
|
*/
|
||||||
|
export async function printPaymentReceipt(
|
||||||
|
db: Db,
|
||||||
|
ticketId: string,
|
||||||
|
opts: { voucher: boolean },
|
||||||
|
logger: FastifyBaseLogger,
|
||||||
|
): Promise<string> {
|
||||||
|
const figures = receiptFigures(db, ticketId);
|
||||||
|
if (!figures) {
|
||||||
|
throw new Error(`no paid session to receipt for ${ticketId}`);
|
||||||
|
}
|
||||||
|
const printers = loadPrinters(db);
|
||||||
|
const data: ReceiptData = {
|
||||||
|
...figures,
|
||||||
|
voucher: opts.voucher,
|
||||||
|
header: ticketHeader(db),
|
||||||
|
};
|
||||||
|
// Prefer the booth printer (operator is at the booth); fall back to the dispenser.
|
||||||
|
const printedBy = await printWithFailover(printers, "booth-receipt", (d: PrinterDevice) =>
|
||||||
|
d.printReceipt(data),
|
||||||
|
);
|
||||||
|
logger.info(
|
||||||
|
`${opts.voucher ? "exit voucher" : "payment receipt"} for ${ticketId} printed on ${printedBy}`,
|
||||||
|
);
|
||||||
|
return printedBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Print a SUBSCRIPTION CARD on the booth printer (failing over to the dispenser):
|
||||||
|
* a scannable QR of the credential code + holder/validity, so the operator can hand
|
||||||
|
* it to the customer. Used on subscription creation and on a "reprint" action.
|
||||||
|
* Returns the printer that printed it; throws NoPrinterAvailableError if none can.
|
||||||
|
*/
|
||||||
|
export async function printSubscriptionCard(
|
||||||
|
db: Db,
|
||||||
|
card: { code: string; holderName?: string | null; validFrom?: string | null; validTo?: string | null },
|
||||||
|
logger: FastifyBaseLogger,
|
||||||
|
): Promise<string> {
|
||||||
|
const printers = loadPrinters(db);
|
||||||
|
const data = {
|
||||||
|
code: card.code,
|
||||||
|
holderName: card.holderName ?? null,
|
||||||
|
validFrom: card.validFrom ?? null,
|
||||||
|
validTo: card.validTo ?? null,
|
||||||
|
header: ticketHeader(db),
|
||||||
|
};
|
||||||
|
const printedBy = await printWithFailover(printers, "booth-receipt", (d: PrinterDevice) =>
|
||||||
|
d.printSubscriptionCard(data),
|
||||||
|
);
|
||||||
|
logger.info(`subscription card ${card.code} printed on ${printedBy}`);
|
||||||
|
return printedBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Print an ADVISORY "out-of-window" slip when a subscriber enters (or exits) outside
|
||||||
|
* their plan's allowed hours. It is NOT a payable ticket and carries NO final amount —
|
||||||
|
* the total is computed at the booth on settlement (early-entry AND any late-exit time
|
||||||
|
* combined). It just gives the subscriber paper proof that a fee is pending against this
|
||||||
|
* occurrence. Albanian (like every customer-facing slip — see i18n.md). Best-effort:
|
||||||
|
* the caller swallows failures so a missing printer never blocks the barrier.
|
||||||
|
*/
|
||||||
|
export async function printWindowChargeNotice(
|
||||||
|
db: Db,
|
||||||
|
notice: { occurrenceId: string; holderName?: string | null; at: string; windowOpensMin?: number; edge: "entry" | "exit" },
|
||||||
|
logger: FastifyBaseLogger,
|
||||||
|
): Promise<string> {
|
||||||
|
const printers = loadPrinters(db);
|
||||||
|
const hhmm = (m?: number) =>
|
||||||
|
m == null ? "" : `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`;
|
||||||
|
const lines = [
|
||||||
|
`Abonent: ${notice.holderName || "-"}`,
|
||||||
|
`${notice.edge === "entry" ? "Hyrje" : "Dalje"}: ${formatStampSq(notice.at)}`,
|
||||||
|
notice.edge === "entry"
|
||||||
|
? `Ka hyrë jashtë orarit${notice.windowOpensMin != null ? ` (orari hap ${hhmm(notice.windowOpensMin)})` : ""}`
|
||||||
|
: "Ka dalë jashtë orarit",
|
||||||
|
"",
|
||||||
|
"⚠ Detyrim do të llogaritet në dalje",
|
||||||
|
" (paguhet në kabinë para se të dilni)",
|
||||||
|
"",
|
||||||
|
`Nr: ${notice.occurrenceId}`,
|
||||||
|
];
|
||||||
|
const printedBy = await printWithFailover(printers, "booth-receipt", (d: PrinterDevice) =>
|
||||||
|
d.printReport({ title: "PARKIM — JASHTË ORARIT", lines }),
|
||||||
|
);
|
||||||
|
logger.info(`out-of-window notice printed for ${notice.occurrenceId} on ${printedBy}`);
|
||||||
|
return printedBy;
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
// Credential capture ("enroll a card"): lets an operator present a physical RFID
|
||||||
|
// card/chip (or a QR) to ONE chosen reader and have its value captured for a
|
||||||
|
// subscription credential, instead of typing it. SINGLE-SHOT + short TTL so the
|
||||||
|
// chosen reader is only "borrowed" for one read / a few seconds; the OTHER reader is
|
||||||
|
// never affected and keeps serving the live entry/exit flow.
|
||||||
|
//
|
||||||
|
// Flow: arm(deviceId) → the reader route checks tryConsume() on each read; the next
|
||||||
|
// read from that armed reader is captured (NOT dispatched to the access flow — the
|
||||||
|
// barrier must not open for a card being enrolled) and capture auto-disarms. The
|
||||||
|
// booth form polls result() until the value appears (or it times out / is cancelled).
|
||||||
|
//
|
||||||
|
// In-memory + single-site single-writer (one booth) → no DB, no cross-process
|
||||||
|
// concerns. See wiki/entities/subscription.md.
|
||||||
|
|
||||||
|
const CAPTURE_TTL_MS = Number(process.env.CAPTURE_TTL_MS ?? 30_000);
|
||||||
|
|
||||||
|
export type CaptureState =
|
||||||
|
| { status: "idle" }
|
||||||
|
| { status: "armed"; deviceId: string; armedAt: number; expiresAt: number }
|
||||||
|
| { status: "captured"; deviceId: string; value: string; capturedAt: number }
|
||||||
|
| { status: "expired"; deviceId: string };
|
||||||
|
|
||||||
|
export class CredentialCapture {
|
||||||
|
#armedDeviceId: string | null = null;
|
||||||
|
#expiresAt = 0;
|
||||||
|
#captured: { deviceId: string; value: string; capturedAt: number } | null = null;
|
||||||
|
#lastExpiredDeviceId: string | null = null;
|
||||||
|
|
||||||
|
/** Arm a single-shot capture on one reader (by its `devices.id`). Replaces any
|
||||||
|
* prior arming (only one capture at a time). Clears a stale captured/expired
|
||||||
|
* result so the form starts fresh. */
|
||||||
|
arm(deviceId: string): { expiresAt: number } {
|
||||||
|
this.#armedDeviceId = deviceId;
|
||||||
|
this.#expiresAt = Date.now() + CAPTURE_TTL_MS;
|
||||||
|
this.#captured = null;
|
||||||
|
this.#lastExpiredDeviceId = null;
|
||||||
|
return { expiresAt: this.#expiresAt };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cancel any pending arming (operator closed the form / clicked cancel). */
|
||||||
|
cancel(): void {
|
||||||
|
this.#armedDeviceId = null;
|
||||||
|
this.#expiresAt = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called by the reader route on EVERY read. If this reader is the armed one (and
|
||||||
|
* not expired), capture the value, disarm, and return true → the caller must NOT
|
||||||
|
* dispatch this read to the access flow. Otherwise false → dispatch normally.
|
||||||
|
*/
|
||||||
|
tryConsume(deviceId: string, value: string): boolean {
|
||||||
|
if (this.#armedDeviceId == null) return false;
|
||||||
|
if (Date.now() > this.#expiresAt) {
|
||||||
|
// Window lapsed before a card was presented — disarm, mark expired.
|
||||||
|
this.#lastExpiredDeviceId = this.#armedDeviceId;
|
||||||
|
this.#armedDeviceId = null;
|
||||||
|
this.#expiresAt = 0;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (deviceId !== this.#armedDeviceId) return false; // a read from the OTHER reader
|
||||||
|
if (!value) return false;
|
||||||
|
this.#captured = { deviceId, value, capturedAt: Date.now() };
|
||||||
|
this.#armedDeviceId = null; // single-shot
|
||||||
|
this.#expiresAt = 0;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Current state for the booth form's poll. Lazily transitions armed→expired. */
|
||||||
|
state(): CaptureState {
|
||||||
|
if (this.#captured) return { status: "captured", ...this.#captured };
|
||||||
|
if (this.#armedDeviceId != null) {
|
||||||
|
if (Date.now() > this.#expiresAt) {
|
||||||
|
this.#lastExpiredDeviceId = this.#armedDeviceId;
|
||||||
|
this.#armedDeviceId = null;
|
||||||
|
this.#expiresAt = 0;
|
||||||
|
return { status: "expired", deviceId: this.#lastExpiredDeviceId };
|
||||||
|
}
|
||||||
|
return { status: "armed", deviceId: this.#armedDeviceId, armedAt: this.#expiresAt - CAPTURE_TTL_MS, expiresAt: this.#expiresAt };
|
||||||
|
}
|
||||||
|
if (this.#lastExpiredDeviceId) return { status: "expired", deviceId: this.#lastExpiredDeviceId };
|
||||||
|
return { status: "idle" };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clear a consumed/expired result once the form has read it. */
|
||||||
|
clear(): void {
|
||||||
|
this.#captured = null;
|
||||||
|
this.#lastExpiredDeviceId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
import type { PrinterStatus } from "@parking/devices";
|
import type { PrinterStatus } from "@parking/devices";
|
||||||
|
import type { LedgerEventRow } from "@parking/db";
|
||||||
|
|
||||||
// Internal event bus for device-originated events (button presses, etc.).
|
// Internal event bus for device-originated events (button presses, etc.).
|
||||||
// Hardware drivers / inbound device pushes emit here; business logic (entry
|
// Hardware drivers / inbound device pushes emit here; business logic (entry
|
||||||
@@ -16,7 +17,7 @@ export interface DeviceInputEvent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A credential read: a ticket scanned at exit, a plate from LPR, a card at a reader.
|
// A credential read: a ticket scanned at exit, a plate from LPR, a card at a reader.
|
||||||
// Drives identity-based flows (exit validation, permits, pay-station lookup). `kind`
|
// Drives identity-based flows (exit validation, subscriptions, pay-station lookup). `kind`
|
||||||
// mirrors IdentitySource. See parking-session.md.
|
// mirrors IdentitySource. See parking-session.md.
|
||||||
export interface DeviceReadEvent {
|
export interface DeviceReadEvent {
|
||||||
readonly driverId: string;
|
readonly driverId: string;
|
||||||
@@ -34,7 +35,7 @@ export interface DeviceReadEvent {
|
|||||||
export interface ReadOutcome {
|
export interface ReadOutcome {
|
||||||
/** Was the vehicle admitted/exited (barrier opened)? Drives the reader's beep. */
|
/** Was the vehicle admitted/exited (barrier opened)? Drives the reader's beep. */
|
||||||
readonly accepted: boolean;
|
readonly accepted: boolean;
|
||||||
/** Which way it went, when known (permit/exit infer this). */
|
/** Which way it went, when known (subscription/exit infer this). */
|
||||||
readonly direction?: "entry" | "exit";
|
readonly direction?: "entry" | "exit";
|
||||||
/** Human-readable reason (for logs / the reader UI), esp. on reject. */
|
/** Human-readable reason (for logs / the reader UI), esp. on reject. */
|
||||||
readonly reason?: string;
|
readonly reason?: string;
|
||||||
@@ -48,6 +49,33 @@ export interface PrinterStatusEvent {
|
|||||||
readonly status: PrinterStatus;
|
readonly status: PrinterStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The unified live status of ANY configured device — what the booth footer shows.
|
||||||
|
* Every enabled device is polled: printers via their rich `readStatus()`
|
||||||
|
* (paper/cover/cutter), all other categories via the generic `healthCheck()`
|
||||||
|
* reachability probe. `state` is the common traffic-light; `detail` carries the
|
||||||
|
* human summary (e.g. "paper out", or an unreachable error). See device-monitor.ts
|
||||||
|
* and wiki/concepts/device-status-monitoring.md.
|
||||||
|
*/
|
||||||
|
export interface DeviceStatusEvent {
|
||||||
|
readonly deviceId: string; // devices id
|
||||||
|
readonly driverId: string;
|
||||||
|
readonly category: "access" | "reader" | "camera" | "printer" | "vision";
|
||||||
|
/**
|
||||||
|
* The device's ROLE descriptor for the footer label — NOT the vendor. A
|
||||||
|
* direction-style token the client localises and pairs with the category, so the
|
||||||
|
* chip reads e.g. "Lexuesi hyrje" / "Kamera dalje" / "Printer kabina":
|
||||||
|
* - reader/camera: "entry" | "exit" | "both" (inherited from its bound relay)
|
||||||
|
* - access: "entry" | "exit" | "both" | "mixed" (from its relays[])
|
||||||
|
* - printer: "lane" (entry-dispenser) | "booth" (booth-receipt)
|
||||||
|
* - undetermined: null (chip shows the category alone)
|
||||||
|
*/
|
||||||
|
readonly roleKind: "entry" | "exit" | "both" | "mixed" | "lane" | "booth" | null;
|
||||||
|
readonly state: "ready" | "degraded" | "offline";
|
||||||
|
readonly detail?: string;
|
||||||
|
readonly checkedAt: string; // ISO-8601
|
||||||
|
}
|
||||||
|
|
||||||
class DeviceEventBus extends EventEmitter {
|
class DeviceEventBus extends EventEmitter {
|
||||||
emitInput(event: DeviceInputEvent): void {
|
emitInput(event: DeviceInputEvent): void {
|
||||||
this.emit("input", event);
|
this.emit("input", event);
|
||||||
@@ -74,6 +102,32 @@ class DeviceEventBus extends EventEmitter {
|
|||||||
this.on("printer-status", cb);
|
this.on("printer-status", cb);
|
||||||
return () => this.off("printer-status", cb);
|
return () => this.off("printer-status", cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Emitted by the device monitor whenever ANY device's unified status CHANGES
|
||||||
|
* (all categories — relays, readers, cameras, printers). Drives the booth
|
||||||
|
* device-status footer over the WS. */
|
||||||
|
emitDeviceStatus(event: DeviceStatusEvent): void {
|
||||||
|
this.emit("device-status", event);
|
||||||
|
}
|
||||||
|
onDeviceStatus(cb: (event: DeviceStatusEvent) => void): () => void {
|
||||||
|
this.on("device-status", cb);
|
||||||
|
return () => this.off("device-status", cb);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Emitted AFTER a signed business event is appended to the ledger (entry, exit,
|
||||||
|
* payment, void, …). The payload is the persisted row — business facts only, no
|
||||||
|
* secrets — so it is safe to fan out to authenticated booth clients over the WS.
|
||||||
|
* This is a read-side notification ONLY: it never feeds back into append/sign/
|
||||||
|
* chain logic. See event-log.ts (emitted from EventLog.append) and routes/ws.ts.
|
||||||
|
*/
|
||||||
|
emitLedger(event: LedgerEventRow): void {
|
||||||
|
this.emit("ledger", event);
|
||||||
|
}
|
||||||
|
onLedger(cb: (event: LedgerEventRow) => void): () => void {
|
||||||
|
this.on("ledger", cb);
|
||||||
|
return () => this.off("ledger", cb);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Process-wide device event bus. */
|
/** Process-wide device event bus. */
|
||||||
|
|||||||
@@ -0,0 +1,192 @@
|
|||||||
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
import { devices, type Db, type DeviceRow } from "@parking/db";
|
||||||
|
import { isMonitorable, registry } from "@parking/devices";
|
||||||
|
import { deviceEvents, type DeviceStatusEvent } from "./device-events.js";
|
||||||
|
import { directionOf, relaysOf } from "./device-resolve.js";
|
||||||
|
import type { VisionClient } from "./vision-client.js";
|
||||||
|
|
||||||
|
/** Synthetic device id for the vision service in the status footer (it's a service,
|
||||||
|
* not a device row, but shares the footer's traffic-light + WS plumbing). */
|
||||||
|
const VISION_STATUS_ID = "vision-service";
|
||||||
|
|
||||||
|
// Unified live DEVICE monitor — the source for the booth's device-status footer.
|
||||||
|
// Every enabled, configured device is probed on an interval, regardless of
|
||||||
|
// category: a printer via its rich readStatus() (paper/cover/cutter — reusing the
|
||||||
|
// same capability the PrinterMonitor uses), and a relay/reader/camera via the
|
||||||
|
// generic healthCheck() reachability probe every Device implements. The result is
|
||||||
|
// flattened to a common traffic-light (ready | degraded | offline) + a detail
|
||||||
|
// string, cached per device id, and emitted on the bus ONLY when it changes.
|
||||||
|
//
|
||||||
|
// This is device-agnostic (talks to the adapter interfaces, never a driver SDK)
|
||||||
|
// and read-only — polling a device never drives a relay or mutates the ledger.
|
||||||
|
// See wiki/concepts/device-status-monitoring.md, printer-status-monitoring.md.
|
||||||
|
|
||||||
|
const POLL_MS = Number(process.env.DEVICE_POLL_MS ?? 8000);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The device's ROLE descriptor for the footer (never the vendor). Direction-style
|
||||||
|
* tokens the client localises next to the category:
|
||||||
|
* - reader/camera → the direction inherited from its bound relay (entry/exit/both)
|
||||||
|
* - access → entry/exit/both from its relays[]; "mixed" if it spans more
|
||||||
|
* than one direction; null if it declares none yet
|
||||||
|
* - printer → "lane" (entry-dispenser) | "booth" (booth-receipt)
|
||||||
|
*/
|
||||||
|
function roleKindOf(db: Db, row: DeviceRow): DeviceStatusEvent["roleKind"] {
|
||||||
|
switch (row.category) {
|
||||||
|
case "reader":
|
||||||
|
case "camera": {
|
||||||
|
const d = directionOf(db, row); // entry | exit | both
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
case "access": {
|
||||||
|
const dirs = new Set(relaysOf(row).map((r) => r.direction));
|
||||||
|
if (dirs.size === 0) return null;
|
||||||
|
if (dirs.size > 1) return "mixed";
|
||||||
|
const only = [...dirs][0]; // entry | exit | both
|
||||||
|
return only ?? null;
|
||||||
|
}
|
||||||
|
case "printer": {
|
||||||
|
const role = (row.config as { role?: string }).role;
|
||||||
|
if (role === "booth-receipt") return "booth";
|
||||||
|
if (role === "entry-dispenser") return "lane";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class DeviceMonitor {
|
||||||
|
readonly #db: Db;
|
||||||
|
readonly #log: FastifyBaseLogger;
|
||||||
|
readonly #pollMs: number;
|
||||||
|
/** Latest unified status per device id. */
|
||||||
|
readonly #latest = new Map<string, DeviceStatusEvent>();
|
||||||
|
#timer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
#ticking = false;
|
||||||
|
|
||||||
|
/** Optional: the vision service client. When present + enabled, the monitor probes
|
||||||
|
* its /health each tick and shows it as a "vision" chip in the footer. */
|
||||||
|
readonly #vision: VisionClient | null;
|
||||||
|
|
||||||
|
constructor(db: Db, log: FastifyBaseLogger, pollMs = POLL_MS, vision: VisionClient | null = null) {
|
||||||
|
this.#db = db;
|
||||||
|
this.#log = log;
|
||||||
|
this.#pollMs = pollMs;
|
||||||
|
this.#vision = vision;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Begin polling. Idempotent. */
|
||||||
|
start(): void {
|
||||||
|
if (this.#timer) return;
|
||||||
|
void this.#tick(); // immediate first pass so the footer fills without a wait
|
||||||
|
this.#timer = setInterval(() => void this.#tick(), this.#pollMs);
|
||||||
|
this.#timer.unref?.();
|
||||||
|
this.#log.info(`device-monitor: polling every ${this.#pollMs}ms`);
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
if (this.#timer) {
|
||||||
|
clearInterval(this.#timer);
|
||||||
|
this.#timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Current snapshot for the API / a freshly-connected WS client. */
|
||||||
|
snapshot(): DeviceStatusEvent[] {
|
||||||
|
return [...this.#latest.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
async #tick(): Promise<void> {
|
||||||
|
if (this.#ticking) return; // never overlap polls
|
||||||
|
this.#ticking = true;
|
||||||
|
try {
|
||||||
|
// Re-read the device set each tick so a newly-assigned/removed device is
|
||||||
|
// picked up without a restart.
|
||||||
|
const rows = await this.#db.select().from(devices).all();
|
||||||
|
const enabled = rows.filter((r) => r.enabled);
|
||||||
|
const present = new Set(enabled.map((r) => r.id));
|
||||||
|
|
||||||
|
// The vision service is a pseudo-device — keep it in the present set when enabled
|
||||||
|
// so the cleanup below doesn't evict it.
|
||||||
|
if (this.#vision?.enabled) present.add(VISION_STATUS_ID);
|
||||||
|
|
||||||
|
// Drop devices that are gone/disabled (so the footer doesn't show stale ones).
|
||||||
|
for (const id of [...this.#latest.keys()]) {
|
||||||
|
if (!present.has(id)) this.#latest.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
await Promise.all([...enabled.map((r) => this.#poll(r)), this.#pollVision()]);
|
||||||
|
} catch (err) {
|
||||||
|
this.#log.warn(`device-monitor tick failed: ${(err as Error).message}`);
|
||||||
|
} finally {
|
||||||
|
this.#ticking = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async #poll(row: DeviceRow): Promise<void> {
|
||||||
|
const cfg = (row.config ?? {}) as Record<string, unknown>;
|
||||||
|
const base = {
|
||||||
|
deviceId: row.id,
|
||||||
|
driverId: row.driverId,
|
||||||
|
category: row.category,
|
||||||
|
roleKind: roleKindOf(this.#db, row),
|
||||||
|
};
|
||||||
|
|
||||||
|
let next: DeviceStatusEvent;
|
||||||
|
const driver = registry.get(row.driverId);
|
||||||
|
if (!driver) {
|
||||||
|
// Configured against a driver that's no longer registered — surface it,
|
||||||
|
// don't silently hide it.
|
||||||
|
next = { ...base, state: "offline", detail: "driver not registered", checkedAt: new Date().toISOString() };
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const device = driver.create(cfg as never);
|
||||||
|
// Printers expose richer paper/cover/cutter status; everything else uses
|
||||||
|
// the generic reachability probe. Both flatten to the same traffic-light.
|
||||||
|
if (isMonitorable(device)) {
|
||||||
|
const s = await device.readStatus();
|
||||||
|
next = { ...base, state: s.status, detail: s.detail, checkedAt: s.checkedAt };
|
||||||
|
} else {
|
||||||
|
const h = await device.healthCheck();
|
||||||
|
next = { ...base, state: h.status, detail: h.detail, checkedAt: new Date().toISOString() };
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// A probe that throws (build error, timeout) reads as offline — never crash
|
||||||
|
// the tick, and fail toward "there's a problem" rather than false-healthy.
|
||||||
|
next = { ...base, state: "offline", detail: (err as Error).message, checkedAt: new Date().toISOString() };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.#publish(row.id, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Probe the vision service /health and publish it as a "vision" footer chip. Skipped
|
||||||
|
* entirely when no client is wired or it's disabled (no chip then). */
|
||||||
|
async #pollVision(): Promise<void> {
|
||||||
|
if (!this.#vision?.enabled) return;
|
||||||
|
const h = await this.#vision.health();
|
||||||
|
const state: DeviceStatusEvent["state"] = h.ok && h.ready ? "ready" : h.ready ? "degraded" : "offline";
|
||||||
|
this.#publish(VISION_STATUS_ID, {
|
||||||
|
deviceId: VISION_STATUS_ID,
|
||||||
|
driverId: "vision",
|
||||||
|
category: "vision",
|
||||||
|
roleKind: null,
|
||||||
|
state,
|
||||||
|
detail: h.ready ? h.recognizer : (h.detail ?? "not ready"),
|
||||||
|
checkedAt: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cache + emit a status, but only when it CHANGED (state or detail). */
|
||||||
|
#publish(id: string, next: DeviceStatusEvent): void {
|
||||||
|
const prev = this.#latest.get(id);
|
||||||
|
this.#latest.set(id, next);
|
||||||
|
if (!prev || prev.state !== next.state || prev.detail !== next.detail) {
|
||||||
|
this.#log.info(
|
||||||
|
`device-monitor: ${next.category}/${next.roleKind ?? "—"} ${id} -> ${next.state}${next.detail ? ` (${next.detail})` : ""}`,
|
||||||
|
);
|
||||||
|
deviceEvents.emitDeviceStatus(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ export type Direction = "entry" | "exit" | "both";
|
|||||||
export type FlowDirection = "entry" | "exit";
|
export type FlowDirection = "entry" | "exit";
|
||||||
|
|
||||||
/** One relay on an access controller: which barrier it opens, in which direction,
|
/** One relay on an access controller: which barrier it opens, in which direction,
|
||||||
* and (optionally) the input terminal its entry button is wired to. */
|
* and (optionally) the input terminals its entry button + presence loop are wired to. */
|
||||||
export interface RelaySpec {
|
export interface RelaySpec {
|
||||||
/** 1-based relay channel on the board (the driver's pulseOpen(doorId)). */
|
/** 1-based relay channel on the board (the driver's pulseOpen(doorId)). */
|
||||||
readonly relay: number;
|
readonly relay: number;
|
||||||
@@ -19,6 +19,21 @@ export interface RelaySpec {
|
|||||||
/** 1-based input terminal of the entry button that fires this relay (transient
|
/** 1-based input terminal of the entry button that fires this relay (transient
|
||||||
* entry). Absent = no button at this barrier (subscriber/reader-driven only). */
|
* entry). Absent = no button at this barrier (subscriber/reader-driven only). */
|
||||||
readonly button?: number;
|
readonly button?: number;
|
||||||
|
/**
|
||||||
|
* Anti-double-press for the transient entry button (one car must yield ONE ticket).
|
||||||
|
* Two modes, chosen by what barrier feedback exists at this lane:
|
||||||
|
* - PRESENCE (preferred, when a vehicle loop is wired): `presenceInput` = the
|
||||||
|
* 1-based input terminal of an induction loop / barrier presence signal on THIS
|
||||||
|
* controller. A press prints only while a car is present, and no second ticket
|
||||||
|
* issues until the loop CLEARS (car drove in) and a new car re-occupies it. This
|
||||||
|
* makes one-car-one-ticket physical.
|
||||||
|
* - COOLDOWN (fallback, no feedback): `entryCooldownSec` suppresses repeat presses
|
||||||
|
* on this relay for N seconds after a ticket prints. A pure timer — mitigation,
|
||||||
|
* not a guarantee. Used when `presenceInput` is unset (or as a secondary guard).
|
||||||
|
* Both absent = no guard (legacy behaviour). See wiki/concepts/entry-double-press.md.
|
||||||
|
*/
|
||||||
|
readonly presenceInput?: number;
|
||||||
|
readonly entryCooldownSec?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Access controller config (the `relays[]` map + connection fields). */
|
/** Access controller config (the `relays[]` map + connection fields). */
|
||||||
@@ -38,11 +53,17 @@ interface BoundConfig {
|
|||||||
readonly [k: string]: unknown;
|
readonly [k: string]: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A resolved barrier: the controller row + the specific relay to pulse. */
|
/** A resolved barrier: the controller row + the specific relay to pulse. Carries the
|
||||||
|
* transient-entry anti-double-press config (presence loop / cooldown) when resolved
|
||||||
|
* from a button press, so the entry flow can enforce one-car-one-ticket. */
|
||||||
export interface ResolvedRelay {
|
export interface ResolvedRelay {
|
||||||
readonly controller: DeviceRow;
|
readonly controller: DeviceRow;
|
||||||
readonly relay: number;
|
readonly relay: number;
|
||||||
readonly direction: Direction;
|
readonly direction: Direction;
|
||||||
|
/** 1-based presence-loop input gating this relay's entry (when wired). */
|
||||||
|
readonly presenceInput?: number;
|
||||||
|
/** Cooldown seconds suppressing repeat presses (fallback when no presence loop). */
|
||||||
|
readonly entryCooldownSec?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** All enabled access controller rows. */
|
/** All enabled access controller rows. */
|
||||||
@@ -76,6 +97,31 @@ export function relayForButton(db: Db, controllerId: string, terminal: number):
|
|||||||
const spec = relaysOf(row).find((r) => r.button === terminal);
|
const spec = relaysOf(row).find((r) => r.button === terminal);
|
||||||
if (!spec) return null;
|
if (!spec) return null;
|
||||||
if (spec.direction !== "entry" && spec.direction !== "both") return null;
|
if (spec.direction !== "entry" && spec.direction !== "both") return null;
|
||||||
|
return {
|
||||||
|
controller: row,
|
||||||
|
relay: spec.relay,
|
||||||
|
direction: spec.direction,
|
||||||
|
presenceInput: spec.presenceInput,
|
||||||
|
entryCooldownSec: spec.entryCooldownSec,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a PRESENCE-LOOP input edge to the entry relay it gates: the controller with
|
||||||
|
* this deviceId, and the relay whose `presenceInput` terminal matches the fired input.
|
||||||
|
* Lets the entry flow track "a car is physically at this entry barrier" so it issues
|
||||||
|
* exactly one ticket per car. Only entry/both relays gate transient entry. Null otherwise.
|
||||||
|
*/
|
||||||
|
export function relayForPresence(db: Db, controllerId: string, terminal: number): ResolvedRelay | null {
|
||||||
|
const row = db
|
||||||
|
.select()
|
||||||
|
.from(devices)
|
||||||
|
.where(and(eq(devices.id, controllerId), eq(devices.category, "access")))
|
||||||
|
.get();
|
||||||
|
if (!row || !row.enabled) return null;
|
||||||
|
const spec = relaysOf(row).find((r) => r.presenceInput === terminal);
|
||||||
|
if (!spec) return null;
|
||||||
|
if (spec.direction !== "entry" && spec.direction !== "both") return null;
|
||||||
return { controller: row, relay: spec.relay, direction: spec.direction };
|
return { controller: row, relay: spec.relay, direction: spec.direction };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomInt, randomUUID } from "node:crypto";
|
||||||
import { sessions, type Db, type DeviceRow } from "@parking/db";
|
import { deviceEvents as deviceEventsTable, eq, sessions, siteConfig, type Db, type DeviceRow } from "@parking/db";
|
||||||
import {
|
import {
|
||||||
NoPrinterAvailableError,
|
NoPrinterAvailableError,
|
||||||
printWithFailover,
|
printWithFailover,
|
||||||
@@ -8,13 +8,16 @@ import {
|
|||||||
type PrinterDevice,
|
type PrinterDevice,
|
||||||
type PrinterInstance,
|
type PrinterInstance,
|
||||||
type TicketData,
|
type TicketData,
|
||||||
|
type TicketHeader,
|
||||||
} from "@parking/devices";
|
} from "@parking/devices";
|
||||||
|
import { DEFAULT_VEHICLE_CATEGORY, reasonPayload } from "@parking/shared";
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
import type { DeviceInputEvent } from "./device-events.js";
|
import type { DeviceInputEvent } from "./device-events.js";
|
||||||
import { getOccupancy } from "./occupancy.js";
|
import { getOccupancy } from "./occupancy.js";
|
||||||
import type { EventLog } from "./event-log.js";
|
import type { EventLog } from "./event-log.js";
|
||||||
import { devicesByDirection, relayForButton, type ResolvedRelay } from "./device-resolve.js";
|
import { devicesByDirection, relayForButton, relayForPresence, type ResolvedRelay } from "./device-resolve.js";
|
||||||
import { snapshotAsync } from "./snapshot.js";
|
import { snapshotAsync } from "./snapshot.js";
|
||||||
|
import type { VisionClient } from "./vision-client.js";
|
||||||
|
|
||||||
// The transient ENTRY flow: a button press → print a ticket → sign a vehicle_entry
|
// The transient ENTRY flow: a button press → print a ticket → sign a vehicle_entry
|
||||||
// → open the barrier. The button is wired into an access controller's input; the
|
// → open the barrier. The button is wired into an access controller's input; the
|
||||||
@@ -33,6 +36,31 @@ import { snapshotAsync } from "./snapshot.js";
|
|||||||
//
|
//
|
||||||
// Ordering: print → (ok) sign vehicle_entry → pulseOpen → snapshot → cache session.
|
// Ordering: print → (ok) sign vehicle_entry → pulseOpen → snapshot → cache session.
|
||||||
// (fail) sign anomaly, stop.
|
// (fail) sign anomaly, stop.
|
||||||
|
//
|
||||||
|
// ONE CAR = ONE TICKET (anti-double-press). The entry button can be physically held
|
||||||
|
// or mashed; without a guard each press mints a fresh ticket + signed vehicle_entry
|
||||||
|
// (corrupting occupancy and letting a transient shop the cheapest ticket at exit). The
|
||||||
|
// guard is per-relay and CONFIGURED on the relay spec (config.relays[]), chosen by what
|
||||||
|
// barrier feedback exists at the lane:
|
||||||
|
// - PRESENCE loop (preferred): `presenceInput` ties ticketing to a real vehicle. A
|
||||||
|
// press prints only while a car is present, and NO second ticket issues until the
|
||||||
|
// loop CLEARS (car drove in) and a new car re-occupies it. We observe the loop's
|
||||||
|
// input edges to track presence + "armed" per relay.
|
||||||
|
// - COOLDOWN (fallback, no feedback): `entryCooldownSec` suppresses repeat presses on
|
||||||
|
// the relay for N seconds after a ticket. A timer — mitigation, not a guarantee.
|
||||||
|
// A suppressed press is recorded as UNSIGNED telemetry (a no-op, not a fraud anomaly).
|
||||||
|
// See wiki/concepts/entry-double-press.md.
|
||||||
|
|
||||||
|
/** Per-relay anti-double-press state, keyed `controllerId:relay`. */
|
||||||
|
interface RelayGuardState {
|
||||||
|
/** Last successful ticket time (ms epoch) — drives the cooldown check. */
|
||||||
|
lastTicketAt: number;
|
||||||
|
/** PRESENCE mode: is a vehicle currently on the loop? (from loop input edges) */
|
||||||
|
present: boolean;
|
||||||
|
/** PRESENCE mode: ready to issue a ticket for a NEW car. Set false after a ticket
|
||||||
|
* prints; re-armed when the loop CLEARS (the car drove through). */
|
||||||
|
armed: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export class EntryFlow {
|
export class EntryFlow {
|
||||||
readonly #db: Db;
|
readonly #db: Db;
|
||||||
@@ -40,17 +68,32 @@ export class EntryFlow {
|
|||||||
readonly #logger: FastifyBaseLogger;
|
readonly #logger: FastifyBaseLogger;
|
||||||
/** Guard against double-fire from the same physical press (on edge only). */
|
/** Guard against double-fire from the same physical press (on edge only). */
|
||||||
readonly #inFlight = new Set<string>();
|
readonly #inFlight = new Set<string>();
|
||||||
|
/** Per-relay one-car-one-ticket state (presence + cooldown), keyed controllerId:relay. */
|
||||||
|
readonly #guard = new Map<string, RelayGuardState>();
|
||||||
|
/** Optional vision client — passed to snapshotAsync so ANPR runs on the entry image. */
|
||||||
|
readonly #vision: VisionClient | null;
|
||||||
|
|
||||||
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger) {
|
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger, vision: VisionClient | null = null) {
|
||||||
this.#db = db;
|
this.#db = db;
|
||||||
this.#log = log;
|
this.#log = log;
|
||||||
this.#logger = logger;
|
this.#logger = logger;
|
||||||
|
this.#vision = vision;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Handle a device input edge. Acts only on the rising ("on") edge of an entry
|
/** Handle a device input edge. Two kinds of edge matter to this flow:
|
||||||
* button — an input terminal mapped to an entry relay on its controller. */
|
* (1) an ENTRY BUTTON press (rising edge) → run entry, subject to the per-relay
|
||||||
|
* anti-double-press guard; (2) a PRESENCE LOOP edge (either direction) → update
|
||||||
|
* presence state so the guard knows when a car arrives/leaves. The same physical
|
||||||
|
* input is never both, so we resolve each independently. */
|
||||||
async onInput(e: DeviceInputEvent): Promise<void> {
|
async onInput(e: DeviceInputEvent): Promise<void> {
|
||||||
if (e.edge !== "on") return; // release edge is just telemetry
|
// Presence-loop edge (both directions matter): keep the per-relay state current.
|
||||||
|
const presence = relayForPresence(this.#db, e.deviceId, e.input);
|
||||||
|
if (presence) {
|
||||||
|
this.#onPresenceEdge(presence, e.edge);
|
||||||
|
return; // a loop input is not a button — nothing else to do
|
||||||
|
}
|
||||||
|
|
||||||
|
if (e.edge !== "on") return; // for buttons, the release edge is just telemetry
|
||||||
|
|
||||||
// The firing device must be an access controller, and the pressed input terminal
|
// The firing device must be an access controller, and the pressed input terminal
|
||||||
// must map to an ENTRY (or both) relay — that's an entry button. Anything else
|
// must map to an ENTRY (or both) relay — that's an entry button. Anything else
|
||||||
@@ -58,6 +101,14 @@ export class EntryFlow {
|
|||||||
const resolved = relayForButton(this.#db, e.deviceId, e.input);
|
const resolved = relayForButton(this.#db, e.deviceId, e.input);
|
||||||
if (!resolved) return;
|
if (!resolved) return;
|
||||||
|
|
||||||
|
// ANTI-DOUBLE-PRESS: is this press allowed to issue a ticket? (presence/cooldown)
|
||||||
|
const suppressed = this.#suppressReason(resolved);
|
||||||
|
if (suppressed) {
|
||||||
|
this.#recordSuppressedPress(e, resolved, suppressed);
|
||||||
|
this.#logger.info(`entry press suppressed (${this.#relayKey(resolved)}): ${suppressed}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const key = `${e.deviceId}:${e.input}`;
|
const key = `${e.deviceId}:${e.input}`;
|
||||||
if (this.#inFlight.has(key)) return; // ignore re-fire while one is processing
|
if (this.#inFlight.has(key)) return; // ignore re-fire while one is processing
|
||||||
this.#inFlight.add(key);
|
this.#inFlight.add(key);
|
||||||
@@ -70,18 +121,110 @@ export class EntryFlow {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Stable per-relay key for the guard map. */
|
||||||
|
#relayKey(r: ResolvedRelay): string {
|
||||||
|
return `${r.controller.id}:${r.relay}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lazily get (or create) the guard state for a relay. New relays start ARMED and
|
||||||
|
* with no car present, so the first press on a fresh lane works immediately. */
|
||||||
|
#guardState(r: ResolvedRelay): RelayGuardState {
|
||||||
|
const key = this.#relayKey(r);
|
||||||
|
let s = this.#guard.get(key);
|
||||||
|
if (!s) {
|
||||||
|
s = { lastTicketAt: 0, present: false, armed: true };
|
||||||
|
this.#guard.set(key, s);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Apply a presence-loop edge to a relay's state. The car ARRIVING re-arms ticketing;
|
||||||
|
* the car LEAVING the loop (after its entry) re-arms for the NEXT car. */
|
||||||
|
#onPresenceEdge(r: ResolvedRelay, edge: "on" | "off"): void {
|
||||||
|
const s = this.#guardState(r);
|
||||||
|
if (edge === "on") {
|
||||||
|
s.present = true; // a vehicle is at the barrier
|
||||||
|
} else {
|
||||||
|
// Loop cleared: the car drove through (or backed off). Re-arm for the next car —
|
||||||
|
// this is the gate that makes a *new* car necessary before another ticket.
|
||||||
|
s.present = false;
|
||||||
|
s.armed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Why a press should be SUPPRESSED (no ticket), or null if it may proceed.
|
||||||
|
* PRESENCE mode is authoritative when a loop is wired; otherwise COOLDOWN; else no
|
||||||
|
* guard (legacy). The two can coexist — presence first, cooldown as a backstop. */
|
||||||
|
#suppressReason(r: ResolvedRelay): string | null {
|
||||||
|
const s = this.#guardState(r);
|
||||||
|
|
||||||
|
if (typeof r.presenceInput === "number") {
|
||||||
|
// Physical one-car-one-ticket: a car must be present AND we must be armed (no
|
||||||
|
// ticket already issued for this still-present car).
|
||||||
|
if (!s.present) return "no vehicle at the barrier (presence loop clear)";
|
||||||
|
if (!s.armed) return "ticket already issued for the car at the barrier";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof r.entryCooldownSec === "number" && r.entryCooldownSec > 0) {
|
||||||
|
const elapsed = Date.now() - s.lastTicketAt;
|
||||||
|
if (elapsed < r.entryCooldownSec * 1000) {
|
||||||
|
const remain = Math.ceil((r.entryCooldownSec * 1000 - elapsed) / 1000);
|
||||||
|
return `within ${r.entryCooldownSec}s entry cooldown (${remain}s left)`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Record a suppressed (repeat/no-car) entry press as UNSIGNED telemetry — a no-op,
|
||||||
|
* not a fraud anomaly, so the signed ledger stays clean (the operator's choice). */
|
||||||
|
#recordSuppressedPress(e: DeviceInputEvent, r: ResolvedRelay, reason: string): void {
|
||||||
|
try {
|
||||||
|
this.#db
|
||||||
|
.insert(deviceEventsTable)
|
||||||
|
.values({
|
||||||
|
id: randomUUID(),
|
||||||
|
deviceId: e.deviceId,
|
||||||
|
category: "access",
|
||||||
|
kind: "input",
|
||||||
|
detail: {
|
||||||
|
driverId: e.driverId,
|
||||||
|
input: e.input,
|
||||||
|
edge: e.edge,
|
||||||
|
entrySuppressed: true,
|
||||||
|
relay: r.relay,
|
||||||
|
reason,
|
||||||
|
},
|
||||||
|
occurredAt: e.at,
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.error(`suppressed-press telemetry insert failed: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async #runEntry(resolved: ResolvedRelay): Promise<void> {
|
async #runEntry(resolved: ResolvedRelay): Promise<void> {
|
||||||
// CAPACITY GATE (transient only). When the lot is full, refuse transient entry:
|
// CAPACITY GATE (transient only). When the lot is full, refuse transient entry:
|
||||||
// no ticket, no vehicle_entry, no open — sign an anomaly. Permit holders are NOT
|
// no ticket, no vehicle_entry, no open — sign an anomaly. Subscribers are NOT
|
||||||
// gated here (their flow ignores site-full; their own maxConcurrent applies), so
|
// gated here (their flow ignores site-full; their own maxConcurrent applies), so
|
||||||
// subscribers aren't locked out. "Full" is a soft policy seam for valet over-
|
// they aren't locked out. "Full" is a soft policy seam for valet over-
|
||||||
// capacity later. See wiki/concepts/capacity-occupancy.md.
|
// capacity later. See wiki/concepts/capacity-occupancy.md.
|
||||||
const occ = getOccupancy(this.#db);
|
const occ = getOccupancy(this.#db);
|
||||||
if (occ.full) {
|
if (occ.full) {
|
||||||
|
// No ticket id exists for a refused entry, so mint a synthetic ref to key the
|
||||||
|
// anomaly + its evidence snapshot together. The operator wants the photo of WHO
|
||||||
|
// was turned away (a fraud/dispute signal), so we still fire the entry camera.
|
||||||
|
const refusedRef = `REFUSED-${randomUUID().replace(/-/g, "").slice(0, 12)}`;
|
||||||
await this.#log.append({
|
await this.#log.append({
|
||||||
type: "anomaly",
|
type: "anomaly",
|
||||||
payload: { reason: `transient entry refused — lot full (${occ.count}/${occ.capacity})`, entryRefused: true, full: true },
|
identity: refusedRef,
|
||||||
|
payload: {
|
||||||
|
...reasonPayload("entry.refused.full", { count: occ.count, capacity: occ.capacity ?? 0 }),
|
||||||
|
entryRefused: true,
|
||||||
|
full: true,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
this.#fireSnapshot("entry", refusedRef);
|
||||||
this.#logger.warn(`transient entry REFUSED: full (${occ.count}/${occ.capacity})`);
|
this.#logger.warn(`transient entry REFUSED: full (${occ.count}/${occ.capacity})`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -91,12 +234,19 @@ export class EntryFlow {
|
|||||||
const printers = this.#loadPrinters();
|
const printers = this.#loadPrinters();
|
||||||
|
|
||||||
// 1. PRINT FIRST. The ticket is the transient's session key — no ticket, no entry.
|
// 1. PRINT FIRST. The ticket is the transient's session key — no ticket, no entry.
|
||||||
const ticket: TicketData = { ticketId, issuedAt };
|
const ticket: TicketData = { ticketId, issuedAt, header: this.#ticketHeader() };
|
||||||
try {
|
try {
|
||||||
const printedBy = await printWithFailover(printers, "entry-dispenser", (d: PrinterDevice) =>
|
const printedBy = await printWithFailover(printers, "entry-dispenser", (d: PrinterDevice) =>
|
||||||
d.printTicket(ticket),
|
d.printTicket(ticket),
|
||||||
);
|
);
|
||||||
this.#logger.info(`entry ticket ${ticketId} printed on ${printedBy}`);
|
this.#logger.info(`entry ticket ${ticketId} printed on ${printedBy}`);
|
||||||
|
// ONE CAR = ONE TICKET: a ticket is now out for the car at this barrier. Disarm +
|
||||||
|
// stamp the cooldown so a repeat press (held button / mashing) issues no second
|
||||||
|
// ticket. PRESENCE mode re-arms when the loop clears (car drove in); COOLDOWN mode
|
||||||
|
// re-allows after entryCooldownSec. Done on the print success, NOT the open.
|
||||||
|
const guard = this.#guardState(resolved);
|
||||||
|
guard.lastTicketAt = Date.now();
|
||||||
|
guard.armed = false;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// HOLD: do not open, do not record a vehicle_entry. Sign an anomaly so the
|
// HOLD: do not open, do not record a vehicle_entry. Sign an anomaly so the
|
||||||
// failed attempt is in the tamper-evident record for the operator.
|
// failed attempt is in the tamper-evident record for the operator.
|
||||||
@@ -105,19 +255,33 @@ export class EntryFlow {
|
|||||||
await this.#log.append({
|
await this.#log.append({
|
||||||
type: "anomaly",
|
type: "anomaly",
|
||||||
identity: ticketId,
|
identity: ticketId,
|
||||||
payload: { reason: `entry held — ticket not printed: ${reason}`, ticketPrinted: false },
|
payload: { ...reasonPayload("entry.held.noTicket", { detail: reason }), ticketPrinted: false },
|
||||||
});
|
});
|
||||||
|
// Capture who is held at the barrier (evidence for the operator handling the car).
|
||||||
|
this.#fireSnapshot("entry", ticketId);
|
||||||
this.#logger.warn(`entry HELD: ${reason} (barrier NOT opened)`);
|
this.#logger.warn(`entry HELD: ${reason} (barrier NOT opened)`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. SIGN the vehicle_entry — BEFORE the relay fires (the core invariant).
|
// 2. SIGN the vehicle_entry — BEFORE the relay fires (the core invariant).
|
||||||
|
// `category` is FROZEN here (in the signed payload) so the tariff prices and
|
||||||
|
// later reprices the same way at exit. Today every transient takes the SITE
|
||||||
|
// default category (operator policy, site_config.default_vehicle_category;
|
||||||
|
// falls back to the shared DEFAULT_VEHICLE_CATEGORY). Per-relay capture (a
|
||||||
|
// "bus lane" relay, mirroring how direction is per-relay in device-resolve.ts)
|
||||||
|
// is the future seam — source it from `resolved` then. A V1/no-category tariff
|
||||||
|
// ignores it; only V2 category cards consult it.
|
||||||
|
const cfg = this.#db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||||
|
const category =
|
||||||
|
cfg?.defaultVehicleCategory && cfg.defaultVehicleCategory.length > 0
|
||||||
|
? cfg.defaultVehicleCategory
|
||||||
|
: DEFAULT_VEHICLE_CATEGORY;
|
||||||
await this.#log.append({
|
await this.#log.append({
|
||||||
type: "vehicle_entry",
|
type: "vehicle_entry",
|
||||||
direction: "entry",
|
direction: "entry",
|
||||||
source: "ticket",
|
source: "ticket",
|
||||||
identity: ticketId,
|
identity: ticketId,
|
||||||
payload: { sessionRef: ticketId, ticketPrinted: true },
|
payload: { sessionRef: ticketId, ticketPrinted: true, category },
|
||||||
occurredAt: issuedAt,
|
occurredAt: issuedAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -128,12 +292,7 @@ export class EntryFlow {
|
|||||||
|
|
||||||
// 3b. SNAPSHOT — fire the entry camera(s), never awaited (evidence, not a gate;
|
// 3b. SNAPSHOT — fire the entry camera(s), never awaited (evidence, not a gate;
|
||||||
// a camera failure must not delay or block the already-open barrier).
|
// a camera failure must not delay or block the already-open barrier).
|
||||||
void snapshotAsync({
|
this.#fireSnapshot("entry", ticketId);
|
||||||
db: this.#db,
|
|
||||||
direction: "entry",
|
|
||||||
identity: ticketId,
|
|
||||||
logger: this.#logger,
|
|
||||||
}).catch((err) => this.#logger.error(`entry snapshot error: ${(err as Error).message}`));
|
|
||||||
|
|
||||||
// 4. Update the session projection cache (rebuildable from the ledger; this is
|
// 4. Update the session projection cache (rebuildable from the ledger; this is
|
||||||
// just a fast read-model, never the source of truth).
|
// just a fast read-model, never the source of truth).
|
||||||
@@ -149,6 +308,15 @@ export class EntryFlow {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fire the entry camera(s) for an identity; never awaited (evidence, not a gate).
|
||||||
|
* Used on both the OPEN path and the refused/held anomaly paths — a turned-away or
|
||||||
|
* held car is exactly when the operator wants the photo. */
|
||||||
|
#fireSnapshot(direction: "entry", identity: string): void {
|
||||||
|
void snapshotAsync({ db: this.#db, direction, identity, logger: this.#logger, vision: this.#vision }).catch(
|
||||||
|
(err) => this.#logger.error(`entry snapshot error: ${(err as Error).message}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** Build a live access adapter from a resolved controller row, or null. */
|
/** Build a live access adapter from a resolved controller row, or null. */
|
||||||
#buildAccess(row: DeviceRow): AccessControlDevice | null {
|
#buildAccess(row: DeviceRow): AccessControlDevice | null {
|
||||||
const driver = registry.get(row.driverId);
|
const driver = registry.get(row.driverId);
|
||||||
@@ -182,9 +350,77 @@ export class EntryFlow {
|
|||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Park identity for the ticket header, from site_config (all fields optional;
|
||||||
|
* the driver prints only what's set). See wiki/concepts/site-metadata.md. */
|
||||||
|
#ticketHeader(): TicketHeader | undefined {
|
||||||
|
const row = this.#db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||||
|
if (!row) return undefined;
|
||||||
|
return {
|
||||||
|
parkName: row.parkName,
|
||||||
|
operatorName: row.operatorName,
|
||||||
|
nius: row.nius,
|
||||||
|
address: row.address,
|
||||||
|
phone: row.phone,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Opaque, unguessable transient ticket id (wiki/concepts/ticket-encoding.md). */
|
/**
|
||||||
|
* Opaque, unguessable transient ticket id (wiki/concepts/ticket-encoding.md).
|
||||||
|
*
|
||||||
|
* Format: 11 digits = 10 cryptographically-random digits + 1 trailing Luhn check
|
||||||
|
* digit. All-numeric so the booth can read it on ANY legacy 1D barcode scanner and
|
||||||
|
* an operator can hand-key it if every reader is down. RANDOM (not sequential): the
|
||||||
|
* id must stay unguessable so an attacker can't iterate to claim a cheaper session
|
||||||
|
* — the anti-fraud property the wiki settles.
|
||||||
|
*
|
||||||
|
* Length is driven by GUESS-RESISTANCE, not volume: with 10^10 valid ids and the
|
||||||
|
* Luhn digit rejecting 9/10 of malformed guesses, a blind attempt at a currently-OPEN
|
||||||
|
* ticket lands at ~1-in-10^7 even with thousands parked — comfortably safe — while
|
||||||
|
* being two digits (≈2 barcode modules) narrower than the old 13. Collisions are
|
||||||
|
* negligible at lot scale; the unique constraints on ledger_events.index / sessions.id
|
||||||
|
* are the backstop. (Older 13-digit ids stay valid — the id is opaque, length-agnostic.)
|
||||||
|
* The Luhn digit lets a manual entry reject a typo (validateTicketCode) instead of
|
||||||
|
* failing as "session not found".
|
||||||
|
*/
|
||||||
function newTicketId(): string {
|
function newTicketId(): string {
|
||||||
return `T-${randomUUID()}`;
|
let body = "";
|
||||||
|
for (let i = 0; i < 10; i += 1) body += String(randomInt(10));
|
||||||
|
return body + luhnCheckDigit(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The Luhn (mod-10) check digit for an all-digit string. */
|
||||||
|
function luhnCheckDigit(digits: string): string {
|
||||||
|
let sum = 0;
|
||||||
|
// Walk right-to-left; the check digit sits at position 0 from the right, so the
|
||||||
|
// last body digit is an "even" position that gets doubled.
|
||||||
|
let double = true;
|
||||||
|
for (let i = digits.length - 1; i >= 0; i -= 1) {
|
||||||
|
let d = digits.charCodeAt(i) - 48;
|
||||||
|
if (double) {
|
||||||
|
d *= 2;
|
||||||
|
if (d > 9) d -= 9;
|
||||||
|
}
|
||||||
|
sum += d;
|
||||||
|
double = !double;
|
||||||
|
}
|
||||||
|
return String((10 - (sum % 10)) % 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True if `code` is a well-formed ticket code: all digits and a valid Luhn checksum.
|
||||||
|
* Lets a manual-entry path (operator types the code off the ticket when readers are
|
||||||
|
* down) reject a typo up front. A scanned/looked-up id that predates this format
|
||||||
|
* (e.g. legacy `T-<uuid>`) won't pass — callers should only gate MANUAL entry on it,
|
||||||
|
* never reject an id that already exists in the ledger. See ticket-encoding.md.
|
||||||
|
*/
|
||||||
|
export function validateTicketCode(code: string): boolean {
|
||||||
|
// Length-agnostic: an all-digit code whose last digit is the Luhn check of the rest.
|
||||||
|
// Accepts the current 11-digit ids AND any legacy 13-digit ones still in circulation
|
||||||
|
// (the id is opaque; only the digits+checksum shape matters). The 10..14 bound keeps
|
||||||
|
// a stray short/long string from being mistaken for a ticket. See ticket-encoding.md.
|
||||||
|
if (!/^\d{10,14}$/.test(code)) return false;
|
||||||
|
const body = code.slice(0, -1);
|
||||||
|
return luhnCheckDigit(body) === code[code.length - 1];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { eq, subscriptions, type Db } from "@parking/db";
|
||||||
|
import type { LedgerEvent } from "@parking/shared";
|
||||||
|
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
|
||||||
|
|
||||||
|
// READ-TIME event enrichment. The signed ledger stays minimal and stable; some fields
|
||||||
|
// are nice to SHOW but must not be signed (they can change, or depend on other tables).
|
||||||
|
// We resolve them when serializing an event for the API / WS feed — never on the
|
||||||
|
// signed record itself.
|
||||||
|
//
|
||||||
|
// Today: a subscription occurrence's identity is an opaque `SUBSESS-…` key. The human
|
||||||
|
// who matters is the subscription HOLDER, whose name lives on the subscriptions row
|
||||||
|
// (mutable master data — NOT signed into the event). We resolve payload.permitId →
|
||||||
|
// holder_name so the feed reads "Aqif Kopertoni" rather than "SUBSESS-08cd1c52e219".
|
||||||
|
|
||||||
|
/** Fallback label when a subscription has no holder name (or was deleted). Matches the
|
||||||
|
* i18n key `booth.subscriberFallback`; kept here in English for the API/log layer. */
|
||||||
|
const SUBSCRIBER_FALLBACK = "Subscriber";
|
||||||
|
|
||||||
|
/** Tiny holder-name cache. Single-writer SQLite; a subscription rename is rare and the
|
||||||
|
* feed is not security-sensitive, so a short-lived cache is plenty. Invalidate by
|
||||||
|
* process lifetime — restart picks up renames; for live correctness the lookup is
|
||||||
|
* cheap enough that we just read per miss. */
|
||||||
|
const holderCache = new Map<string, string | null>();
|
||||||
|
|
||||||
|
/** Resolve a subscription id to its holder name (or null), memoized. */
|
||||||
|
function holderName(db: Db, permitId: string): string | null {
|
||||||
|
if (holderCache.has(permitId)) return holderCache.get(permitId) ?? null;
|
||||||
|
const row = db
|
||||||
|
.select({ holderName: subscriptions.holderName })
|
||||||
|
.from(subscriptions)
|
||||||
|
.where(eq(subscriptions.id, permitId))
|
||||||
|
.get();
|
||||||
|
const name = row?.holderName?.trim() || null;
|
||||||
|
holderCache.set(permitId, name);
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop a cached holder name (call after a subscription create/update/delete). */
|
||||||
|
export function invalidateHolder(permitId: string): void {
|
||||||
|
holderCache.delete(permitId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clear the whole holder cache (call on bulk subscription changes). */
|
||||||
|
export function clearHolderCache(): void {
|
||||||
|
holderCache.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attach read-time display fields to a raw ledger row before it goes to a client:
|
||||||
|
* - `subscriberLabel` for a subscription occurrence (payload.permitId → holder name);
|
||||||
|
* - `plate` for an entry/exit event whose session has an advisory ANPR read.
|
||||||
|
* Idempotent and cheap; events without either pass through unchanged. Used by the WS
|
||||||
|
* feed (per event). For the bulk feed page prefer `enrichEvents` (one plate scan).
|
||||||
|
*/
|
||||||
|
export function enrichEvent<T extends LedgerEvent>(db: Db, event: T): T {
|
||||||
|
let out: T = event;
|
||||||
|
const permitId = event.payload && typeof event.payload.permitId === "string" ? event.payload.permitId : null;
|
||||||
|
if (permitId) out = { ...out, subscriberLabel: holderName(db, permitId) ?? SUBSCRIBER_FALLBACK };
|
||||||
|
if ((event.type === "vehicle_entry" || event.type === "vehicle_exit") && event.identity) {
|
||||||
|
const p = plateForIdentity(db, event.identity);
|
||||||
|
if (p) out = { ...out, plate: p.plate };
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bulk variant for the feed page: enriches a list of events with subscriber labels AND
|
||||||
|
* plates using a SINGLE device_events scan for all the plates (instead of one per row).
|
||||||
|
* Order preserved.
|
||||||
|
*/
|
||||||
|
export function enrichEvents<T extends LedgerEvent>(db: Db, events: T[]): T[] {
|
||||||
|
// Collect identities of entry/exit events to resolve their plates in one scan.
|
||||||
|
const wanted = new Set<string>();
|
||||||
|
for (const e of events) {
|
||||||
|
if ((e.type === "vehicle_entry" || e.type === "vehicle_exit") && e.identity) wanted.add(e.identity);
|
||||||
|
}
|
||||||
|
const plates = wanted.size ? platesForIdentities(db, wanted) : new Map();
|
||||||
|
return events.map((e) => {
|
||||||
|
let out: T = e;
|
||||||
|
const permitId = e.payload && typeof e.payload.permitId === "string" ? e.payload.permitId : null;
|
||||||
|
if (permitId) out = { ...out, subscriberLabel: holderName(db, permitId) ?? SUBSCRIBER_FALLBACK };
|
||||||
|
if ((e.type === "vehicle_entry" || e.type === "vehicle_exit") && e.identity) {
|
||||||
|
const p = plates.get(e.identity);
|
||||||
|
if (p) out = { ...out, plate: p.plate };
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -81,15 +81,34 @@ export function hashEvent(canonical: string): string {
|
|||||||
return createHash("sha256").update(canonical, "utf8").digest("hex");
|
return createHash("sha256").update(canonical, "utf8").digest("hex");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Resolve a verifier for an event's stored `keyId` (see signer.buildVerifier).
|
||||||
|
* Returns undefined when the key that signed an event is not available. */
|
||||||
|
export type SignerResolver = (keyId: string) => Signer | undefined;
|
||||||
|
|
||||||
export class EventLog {
|
export class EventLog {
|
||||||
readonly #db: Db;
|
readonly #db: Db;
|
||||||
readonly #signer: Signer;
|
readonly #signer: Signer;
|
||||||
|
/** Picks the verifying signer per event keyId; lets a chain span key rotations
|
||||||
|
* (JWT-fallback → dedicated key → ATECC608). Defaults to the append signer for
|
||||||
|
* callers that don't pass one (single-key chains, tests). */
|
||||||
|
readonly #resolveVerifier: SignerResolver;
|
||||||
|
/** Optional read-side notification, fired AFTER a row is durably inserted. Used
|
||||||
|
* to fan the event out to live booth clients (WS). It is best-effort and must
|
||||||
|
* NOT influence the append/sign/chain path — a throwing/absent sink is ignored. */
|
||||||
|
readonly #onAppended?: (row: LedgerEventRow) => void;
|
||||||
/** Serialize appends: each waits for the previous to finish. */
|
/** Serialize appends: each waits for the previous to finish. */
|
||||||
#tail: Promise<unknown> = Promise.resolve();
|
#tail: Promise<unknown> = Promise.resolve();
|
||||||
|
|
||||||
constructor(db: Db, signer: Signer) {
|
constructor(
|
||||||
|
db: Db,
|
||||||
|
signer: Signer,
|
||||||
|
resolveVerifier?: SignerResolver,
|
||||||
|
onAppended?: (row: LedgerEventRow) => void,
|
||||||
|
) {
|
||||||
this.#db = db;
|
this.#db = db;
|
||||||
this.#signer = signer;
|
this.#signer = signer;
|
||||||
|
this.#resolveVerifier = resolveVerifier ?? (() => signer);
|
||||||
|
this.#onAppended = onAppended;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Append one event to the chain. Returns the persisted row. Serialized. */
|
/** Append one event to the chain. Returns the persisted row. Serialized. */
|
||||||
@@ -97,7 +116,16 @@ export class EventLog {
|
|||||||
const run = this.#tail.then(() => this.#appendNow(input));
|
const run = this.#tail.then(() => this.#appendNow(input));
|
||||||
// Keep the chain going even if one append rejects (don't wedge the lock).
|
// Keep the chain going even if one append rejects (don't wedge the lock).
|
||||||
this.#tail = run.catch(() => undefined);
|
this.#tail = run.catch(() => undefined);
|
||||||
return run;
|
// Read-side notification, AFTER the row is durably written. Wrapped so a
|
||||||
|
// failing sink can never reject the append or break the chain lock above.
|
||||||
|
return run.then((row) => {
|
||||||
|
try {
|
||||||
|
this.#onAppended?.(row);
|
||||||
|
} catch {
|
||||||
|
// best-effort fan-out only — swallow.
|
||||||
|
}
|
||||||
|
return row;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#appendNow(input: AppendInput): LedgerEventRow {
|
#appendNow(input: AppendInput): LedgerEventRow {
|
||||||
@@ -146,7 +174,13 @@ export class EventLog {
|
|||||||
* Walk the chain oldest→newest and recompute hashes + signatures. Returns the
|
* Walk the chain oldest→newest and recompute hashes + signatures. Returns the
|
||||||
* first detected break, or { ok: true }. This is what reconciliation and an
|
* first detected break, or { ok: true }. This is what reconciliation and an
|
||||||
* integrity self-check call. Catches: tampered content, reordering, a deleted
|
* integrity self-check call. Catches: tampered content, reordering, a deleted
|
||||||
* row (index gap), and a forged/invalid signature.
|
* row (index gap), a forged/invalid signature, and an event signed under a key
|
||||||
|
* that is no longer configured.
|
||||||
|
*
|
||||||
|
* Each row is verified against the signer for ITS OWN `keyId`, not the current
|
||||||
|
* append signer — so a chain that spans a key rotation (e.g. early events under
|
||||||
|
* the JWT_SECRET fallback, later ones under a dedicated EVENT_SIGNING_KEY) still
|
||||||
|
* verifies end to end. See signer.buildVerifier.
|
||||||
*/
|
*/
|
||||||
verifyChain(): { ok: true } | { ok: false; index: number; reason: string } {
|
verifyChain(): { ok: true } | { ok: false; index: number; reason: string } {
|
||||||
const rows = this.#db.select().from(ledgerEvents).orderBy(ledgerEvents.index).all();
|
const rows = this.#db.select().from(ledgerEvents).orderBy(ledgerEvents.index).all();
|
||||||
@@ -159,8 +193,16 @@ export class EventLog {
|
|||||||
if ((row.prevHash ?? null) !== prevHash) {
|
if ((row.prevHash ?? null) !== prevHash) {
|
||||||
return { ok: false, index: row.index, reason: "prevHash does not match chain" };
|
return { ok: false, index: row.index, reason: "prevHash does not match chain" };
|
||||||
}
|
}
|
||||||
|
const verifier = this.#resolveVerifier(row.keyId);
|
||||||
|
if (!verifier) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
index: row.index,
|
||||||
|
reason: `no signer for keyId "${row.keyId}" (key not configured)`,
|
||||||
|
};
|
||||||
|
}
|
||||||
const canonical = canonicalize(row);
|
const canonical = canonicalize(row);
|
||||||
if (!this.#signer.verify(canonical, row.signature)) {
|
if (!verifier.verify(canonical, row.signature)) {
|
||||||
return { ok: false, index: row.index, reason: "signature invalid (content tampered or wrong key)" };
|
return { ok: false, index: row.index, reason: "signature invalid (content tampered or wrong key)" };
|
||||||
}
|
}
|
||||||
prevHash = hashEvent(canonical);
|
prevHash = hashEvent(canonical);
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { eq, ledgerEvents, sessions, type Db, type DeviceRow } from "@parking/db";
|
import { desc, eq, ledgerEvents, sessions, tariffVersions, tariffs, type Db, type DeviceRow } from "@parking/db";
|
||||||
import { registry, type AccessControlDevice } from "@parking/devices";
|
import { registry, type AccessControlDevice } from "@parking/devices";
|
||||||
import type { ResolvedRelay } from "./device-resolve.js";
|
import { firstRelayByDirection, type ResolvedRelay } from "./device-resolve.js";
|
||||||
import { snapshotAsync } from "./snapshot.js";
|
import { snapshotAsync } from "./snapshot.js";
|
||||||
import type { LedgerPayload } from "@parking/shared";
|
import type { VisionClient } from "./vision-client.js";
|
||||||
|
import { computeFee, reasonPayload, renderReasonEn, type LedgerPayload, type TariffStructure } from "@parking/shared";
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
||||||
import type { EventLog } from "./event-log.js";
|
import type { EventLog } from "./event-log.js";
|
||||||
@@ -30,23 +31,240 @@ interface SessionView {
|
|||||||
readonly enteredAt: string;
|
readonly enteredAt: string;
|
||||||
readonly open: boolean; // no vehicle_exit yet
|
readonly open: boolean; // no vehicle_exit yet
|
||||||
readonly paidAt: string | null; // latest payment time, if any
|
readonly paidAt: string | null; // latest payment time, if any
|
||||||
|
/** A SUBSCRIPTION occurrence (prepaid; entry payload permit:true). Authorized to
|
||||||
|
* exit / re-open without a `payment`. */
|
||||||
|
readonly subscription: boolean;
|
||||||
readonly graceExitMin: number | null; // from the payment's tariff context, if known
|
readonly graceExitMin: number | null; // from the payment's tariff context, if known
|
||||||
|
// Within the FREE entry-grace window (a quick in-and-out that the tariff prices at
|
||||||
|
// 0). When true the exit opens without a pay-station visit — we mint a $0 payment so
|
||||||
|
// the ledger's "an exit is covered by a payment" invariant still holds. Null when no
|
||||||
|
// active tariff resolves (then we fall back to the normal paid check).
|
||||||
|
readonly freeGrace: { tariffVersionId: string; currency: string; graceExitMin: number } | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Result of a booth-driven exit (POST /api/exit). `ok=false` = validation rejected
|
||||||
|
* (nothing signed beyond an anomaly). `ok=true, opened=false` = exit IS signed but
|
||||||
|
* the barrier didn't open (payment stands; operator opens manually). */
|
||||||
|
export type BoothExitResult =
|
||||||
|
| { ok: false; status: "invalid" | "no_session" | "closed" | "unpaid" | "grace_expired"; reason: string }
|
||||||
|
| { ok: true; opened: true }
|
||||||
|
| { ok: true; opened: false; reason: string };
|
||||||
|
|
||||||
|
/** Result of a human-intervention barrier re-open (POST /api/barrier/reopen).
|
||||||
|
* `ok=false` = refused (no session / unpaid). `ok=true, opened=false` = the
|
||||||
|
* intervention was recorded (signed anomaly) but the relay did not fire. */
|
||||||
|
export type BoothReopenResult =
|
||||||
|
| { ok: false; reason: string }
|
||||||
|
| { ok: true; opened: boolean; reason?: string };
|
||||||
|
|
||||||
export class ExitFlow {
|
export class ExitFlow {
|
||||||
readonly #db: Db;
|
readonly #db: Db;
|
||||||
readonly #log: EventLog;
|
readonly #log: EventLog;
|
||||||
readonly #logger: FastifyBaseLogger;
|
readonly #logger: FastifyBaseLogger;
|
||||||
readonly #inFlight = new Set<string>();
|
readonly #inFlight = new Set<string>();
|
||||||
|
/** Optional vision client — passed to snapshotAsync so ANPR runs on the exit image. */
|
||||||
|
readonly #vision: VisionClient | null;
|
||||||
|
|
||||||
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger) {
|
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger, vision: VisionClient | null = null) {
|
||||||
this.#db = db;
|
this.#db = db;
|
||||||
this.#log = log;
|
this.#log = log;
|
||||||
this.#logger = logger;
|
this.#logger = logger;
|
||||||
|
this.#vision = vision;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* BOOTH-driven exit: the operator (not a reader at the lane) opens the barrier for
|
||||||
|
* a ticket. Runs the SAME validation as the reader path — there is no booth-only
|
||||||
|
* bypass that admits an unpaid car (see wiki/concepts/booth-exit-flow.md +
|
||||||
|
* threat-model.md). On a valid session it signs vehicle_exit, resolves AN exit
|
||||||
|
* relay site-wide, pulses it, and fires the exit snapshot.
|
||||||
|
*
|
||||||
|
* Returns a discriminated result so the route can react precisely:
|
||||||
|
* - { ok: false, status } when validation rejects (unpaid / no session / closed)
|
||||||
|
* — nothing is signed beyond the existing anomaly; the operator takes payment.
|
||||||
|
* - { ok: true, opened: true } on a clean exit.
|
||||||
|
* - { ok: true, opened: false } when the exit IS signed but the relay open FAILED
|
||||||
|
* (offline controller / no exit relay). The signed payment + vehicle_exit STAND
|
||||||
|
* (money was taken, the car is owed an exit) and an `anomaly` is appended so the
|
||||||
|
* operator opens manually. Payment is never rolled back.
|
||||||
|
*/
|
||||||
|
async exitForBooth(identity: string): Promise<BoothExitResult> {
|
||||||
|
const id = identity.trim();
|
||||||
|
if (!id) return { ok: false, status: "invalid", reason: "ticket id required" };
|
||||||
|
|
||||||
|
const key = `booth:${id}`;
|
||||||
|
if (this.#inFlight.has(key)) return { ok: false, status: "invalid", reason: "exit already in progress" };
|
||||||
|
this.#inFlight.add(key);
|
||||||
|
try {
|
||||||
|
const view = this.#sessionFor(id);
|
||||||
|
|
||||||
|
// No open session — unknown/closed ticket. Sign an anomaly (same as the reader
|
||||||
|
// path) so a booth attempt on a bad ticket is auditable.
|
||||||
|
if (!view || !view.open) {
|
||||||
|
const rp = reasonPayload(view ? "exit.refused.closed" : "exit.refused.noSession");
|
||||||
|
await this.#log.append({ type: "anomaly", identity: id, payload: { ...rp, exitRefused: true, source: "booth" } });
|
||||||
|
this.#fireExitSnapshot(id);
|
||||||
|
this.#logger.warn(`booth exit refused (${id}): ${rp.reason}`);
|
||||||
|
return { ok: false, status: view ? "closed" : "no_session", reason: rp.reason };
|
||||||
|
}
|
||||||
|
|
||||||
|
// PAID + within grace, OR free entry-grace — the same checks the reader uses.
|
||||||
|
const freeGrace = view.paidAt == null && view.freeGrace != null;
|
||||||
|
const paid = view.paidAt != null;
|
||||||
|
const withinGrace =
|
||||||
|
paid && view.graceExitMin != null && Date.now() - Date.parse(view.paidAt!) <= view.graceExitMin * 60_000;
|
||||||
|
|
||||||
|
if (!freeGrace && (!paid || !withinGrace)) {
|
||||||
|
const rp = reasonPayload(paid ? "exit.refused.graceExpired" : "exit.refused.unpaid");
|
||||||
|
await this.#log.append({ type: "anomaly", identity: id, payload: { ...rp, exitRefused: true, source: "booth" } });
|
||||||
|
this.#fireExitSnapshot(id);
|
||||||
|
this.#logger.warn(`booth exit refused (${id}): ${rp.reason}`);
|
||||||
|
return { ok: false, status: paid ? "grace_expired" : "unpaid", reason: rp.reason };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Free entry-grace path: mint the $0 payment first (ledger invariant), as the
|
||||||
|
// reader path does.
|
||||||
|
if (freeGrace && view.freeGrace) {
|
||||||
|
await this.#log.append({
|
||||||
|
type: "payment",
|
||||||
|
identity: id,
|
||||||
|
payload: {
|
||||||
|
sessionRef: id,
|
||||||
|
amountMinor: 0,
|
||||||
|
currency: view.freeGrace.currency,
|
||||||
|
tariffVersionId: view.freeGrace.tariffVersionId,
|
||||||
|
graceExitMin: view.freeGrace.graceExitMin,
|
||||||
|
...reasonPayload("exit.freeGrace"),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve AN exit barrier site-wide (no reader binding to follow at the booth).
|
||||||
|
const resolved = firstRelayByDirection(this.#db, "exit");
|
||||||
|
|
||||||
|
// Sign the vehicle_exit regardless of whether a relay resolves — the decision
|
||||||
|
// to let the car out has been made and validated. Then attempt the open.
|
||||||
|
await this.#signExit(id);
|
||||||
|
|
||||||
|
if (!resolved) {
|
||||||
|
await this.#openFailedAnomaly(id, "no exit relay configured");
|
||||||
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.noBarrier") };
|
||||||
|
}
|
||||||
|
const access = this.#buildAccess(resolved.controller);
|
||||||
|
if (!access) {
|
||||||
|
await this.#openFailedAnomaly(id, "exit controller would not build");
|
||||||
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await access.pulseOpen(resolved.relay);
|
||||||
|
} catch (err) {
|
||||||
|
await this.#openFailedAnomaly(id, `pulseOpen failed: ${(err as Error).message}`);
|
||||||
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
|
||||||
|
}
|
||||||
|
|
||||||
|
this.#fireExitSnapshot(id);
|
||||||
|
this.#closeSessionCache(id);
|
||||||
|
return { ok: true, opened: true };
|
||||||
|
} finally {
|
||||||
|
this.#inFlight.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HUMAN-INTERVENTION barrier re-open for an ACTIVE session (booth Active Sessions
|
||||||
|
* list). The barrier is unconfirmed; a car may be stuck after a damaged-ticket
|
||||||
|
* read, a dead scanner, or a phantom re-close (animal / bag / box). The operator
|
||||||
|
* opens the barrier with a signed trace.
|
||||||
|
*
|
||||||
|
* Guard: requires a PAYMENT — no payment, no re-open (the no-unpaid-bypass rule;
|
||||||
|
* the UI also hides the button). It re-pulses the exit relay and signs an `anomaly`
|
||||||
|
* ("manual barrier open", attributed). Idempotent-safe per identity via #inFlight.
|
||||||
|
*
|
||||||
|
* CLOSING THE SESSION (fix 2026-06-18): if the session is still OPEN (no
|
||||||
|
* `vehicle_exit` yet), the manual re-open *is* this car leaving — so we also sign a
|
||||||
|
* `vehicle_exit` (attributed as human-intervention). Without it the paid session
|
||||||
|
* would linger in the Active Sessions list FOREVER, since the grace-expiry eviction
|
||||||
|
* only applies to already-exited sessions (the T-397815c0 bug). If the session is
|
||||||
|
* already CLOSED (a prior exit exists — the phantom re-close case), we do NOT sign a
|
||||||
|
* second exit (that would double-count occupancy): anomaly only, as before.
|
||||||
|
* See wiki/concepts/booth-exit-flow.md.
|
||||||
|
*/
|
||||||
|
async reopenBarrier(identity: string, operator?: string): Promise<BoothReopenResult> {
|
||||||
|
const id = identity.trim();
|
||||||
|
if (!id) return { ok: false, reason: "ticket id required" };
|
||||||
|
|
||||||
|
const view = this.#sessionFor(id);
|
||||||
|
if (!view) return { ok: false, reason: "no session for ticket" };
|
||||||
|
// Authorization to re-open: a SUBSCRIPTION occurrence (prepaid — exactly the case
|
||||||
|
// the operator must assist when the exit reader / card fails) OR a transient whose
|
||||||
|
// payment is STILL WITHIN the walk-back grace window. A stale payment does NOT
|
||||||
|
// authorize a free open: a car that paid once and then sat inside past grace owes a
|
||||||
|
// top-up for the extra time — letting it out on the old payment is the overstay-fraud
|
||||||
|
// path. So we mirror the exit flow's grace check here (not just in the UI): an
|
||||||
|
// unpaid OR grace-expired transient takes the pay/exit (top-up) flow instead.
|
||||||
|
// The no-unpaid-bypass + no-free-overstay-exit rules, enforced server-side.
|
||||||
|
const paid = view.paidAt != null;
|
||||||
|
const withinGrace =
|
||||||
|
paid && view.graceExitMin != null && Date.now() - Date.parse(view.paidAt!) <= view.graceExitMin * 60_000;
|
||||||
|
if (!view.subscription && (!paid || !withinGrace)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
reason: paid ? "walk-back grace expired — take a top-up payment first" : "session not paid — no barrier open without payment",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = `reopen:${id}`;
|
||||||
|
if (this.#inFlight.has(key)) return { ok: false, reason: "re-open already in progress" };
|
||||||
|
this.#inFlight.add(key);
|
||||||
|
try {
|
||||||
|
const resolved = firstRelayByDirection(this.#db, "exit");
|
||||||
|
// Sign the audited anomaly FIRST (the intervention is recorded whether or not
|
||||||
|
// the physical open succeeds).
|
||||||
|
await this.#log.append({
|
||||||
|
type: "anomaly",
|
||||||
|
identity: id,
|
||||||
|
payload: {
|
||||||
|
...reasonPayload("exit.manualOpen"),
|
||||||
|
source: "booth",
|
||||||
|
barrierReopen: true,
|
||||||
|
...(operator ? { operator } : {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Close an OPEN session: the re-open is the exit. Sign the vehicle_exit so the
|
||||||
|
// session leaves the active list + occupancy settles. Skip when already exited
|
||||||
|
// (no double-count). Recorded as a human-intervention exit for the audit trail.
|
||||||
|
if (view.open) {
|
||||||
|
await this.#signExit(id, "manual");
|
||||||
|
this.#closeSessionCache(id);
|
||||||
|
this.#fireExitSnapshot(id);
|
||||||
|
this.#logger.info(`barrier re-open also closed open session ${id} (human-intervention exit)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!resolved) {
|
||||||
|
this.#logger.warn(`barrier re-open for ${id}: no exit relay configured`);
|
||||||
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.noBarrier") };
|
||||||
|
}
|
||||||
|
const access = this.#buildAccess(resolved.controller);
|
||||||
|
if (!access) {
|
||||||
|
this.#logger.warn(`barrier re-open for ${id}: exit controller would not build`);
|
||||||
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await access.pulseOpen(resolved.relay);
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.error(`barrier re-open pulseOpen failed (${id}): ${(err as Error).message}`);
|
||||||
|
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
|
||||||
|
}
|
||||||
|
this.#logger.info(`manual barrier open for ${id}${operator ? ` by ${operator}` : ""}`);
|
||||||
|
return { ok: true, opened: true };
|
||||||
|
} finally {
|
||||||
|
this.#inFlight.delete(key);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Handle a transient-ticket read at an exit barrier (the relay pre-resolved by the
|
/** Handle a transient-ticket read at an exit barrier (the relay pre-resolved by the
|
||||||
* read dispatcher from the reader's binding, which has ruled out a permit match). */
|
* read dispatcher from the reader's binding, which has ruled out a subscription match). */
|
||||||
async handleAt(resolved: ResolvedRelay, e: DeviceReadEvent): Promise<ReadOutcome> {
|
async handleAt(resolved: ResolvedRelay, e: DeviceReadEvent): Promise<ReadOutcome> {
|
||||||
const key = `${e.deviceId}:${e.value}`;
|
const key = `${e.deviceId}:${e.value}`;
|
||||||
if (this.#inFlight.has(key)) return { accepted: false, reason: "duplicate read in flight" };
|
if (this.#inFlight.has(key)) return { accepted: false, reason: "duplicate read in flight" };
|
||||||
@@ -66,14 +284,37 @@ export class ExitFlow {
|
|||||||
|
|
||||||
// No matching open session — unknown/duplicate ticket. Reject + log.
|
// No matching open session — unknown/duplicate ticket. Reject + log.
|
||||||
if (!view || !view.open) {
|
if (!view || !view.open) {
|
||||||
const reason = view ? "exit refused — session already closed" : "exit refused — no open session for credential";
|
const rp = reasonPayload(view ? "exit.refused.closed" : "exit.refused.noSession");
|
||||||
await this.#log.append({
|
await this.#log.append({
|
||||||
type: "anomaly",
|
type: "anomaly",
|
||||||
identity: e.value,
|
identity: e.value,
|
||||||
payload: { reason, exitRefused: true },
|
payload: { ...rp, exitRefused: true },
|
||||||
});
|
});
|
||||||
|
this.#fireExitSnapshot(e.value);
|
||||||
this.#logger.warn(`exit refused: no open session for ${e.value}`);
|
this.#logger.warn(`exit refused: no open session for ${e.value}`);
|
||||||
return { accepted: false, direction: "exit", reason };
|
return { accepted: false, direction: "exit", reason: rp.reason };
|
||||||
|
}
|
||||||
|
|
||||||
|
// FREE entry-grace: a quick in-and-out the tariff prices at 0 exits at the gate
|
||||||
|
// with no pay-station visit. Mint a signed $0 `payment` first so the ledger keeps
|
||||||
|
// its "an exit is covered by a payment" invariant, then fall through to open.
|
||||||
|
// Only when NOT already paid (a real payment, walk-back grace, takes precedence).
|
||||||
|
if (view.paidAt == null && view.freeGrace) {
|
||||||
|
await this.#log.append({
|
||||||
|
type: "payment",
|
||||||
|
// No `source` (not operator-keyed nor a read) — the payload reason marks it.
|
||||||
|
identity: e.value,
|
||||||
|
payload: {
|
||||||
|
sessionRef: e.value,
|
||||||
|
amountMinor: 0,
|
||||||
|
currency: view.freeGrace.currency,
|
||||||
|
tariffVersionId: view.freeGrace.tariffVersionId,
|
||||||
|
graceExitMin: view.freeGrace.graceExitMin,
|
||||||
|
...reasonPayload("exit.freeGrace"),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.#logger.info(`exit free within entry-grace (${e.value})`);
|
||||||
|
return this.#signExitAndOpen(resolved, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
// PAID + within walk-back grace?
|
// PAID + within walk-back grace?
|
||||||
@@ -84,49 +325,85 @@ export class ExitFlow {
|
|||||||
Date.now() - Date.parse(view.paidAt!) <= view.graceExitMin * 60_000;
|
Date.now() - Date.parse(view.paidAt!) <= view.graceExitMin * 60_000;
|
||||||
|
|
||||||
if (!paid || !withinGrace) {
|
if (!paid || !withinGrace) {
|
||||||
const reason = !paid
|
const rp = reasonPayload(paid ? "exit.refused.graceExpired" : "exit.refused.unpaid");
|
||||||
? "exit refused — not paid (pay at the station)"
|
|
||||||
: "exit refused — walk-back grace expired (top-up required)";
|
|
||||||
await this.#log.append({
|
await this.#log.append({
|
||||||
type: "anomaly",
|
type: "anomaly",
|
||||||
identity: e.value,
|
identity: e.value,
|
||||||
payload: { reason, exitRefused: true, sessionRef: e.value },
|
payload: { ...rp, exitRefused: true, sessionRef: e.value },
|
||||||
});
|
});
|
||||||
this.#logger.warn(`exit refused (${e.value}): ${reason}`);
|
this.#fireExitSnapshot(e.value);
|
||||||
return { accepted: false, direction: "exit", reason };
|
this.#logger.warn(`exit refused (${e.value}): ${rp.reason}`);
|
||||||
|
return { accepted: false, direction: "exit", reason: rp.reason };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Valid: sign the exit BEFORE opening, then open, then update the cache.
|
// Valid (a real payment within walk-back grace): sign + open.
|
||||||
await this.#log.append({
|
return this.#signExitAndOpen(resolved, e);
|
||||||
type: "vehicle_exit",
|
}
|
||||||
direction: "exit",
|
|
||||||
source: e.kind === "plate" ? "lpr" : "ticket",
|
/** Sign the vehicle_exit BEFORE opening, then open, snapshot, and update the cache.
|
||||||
identity: e.value,
|
* Shared by the paid-exit and free-entry-grace paths. The caller has already
|
||||||
payload: { sessionRef: e.value },
|
* established the session is allowed out (and, for grace, minted the $0 payment). */
|
||||||
});
|
async #signExitAndOpen(resolved: ResolvedRelay, e: DeviceReadEvent): Promise<ReadOutcome> {
|
||||||
|
await this.#signExit(e.value, e.kind === "plate" ? "lpr" : "ticket");
|
||||||
|
|
||||||
const access = this.#buildAccess(resolved.controller);
|
const access = this.#buildAccess(resolved.controller);
|
||||||
if (access) await access.pulseOpen(resolved.relay);
|
if (access) await access.pulseOpen(resolved.relay);
|
||||||
else this.#logger.warn(`exit signed for ${e.value} but the exit relay won't build`);
|
else this.#logger.warn(`exit signed for ${e.value} but the exit relay won't build`);
|
||||||
|
|
||||||
// SNAPSHOT — fire the exit camera(s), never awaited (evidence, not a gate).
|
this.#fireExitSnapshot(e.value);
|
||||||
|
this.#closeSessionCache(e.value);
|
||||||
|
return { accepted: true, direction: "exit" };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Append the signed vehicle_exit. `source`: "ticket" (booth/reader), "lpr" (plate),
|
||||||
|
* or "manual" (a human-intervention barrier re-open that closes an open session —
|
||||||
|
* see reopenBarrier). */
|
||||||
|
async #signExit(identity: string, source: "ticket" | "lpr" | "manual" = "ticket"): Promise<void> {
|
||||||
|
await this.#log.append({
|
||||||
|
type: "vehicle_exit",
|
||||||
|
direction: "exit",
|
||||||
|
source,
|
||||||
|
identity,
|
||||||
|
payload: {
|
||||||
|
sessionRef: identity,
|
||||||
|
...(source === "manual" ? reasonPayload("exit.manualOpen") : {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fire the exit camera(s); never awaited (evidence, not a gate). */
|
||||||
|
#fireExitSnapshot(identity: string): void {
|
||||||
void snapshotAsync({
|
void snapshotAsync({
|
||||||
db: this.#db,
|
db: this.#db,
|
||||||
direction: "exit",
|
direction: "exit",
|
||||||
identity: e.value,
|
identity,
|
||||||
logger: this.#logger,
|
logger: this.#logger,
|
||||||
|
vision: this.#vision,
|
||||||
}).catch((err) => this.#logger.error(`exit snapshot error: ${(err as Error).message}`));
|
}).catch((err) => this.#logger.error(`exit snapshot error: ${(err as Error).message}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Update the (rebuildable) session projection cache to closed. */
|
||||||
|
#closeSessionCache(identity: string): void {
|
||||||
try {
|
try {
|
||||||
this.#db
|
this.#db
|
||||||
.update(sessions)
|
.update(sessions)
|
||||||
.set({ exitedAt: new Date().toISOString(), state: "closed" })
|
.set({ exitedAt: new Date().toISOString(), state: "closed" })
|
||||||
.where(eq(sessions.id, e.value))
|
.where(eq(sessions.id, identity))
|
||||||
.run();
|
.run();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.#logger.error(`session-cache close failed for ${e.value}: ${(err as Error).message}`);
|
this.#logger.error(`session-cache close failed for ${identity}: ${(err as Error).message}`);
|
||||||
}
|
}
|
||||||
return { accepted: true, direction: "exit" };
|
}
|
||||||
|
|
||||||
|
/** Record an audited anomaly when an exit was signed but the barrier didn't open.
|
||||||
|
* The payment + exit STAND; this tells the operator to open manually. */
|
||||||
|
async #openFailedAnomaly(identity: string, detail: string): Promise<void> {
|
||||||
|
await this.#log.append({
|
||||||
|
type: "anomaly",
|
||||||
|
identity,
|
||||||
|
payload: { ...reasonPayload("exit.open.failed"), detail, source: "booth", exitOpenFailed: true },
|
||||||
|
});
|
||||||
|
this.#logger.error(`booth exit open failed (${identity}): ${detail}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fold the signed ledger into a session view for one identity (authoritative). */
|
/** Fold the signed ledger into a session view for one identity (authoritative). */
|
||||||
@@ -153,15 +430,57 @@ export class ExitFlow {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Free entry-grace: if the tariff prices entry→now at 0 (a quick in-and-out),
|
||||||
|
// the exit may open at the gate. Resolve against the tariff in force at entry,
|
||||||
|
// same as the pay station. Null when no payment is needed yet and no tariff
|
||||||
|
// resolves — then exit falls back to the normal paid check.
|
||||||
|
let freeGrace: SessionView["freeGrace"] = null;
|
||||||
|
if (!exited && paidAt == null) {
|
||||||
|
const tv = this.#tariffVersionFor(entry.occurredAt);
|
||||||
|
if (tv) {
|
||||||
|
const structure = tv.structure as unknown as TariffStructure;
|
||||||
|
// Same frozen-at-entry category the pay station uses, so the free-grace
|
||||||
|
// check agrees with the booth quote for V2 category tariffs.
|
||||||
|
const category = (entry.payload as { category?: string } | null)?.category;
|
||||||
|
const fee = computeFee(entry.occurredAt, new Date().toISOString(), structure, category);
|
||||||
|
if (fee === 0) {
|
||||||
|
freeGrace = {
|
||||||
|
tariffVersionId: tv.id,
|
||||||
|
currency: tv.currency,
|
||||||
|
graceExitMin: structure.gracePeriodExitMin,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const entryPl = (entry.payload ?? {}) as { permit?: boolean; permitId?: string };
|
||||||
|
const subscription = entryPl.permit === true || entryPl.permitId != null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
identity,
|
identity,
|
||||||
enteredAt: entry.occurredAt,
|
enteredAt: entry.occurredAt,
|
||||||
open: !exited,
|
open: !exited,
|
||||||
paidAt,
|
paidAt,
|
||||||
|
subscription,
|
||||||
graceExitMin,
|
graceExitMin,
|
||||||
|
freeGrace,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The tariff version in force at `at` — latest effectiveFrom ≤ at, for the
|
||||||
|
* (single, for now) active site tariff. Mirrors PayStation#tariffVersionFor. */
|
||||||
|
#tariffVersionFor(at: string) {
|
||||||
|
const tariff = this.#db.select().from(tariffs).where(eq(tariffs.scope, "site")).get();
|
||||||
|
if (!tariff) return null;
|
||||||
|
const versions = this.#db
|
||||||
|
.select()
|
||||||
|
.from(tariffVersions)
|
||||||
|
.where(eq(tariffVersions.tariffId, tariff.id))
|
||||||
|
.orderBy(desc(tariffVersions.effectiveFrom))
|
||||||
|
.all();
|
||||||
|
return versions.find((v) => v.effectiveFrom <= at) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
/** Build a live access adapter from a resolved controller row, or null. */
|
/** Build a live access adapter from a resolved controller row, or null. */
|
||||||
#buildAccess(row: DeviceRow): AccessControlDevice | null {
|
#buildAccess(row: DeviceRow): AccessControlDevice | null {
|
||||||
const driver = registry.get(row.driverId);
|
const driver = registry.get(row.driverId);
|
||||||
|
|||||||
@@ -0,0 +1,236 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { and, appLogs, desc, eq, sql, type Db } from "@parking/db";
|
||||||
|
import {
|
||||||
|
LOG_LEVEL_ORDER,
|
||||||
|
type AppLogRecord,
|
||||||
|
type ClientLogInput,
|
||||||
|
type LogLevel,
|
||||||
|
type LogSource,
|
||||||
|
} from "@parking/shared";
|
||||||
|
|
||||||
|
// Application/diagnostic LOG SINK — the host-side store behind the third log stream
|
||||||
|
// (app_logs), distinct from the signed ledger and device telemetry. It persists:
|
||||||
|
// - BACKEND warn/error/fatal, fed by a pino stream (see pinoDbStream) so any
|
||||||
|
// app.log.warn/error lands in the DB without changing call sites.
|
||||||
|
// - FRONTEND errors POSTed to /api/logs (failed requests, uncaught errors).
|
||||||
|
// Everything here is UNSIGNED + prunable. Pruned by age AND a row cap so an offline
|
||||||
|
// appliance with finite disk can't be filled by a log storm. See
|
||||||
|
// wiki/concepts/app-logs.md, decisions/event-streams-split.md.
|
||||||
|
|
||||||
|
/** Only warn and above are persisted from the backend (info/debug stay stdout-only). */
|
||||||
|
const BACKEND_PERSIST_MIN: LogLevel = "warn";
|
||||||
|
|
||||||
|
/** Defensive caps so one runaway log can't bloat a row (chars). */
|
||||||
|
const MAX_MESSAGE = 4_000;
|
||||||
|
const MAX_STACK = 16_000;
|
||||||
|
const MAX_CONTEXT_JSON = 16_000;
|
||||||
|
|
||||||
|
export interface LogRetention {
|
||||||
|
/** Delete logs older than this many days. */
|
||||||
|
readonly maxAgeDays: number;
|
||||||
|
/** Hard cap on total rows — the oldest beyond this are pruned. */
|
||||||
|
readonly maxRows: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_RETENTION: LogRetention = {
|
||||||
|
maxAgeDays: Number(process.env.LOG_RETENTION_DAYS ?? 30),
|
||||||
|
maxRows: Number(process.env.LOG_RETENTION_MAX_ROWS ?? 50_000),
|
||||||
|
};
|
||||||
|
|
||||||
|
function clamp(s: string | null | undefined, max: number): string | null {
|
||||||
|
if (s == null) return null;
|
||||||
|
return s.length > max ? s.slice(0, max) : s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Serialize context to JSON, bounded — never throw on a circular/huge object. */
|
||||||
|
function safeContext(ctx: Record<string, unknown> | null | undefined): Record<string, unknown> | null {
|
||||||
|
if (ctx == null) return null;
|
||||||
|
try {
|
||||||
|
const json = JSON.stringify(ctx);
|
||||||
|
if (json.length <= MAX_CONTEXT_JSON) return ctx;
|
||||||
|
return { _truncated: true, preview: json.slice(0, MAX_CONTEXT_JSON) };
|
||||||
|
} catch {
|
||||||
|
return { _unserializable: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LogService {
|
||||||
|
readonly #db: Db;
|
||||||
|
readonly #retention: LogRetention;
|
||||||
|
/** Reentrancy guard: never let persisting a log itself emit a persisted log. */
|
||||||
|
#writing = false;
|
||||||
|
|
||||||
|
constructor(db: Db, retention: LogRetention = DEFAULT_RETENTION) {
|
||||||
|
this.#db = db;
|
||||||
|
this.#retention = retention;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Low-level insert. Best-effort: a logging failure must never break a request or
|
||||||
|
* recurse (a DB error here would otherwise log → insert → error → log …). */
|
||||||
|
#insert(row: {
|
||||||
|
level: LogLevel;
|
||||||
|
source: LogSource;
|
||||||
|
message: string;
|
||||||
|
context?: Record<string, unknown> | null;
|
||||||
|
httpStatus?: number | null;
|
||||||
|
path?: string | null;
|
||||||
|
stack?: string | null;
|
||||||
|
userId?: string | null;
|
||||||
|
userAgent?: string | null;
|
||||||
|
createdAt?: string;
|
||||||
|
}): void {
|
||||||
|
if (this.#writing) return;
|
||||||
|
this.#writing = true;
|
||||||
|
try {
|
||||||
|
this.#db
|
||||||
|
.insert(appLogs)
|
||||||
|
.values({
|
||||||
|
id: randomUUID(),
|
||||||
|
level: row.level,
|
||||||
|
source: row.source,
|
||||||
|
message: clamp(row.message, MAX_MESSAGE) ?? "",
|
||||||
|
context: safeContext(row.context),
|
||||||
|
httpStatus: row.httpStatus ?? null,
|
||||||
|
path: clamp(row.path, 512),
|
||||||
|
stack: clamp(row.stack, MAX_STACK),
|
||||||
|
userId: row.userId ?? null,
|
||||||
|
userAgent: clamp(row.userAgent, 512),
|
||||||
|
createdAt: row.createdAt ?? new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
} catch {
|
||||||
|
// Swallow — diagnostics must never take down the path they observe. (Can't log
|
||||||
|
// it; that's the recursion we're guarding against.)
|
||||||
|
} finally {
|
||||||
|
this.#writing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Persist a BACKEND log line (called by the pino stream). Below warn is dropped. */
|
||||||
|
recordBackend(level: LogLevel, message: string, context?: Record<string, unknown> | null): void {
|
||||||
|
if (LOG_LEVEL_ORDER[level] < LOG_LEVEL_ORDER[BACKEND_PERSIST_MIN]) return;
|
||||||
|
this.#insert({ level, source: "backend", message, context });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Persist a FRONTEND-reported log (from POST /api/logs). The server stamps the
|
||||||
|
* user + receive time; the client supplies level/message/context. */
|
||||||
|
recordClient(
|
||||||
|
input: ClientLogInput,
|
||||||
|
meta: { userId?: string | null; userAgent?: string | null },
|
||||||
|
): void {
|
||||||
|
this.#insert({
|
||||||
|
level: input.level,
|
||||||
|
source: "frontend",
|
||||||
|
message: input.message,
|
||||||
|
context: input.context ?? null,
|
||||||
|
httpStatus: input.httpStatus ?? null,
|
||||||
|
path: input.path ?? null,
|
||||||
|
stack: input.stack ?? null,
|
||||||
|
userId: meta.userId ?? null,
|
||||||
|
userAgent: meta.userAgent ?? null,
|
||||||
|
// Keep the client's capture time in context for ordering; createdAt is server time.
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read recent logs, newest first, with optional level/source/since filters. */
|
||||||
|
query(opts: {
|
||||||
|
limit: number;
|
||||||
|
level?: LogLevel;
|
||||||
|
source?: LogSource;
|
||||||
|
since?: string;
|
||||||
|
}): AppLogRecord[] {
|
||||||
|
const conds = [];
|
||||||
|
if (opts.level) conds.push(eq(appLogs.level, opts.level));
|
||||||
|
if (opts.source) conds.push(eq(appLogs.source, opts.source));
|
||||||
|
if (opts.since) conds.push(sql`${appLogs.createdAt} >= ${opts.since}`);
|
||||||
|
const rows = this.#db
|
||||||
|
.select()
|
||||||
|
.from(appLogs)
|
||||||
|
.where(conds.length ? and(...conds) : undefined)
|
||||||
|
.orderBy(desc(appLogs.createdAt))
|
||||||
|
.limit(opts.limit)
|
||||||
|
.all();
|
||||||
|
return rows as unknown as AppLogRecord[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Prune by age then by row cap. Returns how many rows were deleted. Safe to call
|
||||||
|
* on a timer; cheap (indexed on created_at). */
|
||||||
|
prune(): number {
|
||||||
|
let deleted = 0;
|
||||||
|
try {
|
||||||
|
const cutoff = new Date(Date.now() - this.#retention.maxAgeDays * 86_400_000).toISOString();
|
||||||
|
const byAge = this.#db.delete(appLogs).where(sql`${appLogs.createdAt} < ${cutoff}`).run();
|
||||||
|
deleted += byAge.changes ?? 0;
|
||||||
|
|
||||||
|
// Row cap: keep the newest maxRows, delete the rest. One subquery — find the
|
||||||
|
// created_at boundary of the keep-window, delete older.
|
||||||
|
const total = this.#db.select({ c: sql<number>`count(*)` }).from(appLogs).get();
|
||||||
|
const count = total?.c ?? 0;
|
||||||
|
if (count > this.#retention.maxRows) {
|
||||||
|
const boundary = this.#db
|
||||||
|
.select({ createdAt: appLogs.createdAt })
|
||||||
|
.from(appLogs)
|
||||||
|
.orderBy(desc(appLogs.createdAt))
|
||||||
|
.limit(1)
|
||||||
|
.offset(this.#retention.maxRows - 1)
|
||||||
|
.get();
|
||||||
|
if (boundary) {
|
||||||
|
const byCap = this.#db
|
||||||
|
.delete(appLogs)
|
||||||
|
.where(sql`${appLogs.createdAt} < ${boundary.createdAt}`)
|
||||||
|
.run();
|
||||||
|
deleted += byCap.changes ?? 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// best-effort
|
||||||
|
}
|
||||||
|
return deleted;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A pino-compatible write stream that forwards BACKEND warn+ lines into the LogService.
|
||||||
|
* Pino writes one JSON object per line to this stream; we parse, map the numeric level
|
||||||
|
* to a name, and persist. Returned as `{ write }` so it can be passed as pino's stream.
|
||||||
|
* stdout still receives the same line (we tee), so console logging is unchanged.
|
||||||
|
*/
|
||||||
|
export function pinoDbStream(
|
||||||
|
service: LogService,
|
||||||
|
tee: NodeJS.WritableStream,
|
||||||
|
): { write: (line: string) => void } {
|
||||||
|
const NUM_TO_LEVEL: Record<number, LogLevel> = {
|
||||||
|
10: "trace",
|
||||||
|
20: "debug",
|
||||||
|
30: "info",
|
||||||
|
40: "warn",
|
||||||
|
50: "error",
|
||||||
|
60: "fatal",
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
write(line: string): void {
|
||||||
|
// Always tee to the original destination first (don't lose stdout logging).
|
||||||
|
try {
|
||||||
|
tee.write(line);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const obj = JSON.parse(line) as {
|
||||||
|
level?: number;
|
||||||
|
msg?: string;
|
||||||
|
err?: { stack?: string; message?: string };
|
||||||
|
[k: string]: unknown;
|
||||||
|
};
|
||||||
|
const level = NUM_TO_LEVEL[obj.level ?? 30] ?? "info";
|
||||||
|
if (LOG_LEVEL_ORDER[level] < LOG_LEVEL_ORDER[BACKEND_PERSIST_MIN]) return;
|
||||||
|
// Strip pino's noisy standard fields from the persisted context.
|
||||||
|
const { level: _l, time: _t, pid: _p, hostname: _h, msg, ...rest } = obj;
|
||||||
|
service.recordBackend(level, typeof msg === "string" ? msg : "", rest);
|
||||||
|
} catch {
|
||||||
|
// A non-JSON line (shouldn't happen with pino) — ignore for persistence.
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { eq, ledgerEvents, siteConfig, type Db } from "@parking/db";
|
import { eq, ledgerEvents, siteConfig, subscriptions, type Db } from "@parking/db";
|
||||||
|
|
||||||
// Occupancy = a FOLD over the signed ledger: the count of vehicle_entry events
|
// Occupancy = a FOLD over the signed ledger: the count of vehicle_entry events
|
||||||
// with no matching vehicle_exit. Never a hand-maintained counter (which is
|
// with no matching vehicle_exit. Never a hand-maintained counter (which is
|
||||||
@@ -7,11 +7,18 @@ import { eq, ledgerEvents, siteConfig, type Db } from "@parking/db";
|
|||||||
export interface Occupancy {
|
export interface Occupancy {
|
||||||
/** Cars currently inside (open sessions). */
|
/** Cars currently inside (open sessions). */
|
||||||
readonly count: number;
|
readonly count: number;
|
||||||
|
/** Spots HELD for active subscribers who are NOT currently parked (when the
|
||||||
|
* reserve-subscriber-spots toggle is on; 0 otherwise). Each active subscription holds
|
||||||
|
* `quantity` spots minus however many of its cars are already inside. */
|
||||||
|
readonly reserved: number;
|
||||||
/** Admin-set nominal capacity, or null = no limit. */
|
/** Admin-set nominal capacity, or null = no limit. */
|
||||||
readonly capacity: number | null;
|
readonly capacity: number | null;
|
||||||
/** capacity − count, or null when uncapped. Can read 0 (or below) when full. */
|
/** capacity − count, or null when uncapped. Can read 0 (or below) when full. */
|
||||||
readonly free: number | null;
|
readonly free: number | null;
|
||||||
/** True when count ≥ capacity (always false when uncapped). */
|
/** Effective free for a TRANSIENT car = capacity − count − reserved (null uncapped). */
|
||||||
|
readonly effectiveFree: number | null;
|
||||||
|
/** True when a TRANSIENT entry should be refused: count + reserved ≥ capacity
|
||||||
|
* (always false when uncapped). Subscribers are never gated by this. */
|
||||||
readonly full: boolean;
|
readonly full: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,13 +44,66 @@ export function siteCapacity(db: Db): number | null {
|
|||||||
return row?.capacity ?? null;
|
return row?.capacity ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Spots to RESERVE for active subscribers who aren't currently parked. Off (0) unless
|
||||||
|
* `site_config.reserve_subscriber_spots` is set. For each ACTIVE subscription (status
|
||||||
|
* active AND now ∈ [validFrom, validTo]), hold `quantity` spots minus the cars of that
|
||||||
|
* subscription already inside (so we never double-count a parked subscriber). This is
|
||||||
|
* what makes a transient see "full" sooner while the subscriber's spot is held.
|
||||||
|
*/
|
||||||
|
export function reservedSubscriberSpots(db: Db): number {
|
||||||
|
const cfg = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||||
|
if (!cfg?.reserveSubscriberSpots) return 0;
|
||||||
|
|
||||||
|
// Cars currently inside per subscription (occurrence entries by permitId, net of exits).
|
||||||
|
const rows = db.select().from(ledgerEvents).orderBy(ledgerEvents.index).all();
|
||||||
|
const insidePerSub = new Map<string, number>();
|
||||||
|
const net = new Map<string, number>(); // occurrence identity → entries−exits
|
||||||
|
const subOf = new Map<string, string>(); // occurrence identity → subscription id
|
||||||
|
for (const r of rows) {
|
||||||
|
const id = r.identity;
|
||||||
|
if (!id) continue;
|
||||||
|
if (r.type === "vehicle_entry") {
|
||||||
|
const pl = (r.payload ?? {}) as { permitId?: string };
|
||||||
|
if (pl.permitId == null) continue; // transient
|
||||||
|
net.set(id, (net.get(id) ?? 0) + 1);
|
||||||
|
subOf.set(id, pl.permitId);
|
||||||
|
} else if (r.type === "vehicle_exit") {
|
||||||
|
if (net.has(id)) net.set(id, (net.get(id) ?? 0) - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [id, n] of net) if (n > 0) {
|
||||||
|
const sub = subOf.get(id)!;
|
||||||
|
insidePerSub.set(sub, (insidePerSub.get(sub) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const subs = db.select().from(subscriptions).all();
|
||||||
|
let reserved = 0;
|
||||||
|
for (const s of subs) {
|
||||||
|
const active =
|
||||||
|
s.status === "active" &&
|
||||||
|
(s.validFrom == null || now >= s.validFrom) &&
|
||||||
|
(s.validTo == null || now <= s.validTo);
|
||||||
|
if (!active) continue;
|
||||||
|
const qty = s.quantity ?? 1;
|
||||||
|
const inside = insidePerSub.get(s.id) ?? 0;
|
||||||
|
reserved += Math.max(0, qty - inside); // hold only the not-yet-parked portion
|
||||||
|
}
|
||||||
|
return reserved;
|
||||||
|
}
|
||||||
|
|
||||||
export function getOccupancy(db: Db): Occupancy {
|
export function getOccupancy(db: Db): Occupancy {
|
||||||
const count = occupancyCount(db);
|
const count = occupancyCount(db);
|
||||||
const capacity = siteCapacity(db);
|
const capacity = siteCapacity(db);
|
||||||
|
const reserved = reservedSubscriberSpots(db);
|
||||||
return {
|
return {
|
||||||
count,
|
count,
|
||||||
|
reserved,
|
||||||
capacity,
|
capacity,
|
||||||
free: capacity == null ? null : capacity - count,
|
free: capacity == null ? null : capacity - count,
|
||||||
full: capacity != null && count >= capacity,
|
effectiveFree: capacity == null ? null : capacity - count - reserved,
|
||||||
|
// A transient is refused once physical cars + held subscriber spots reach capacity.
|
||||||
|
full: capacity != null && count + reserved >= capacity,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { desc, eq, ledgerEvents, sessions, tariffVersions, tariffs, type Db } from "@parking/db";
|
import { desc, eq, ledgerEvents, sessions, subscriptions, tariffVersions, tariffs, type Db } from "@parking/db";
|
||||||
import { computeFee, type TariffStructure, type Tender } from "@parking/shared";
|
import { priceSession, type TariffStructure, type Tender } from "@parking/shared";
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
import type { EventLog } from "./event-log.js";
|
import type { EventLog } from "./event-log.js";
|
||||||
|
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
|
||||||
|
import { windowOwedBetween } from "./subscription-window.js";
|
||||||
|
|
||||||
// The PAY STATION: a customer pays for an open session BEFORE walking back to the
|
// The PAY STATION: a customer pays for an open session BEFORE walking back to the
|
||||||
// car (pay-on-foot — payment is decoupled from exit). Two steps:
|
// car (pay-on-foot — payment is decoupled from exit). Two steps:
|
||||||
@@ -28,13 +30,90 @@ export class NoTariffError extends Error {
|
|||||||
|
|
||||||
export interface Quote {
|
export interface Quote {
|
||||||
readonly identity: string;
|
readonly identity: string;
|
||||||
|
/** Vehicle entry time (the session's original entry; for display/audit). */
|
||||||
readonly enteredAt: string;
|
readonly enteredAt: string;
|
||||||
|
/** Start of the period being billed RIGHT NOW. For a first payment this is the
|
||||||
|
* entry. For an OVERSTAY (a paid session whose walk-back grace lapsed — the car
|
||||||
|
* re-parked / a new period began) it is the moment that grace expired: the overstay
|
||||||
|
* 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]. */
|
||||||
readonly amountMinor: number;
|
readonly amountMinor: number;
|
||||||
|
/** True when this quote prices an overstay period (grace lapsed), not the first stay. */
|
||||||
|
readonly overstay: boolean;
|
||||||
readonly currency: string;
|
readonly currency: string;
|
||||||
readonly tariffVersionId: string;
|
readonly tariffVersionId: string;
|
||||||
readonly graceExitMin: number;
|
readonly graceExitMin: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One row in the booth Active Sessions list. A session is "active" while it is
|
||||||
|
* still open OR exited-but-within-grace — because the barrier is UNCONFIRMED, a
|
||||||
|
* paid/exited car is presumed possibly-still-present until grace expires. The
|
||||||
|
* "Open barrier" action is offered only when `paidAt != null` (no payment, no
|
||||||
|
* button — the no-unpaid-bypass rule). See wiki/concepts/booth-exit-flow.md. */
|
||||||
|
export interface ActiveSession {
|
||||||
|
readonly identity: string;
|
||||||
|
readonly source: string | null;
|
||||||
|
readonly enteredAt: string;
|
||||||
|
/** null while still inside; set once a vehicle_exit is signed (may still be present). */
|
||||||
|
readonly exitedAt: string | null;
|
||||||
|
readonly open: boolean;
|
||||||
|
readonly paidAt: string | null;
|
||||||
|
/** Amount owed now (open + unpaid only; null otherwise / no tariff). */
|
||||||
|
readonly amountMinor: number | null;
|
||||||
|
readonly currency: string | null;
|
||||||
|
readonly withinGrace: boolean;
|
||||||
|
readonly graceExpiresAt: string | null;
|
||||||
|
/** OVERSTAY = a paid transient whose walk-back grace lapsed with NO signed vehicle_exit.
|
||||||
|
* The car either re-parked (a new period began) or is faulty/abandoned — not a system
|
||||||
|
* fault, and not "stuck". It lingers in occupancy and owes a fresh period (priced from
|
||||||
|
* grace-expiry, see `quote`). We keep it listed and BADGE it OVERSTAY so the operator
|
||||||
|
* reconciles via a top-up, instead of silently aging it out. No free barrier open.
|
||||||
|
* See wiki/concepts/booth-exit-flow.md. */
|
||||||
|
readonly overstay: boolean;
|
||||||
|
/** True for a SUBSCRIPTION occurrence (prepaid — never charged). The booth shows it
|
||||||
|
* with snapshots + an always-available "open barrier" (assist a faulty exit reader /
|
||||||
|
* missing card), and never a pay flow. See wiki/entities/subscription.md. */
|
||||||
|
readonly subscription: boolean;
|
||||||
|
/** The subscription id (on-chain `permitId`), when `subscription` is true. */
|
||||||
|
readonly subscriptionId: string | null;
|
||||||
|
/** The subscriber's holder name (for a friendly label instead of the raw key). */
|
||||||
|
readonly subscriptionHolder: string | null;
|
||||||
|
/** Advisory licence plate recognized for this session (ANPR-on-snapshot), shown for
|
||||||
|
* at-a-glance identification. Null when no plate was read. Never an access decision. */
|
||||||
|
readonly plate: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Booth session view: everything the pay/exit modal needs in one read. */
|
||||||
|
export interface SessionLookup {
|
||||||
|
readonly identity: string;
|
||||||
|
readonly found: boolean;
|
||||||
|
/** Open = entered, no exit yet. */
|
||||||
|
readonly open: boolean;
|
||||||
|
readonly enteredAt: string | null;
|
||||||
|
readonly exitedAt: string | null;
|
||||||
|
/** Latest payment time, if paid. */
|
||||||
|
readonly paidAt: string | null;
|
||||||
|
/** Amount owed right now (the quote). Null when no session / no active tariff. */
|
||||||
|
readonly amountMinor: number | null;
|
||||||
|
readonly currency: string | null;
|
||||||
|
/** True when paid AND still within the walk-back grace window. */
|
||||||
|
readonly withinGrace: boolean;
|
||||||
|
/** ISO time the walk-back grace expires (paidAt + graceExitMin), if paid. */
|
||||||
|
readonly graceExpiresAt: string | null;
|
||||||
|
/** OVERSTAY = paid transient, walk-back grace expired, no signed exit. A new period
|
||||||
|
* began; `amountMinor` is the fresh fee from grace-expiry — it cannot exit for free. */
|
||||||
|
readonly overstay: boolean;
|
||||||
|
/** True for a SUBSCRIPTION occurrence (prepaid — never charged; barrier-open only). */
|
||||||
|
readonly subscription: boolean;
|
||||||
|
readonly subscriptionId: string | null;
|
||||||
|
readonly subscriptionHolder: string | null;
|
||||||
|
/** Advisory licence plate recognized for this session (ANPR-on-snapshot). Null when
|
||||||
|
* none. Display/audit only — never an access decision. */
|
||||||
|
readonly plate: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export class PayStation {
|
export class PayStation {
|
||||||
readonly #db: Db;
|
readonly #db: Db;
|
||||||
readonly #log: EventLog;
|
readonly #log: EventLog;
|
||||||
@@ -46,38 +125,106 @@ export class PayStation {
|
|||||||
this.#logger = logger;
|
this.#logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Price an open session against the tariff in force at its entry. No side effect. */
|
/** 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
|
||||||
|
* own daily-cap ladder. This is NOT "full stay minus paid": with a daily cap the
|
||||||
|
* whole-stay gross plateaus while prior payments keep pace, so the delta collapses to
|
||||||
|
* 0 and a multi-day overstay would exit free (ticket 1245791632490). A new period
|
||||||
|
* reflects the reality and re-accrues the fee. No side effect. */
|
||||||
quote(identity: string): Quote {
|
quote(identity: string): Quote {
|
||||||
const entry = this.#openEntry(identity);
|
const entry = this.#openEntry(identity);
|
||||||
if (!entry) throw new NoOpenSessionError(identity);
|
if (!entry) throw new NoOpenSessionError(identity);
|
||||||
|
|
||||||
|
// The tariff in force is keyed to ENTRY (the version frozen for this session), even
|
||||||
|
// for an overstay period — the customer keeps the rate card they entered under.
|
||||||
const tv = this.#tariffVersionFor(entry.occurredAt);
|
const tv = this.#tariffVersionFor(entry.occurredAt);
|
||||||
if (!tv) throw new NoTariffError();
|
if (!tv) throw new NoTariffError();
|
||||||
const structure = tv.structure as unknown as TariffStructure;
|
const structure = tv.structure as unknown as TariffStructure;
|
||||||
|
|
||||||
const amountMinor = computeFee(entry.occurredAt, new Date().toISOString(), structure);
|
// Category was frozen in the signed vehicle_entry payload — pricing AND repricing
|
||||||
|
// both read it from there, so a V2 category tariff yields the same amount at the
|
||||||
|
// booth and at exit. Absent (legacy/V1) ⇒ undefined ⇒ category-agnostic pricing.
|
||||||
|
const category = (entry.payload as { category?: string } | null)?.category;
|
||||||
|
|
||||||
|
// Pure pricing shared with the Tariff Lab (priceSession). Only the latest payment
|
||||||
|
// matters for grace/overstay; pass it through. Overstay → fresh period from
|
||||||
|
// grace-expiry; within-grace → settled; unpaid → entry→now running total.
|
||||||
|
const last = this.#lastPayment(identity);
|
||||||
|
const p = priceSession(
|
||||||
|
entry.occurredAt,
|
||||||
|
new Date().toISOString(),
|
||||||
|
structure,
|
||||||
|
last ? [last] : [],
|
||||||
|
category,
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
identity,
|
identity,
|
||||||
enteredAt: entry.occurredAt,
|
enteredAt: entry.occurredAt,
|
||||||
amountMinor,
|
periodStart: p.periodStart,
|
||||||
|
amountMinor: p.amountMinor,
|
||||||
|
overstay: p.overstay,
|
||||||
currency: tv.currency,
|
currency: tv.currency,
|
||||||
tariffVersionId: tv.id,
|
tariffVersionId: tv.id,
|
||||||
graceExitMin: structure.gracePeriodExitMin,
|
graceExitMin: structure.gracePeriodExitMin,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The latest signed `payment` for this session (time + the grace window it granted),
|
||||||
|
* or null if never paid. Folds the append-only ledger. */
|
||||||
|
#lastPayment(identity: string): { paidAt: string; graceExitMin: number | null } | null {
|
||||||
|
const rows = this.#db
|
||||||
|
.select({ type: ledgerEvents.type, occurredAt: ledgerEvents.occurredAt, payload: ledgerEvents.payload })
|
||||||
|
.from(ledgerEvents)
|
||||||
|
.where(eq(ledgerEvents.identity, identity))
|
||||||
|
.orderBy(ledgerEvents.index)
|
||||||
|
.all();
|
||||||
|
let last: { paidAt: string; graceExitMin: number | null } | null = null;
|
||||||
|
for (const r of rows) {
|
||||||
|
if (r.type !== "payment") continue;
|
||||||
|
const g = (r.payload as { graceExitMin?: number } | null)?.graceExitMin;
|
||||||
|
last = { paidAt: r.occurredAt, graceExitMin: typeof g === "number" ? g : null };
|
||||||
|
}
|
||||||
|
return last;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Take payment for a session and append the signed `payment` event. Re-quotes at
|
* Take payment for a session and append the signed `payment` event. Re-quotes at
|
||||||
* the moment of payment (the customer pays for time parked SO FAR). For an
|
* the moment of payment (the customer pays for time parked SO FAR). For an OVERSTAY
|
||||||
* overstay top-up the same call re-prices entry→now and the exit flow's
|
* (grace lapsed) the quote prices a fresh period from grace-expiry→now (see `quote`),
|
||||||
* grace-window restarts from this payment. `overrideMinor` lets the operator set
|
* and this payment writes a new `graceExitMin` so the walk-back window restarts.
|
||||||
* an arbitrary amount (lost ticket / dispute) — recorded as the charged amount.
|
* `overrideMinor` lets the operator set an arbitrary amount (lost ticket / dispute) —
|
||||||
|
* recorded as the charged amount.
|
||||||
*/
|
*/
|
||||||
async pay(
|
async pay(
|
||||||
identity: string,
|
identity: string,
|
||||||
tender: Tender,
|
tender: Tender,
|
||||||
overrideMinor?: number,
|
overrideMinor?: number,
|
||||||
): Promise<{ amountMinor: number; currency: string }> {
|
): Promise<{ amountMinor: number; currency: string }> {
|
||||||
|
// A SUBSCRIPTION occurrence settles its out-of-window tariff-bridge charge here
|
||||||
|
// (not a transient quote — the subscription itself is prepaid). The payment is keyed
|
||||||
|
// to the occurrence so the exit gate (#windowOwed − payments) clears.
|
||||||
|
const subWindow = this.#payableSubscriptionWindow(identity);
|
||||||
|
if (subWindow) {
|
||||||
|
const amountMinor = overrideMinor ?? subWindow.dueMinor;
|
||||||
|
await this.#log.append({
|
||||||
|
type: "payment",
|
||||||
|
source: "manual",
|
||||||
|
identity,
|
||||||
|
payload: {
|
||||||
|
sessionRef: identity,
|
||||||
|
amountMinor,
|
||||||
|
currency: subWindow.currency ?? undefined,
|
||||||
|
tender,
|
||||||
|
...(subWindow.tariffVersionId ? { tariffVersionId: subWindow.tariffVersionId } : {}),
|
||||||
|
subscriptionWindowCharge: true,
|
||||||
|
...(overrideMinor != null ? { reason: "operator-set amount", quotedMinor: subWindow.dueMinor } : {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.#logger.info(`subscription window-charge payment ${amountMinor} ${subWindow.currency ?? ""} (${tender}) for ${identity}`);
|
||||||
|
return { amountMinor, currency: subWindow.currency ?? "" };
|
||||||
|
}
|
||||||
|
|
||||||
const q = this.quote(identity);
|
const q = this.quote(identity);
|
||||||
const amountMinor = overrideMinor ?? q.amountMinor;
|
const amountMinor = overrideMinor ?? q.amountMinor;
|
||||||
|
|
||||||
@@ -109,6 +256,270 @@ export class PayStation {
|
|||||||
return { amountMinor, currency: q.currency };
|
return { amountMinor, currency: q.currency };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One-read session view for the booth pay/exit modal: entry/exit times, paid
|
||||||
|
* state, amount owed now, and walk-back-grace status. Read-only — folds the
|
||||||
|
* signed ledger (authoritative). A quote failure (no tariff) leaves amount null
|
||||||
|
* rather than throwing, so the modal can still show the session.
|
||||||
|
*/
|
||||||
|
lookup(identity: string): SessionLookup {
|
||||||
|
const id = identity.trim();
|
||||||
|
const rows = this.#db
|
||||||
|
.select()
|
||||||
|
.from(ledgerEvents)
|
||||||
|
.where(eq(ledgerEvents.identity, id))
|
||||||
|
.orderBy(ledgerEvents.index)
|
||||||
|
.all();
|
||||||
|
const entry = rows.find((r) => r.type === "vehicle_entry");
|
||||||
|
if (!entry) {
|
||||||
|
return {
|
||||||
|
identity: id, found: false, open: false, enteredAt: null, exitedAt: null,
|
||||||
|
paidAt: null, amountMinor: null, currency: null, withinGrace: false, graceExpiresAt: null,
|
||||||
|
overstay: false, subscription: false, subscriptionId: null, subscriptionHolder: null, plate: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// Subscription occurrence? The entry payload carries permit:true + permitId.
|
||||||
|
const entryPl = (entry.payload ?? {}) as { permit?: boolean; permitId?: string };
|
||||||
|
const isSubscription = entryPl.permit === true || entryPl.permitId != null;
|
||||||
|
const subscriptionId = isSubscription ? (entryPl.permitId ?? null) : null;
|
||||||
|
const exitRow = rows.find((r) => r.type === "vehicle_exit");
|
||||||
|
const open = !exitRow;
|
||||||
|
|
||||||
|
let paidAt: string | null = null;
|
||||||
|
let graceExitMin: number | null = null;
|
||||||
|
for (const r of rows) {
|
||||||
|
if (r.type === "payment") {
|
||||||
|
paidAt = r.occurredAt;
|
||||||
|
const p = (r.payload ?? {}) as { graceExitMin?: number };
|
||||||
|
if (typeof p.graceExitMin === "number") graceExitMin = p.graceExitMin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const graceExpiresAt =
|
||||||
|
paidAt && graceExitMin != null ? new Date(Date.parse(paidAt) + graceExitMin * 60_000).toISOString() : null;
|
||||||
|
const withinGrace = graceExpiresAt != null && Date.now() <= Date.parse(graceExpiresAt);
|
||||||
|
|
||||||
|
// Amount owed now (best-effort; null if no tariff resolves). For a TRANSIENT session
|
||||||
|
// it's the running tariff. For a SUBSCRIPTION it's normally null (prepaid) — EXCEPT a
|
||||||
|
// time-window plan can owe an out-of-window TARIFF-BRIDGE charge (early-entry carried
|
||||||
|
// on the entry payload + a live late-exit charge), which the booth must take so the
|
||||||
|
// exit gate clears. See wiki/entities/subscription.md.
|
||||||
|
let amountMinor: number | null = null;
|
||||||
|
let currency: string | null = null;
|
||||||
|
if (open && !isSubscription) {
|
||||||
|
try {
|
||||||
|
const q = this.quote(id);
|
||||||
|
amountMinor = q.amountMinor;
|
||||||
|
currency = q.currency;
|
||||||
|
} catch {
|
||||||
|
/* no active tariff — leave null; modal shows session without a price */
|
||||||
|
}
|
||||||
|
} else if (open && isSubscription) {
|
||||||
|
const w = this.#subscriptionWindowDue(id, subscriptionId);
|
||||||
|
if (w && w.dueMinor > 0) {
|
||||||
|
amountMinor = w.dueMinor;
|
||||||
|
currency = w.currency;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const overstay = open && !isSubscription && paidAt != null && graceExpiresAt != null && !withinGrace;
|
||||||
|
|
||||||
|
return {
|
||||||
|
identity: id, found: true, open,
|
||||||
|
enteredAt: entry.occurredAt, exitedAt: exitRow?.occurredAt ?? null,
|
||||||
|
paidAt, amountMinor, currency, withinGrace, graceExpiresAt, overstay,
|
||||||
|
subscription: isSubscription, subscriptionId,
|
||||||
|
subscriptionHolder: this.#holderOf(subscriptionId),
|
||||||
|
plate: plateForIdentity(this.#db, id)?.plate ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All ACTIVE sessions for the booth list: still-open, OR exited-but-within-grace
|
||||||
|
* (the barrier is unconfirmed, so a paid/exited car is presumed possibly-present
|
||||||
|
* until grace expires). One ledger scan, grouped by identity (cheaper than N
|
||||||
|
* lookups). Sorted by entry time, newest first. Folds the SIGNED ledger
|
||||||
|
* (authoritative — not the sessions projection cache, which can drift).
|
||||||
|
* See wiki/concepts/booth-exit-flow.md.
|
||||||
|
*/
|
||||||
|
activeSessions(): ActiveSession[] {
|
||||||
|
const rows = this.#db.select().from(ledgerEvents).orderBy(ledgerEvents.index).all();
|
||||||
|
|
||||||
|
// Group the relevant events per identity in one pass.
|
||||||
|
type Acc = {
|
||||||
|
enteredAt?: string;
|
||||||
|
source: string | null;
|
||||||
|
exitedAt?: string;
|
||||||
|
paidAt?: string;
|
||||||
|
graceExitMin?: number;
|
||||||
|
subscriptionId?: string | null;
|
||||||
|
};
|
||||||
|
const byId = new Map<string, Acc>();
|
||||||
|
for (const r of rows) {
|
||||||
|
const id = r.identity;
|
||||||
|
if (!id) continue;
|
||||||
|
if (r.type === "vehicle_entry") {
|
||||||
|
const a = byId.get(id) ?? { source: r.source ?? null };
|
||||||
|
a.enteredAt = r.occurredAt;
|
||||||
|
a.source = r.source ?? a.source;
|
||||||
|
// Subscription occurrence? The entry payload carries permit:true + permitId
|
||||||
|
// (the on-chain field). Mark it so the booth never tries to charge it.
|
||||||
|
const pl = (r.payload ?? {}) as { permit?: boolean; permitId?: string };
|
||||||
|
if (pl.permit === true || pl.permitId) a.subscriptionId = pl.permitId ?? null;
|
||||||
|
byId.set(id, a);
|
||||||
|
} else if (r.type === "vehicle_exit") {
|
||||||
|
const a = byId.get(id);
|
||||||
|
if (a) a.exitedAt = r.occurredAt;
|
||||||
|
} else if (r.type === "payment") {
|
||||||
|
const a = byId.get(id);
|
||||||
|
if (a) {
|
||||||
|
a.paidAt = r.occurredAt;
|
||||||
|
const p = (r.payload ?? {}) as { graceExitMin?: number };
|
||||||
|
if (typeof p.graceExitMin === "number") a.graceExitMin = p.graceExitMin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve advisory plates for all candidate identities in ONE device_events scan
|
||||||
|
// (cheaper than one lookup per row).
|
||||||
|
const plates = platesForIdentities(this.#db, byId.keys());
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const out: ActiveSession[] = [];
|
||||||
|
for (const [identity, a] of byId) {
|
||||||
|
if (!a.enteredAt) continue; // no entry → not a real session
|
||||||
|
const open = a.exitedAt == null;
|
||||||
|
const graceExpiresAt =
|
||||||
|
a.paidAt && a.graceExitMin != null
|
||||||
|
? new Date(Date.parse(a.paidAt) + a.graceExitMin * 60_000).toISOString()
|
||||||
|
: null;
|
||||||
|
const withinGrace = graceExpiresAt != null && now <= Date.parse(graceExpiresAt);
|
||||||
|
const paid = a.paidAt != null;
|
||||||
|
|
||||||
|
const isSubscription = a.subscriptionId !== undefined;
|
||||||
|
|
||||||
|
// ACTIVE membership:
|
||||||
|
// - exited + within grace → still shown (barrier unconfirmed, may be present);
|
||||||
|
// - exited + past grace → presumed gone, omitted;
|
||||||
|
// - open + UNPAID → always shown (a car owing money never ages out —
|
||||||
|
// it's genuinely still inside until it pays, however long that takes);
|
||||||
|
// - open + PAID + past grace → OVERSTAY. A paid transient whose walk-back grace
|
||||||
|
// lapsed with no signed vehicle_exit: the car re-parked (a new period) or is
|
||||||
|
// faulty/abandoned — not a system fault, not "stuck". It lingers in occupancy
|
||||||
|
// and owes a fresh period (priced from grace-expiry, see `quote`). We used to
|
||||||
|
// age these out (a silent display filter); now we KEEP them and flag `overstay`
|
||||||
|
// so the operator reconciles via a top-up. The signed log is untouched, and the
|
||||||
|
// barrier never opens for free on these. See booth-exit-flow.md.
|
||||||
|
if (!open && !withinGrace) continue;
|
||||||
|
const overstay =
|
||||||
|
open && paid && !isSubscription && graceExpiresAt != null && !withinGrace;
|
||||||
|
|
||||||
|
// Amount owed now: an open + unpaid TRANSIENT (first stay) OR an OVERSTAY (the new
|
||||||
|
// period's top-up). A subscription is prepaid — never quote/charge it.
|
||||||
|
let amountMinor: number | null = null;
|
||||||
|
let currency: string | null = null;
|
||||||
|
if (open && !isSubscription && (a.paidAt == null || overstay)) {
|
||||||
|
try {
|
||||||
|
const q = this.quote(identity);
|
||||||
|
amountMinor = q.amountMinor;
|
||||||
|
currency = q.currency;
|
||||||
|
} catch {
|
||||||
|
/* no active tariff — leave null */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out.push({
|
||||||
|
identity,
|
||||||
|
source: a.source,
|
||||||
|
enteredAt: a.enteredAt,
|
||||||
|
exitedAt: a.exitedAt ?? null,
|
||||||
|
open,
|
||||||
|
paidAt: a.paidAt ?? null,
|
||||||
|
amountMinor,
|
||||||
|
currency,
|
||||||
|
withinGrace,
|
||||||
|
graceExpiresAt,
|
||||||
|
overstay,
|
||||||
|
subscription: isSubscription,
|
||||||
|
subscriptionId: a.subscriptionId ?? null,
|
||||||
|
subscriptionHolder: this.#holderOf(a.subscriptionId ?? null),
|
||||||
|
plate: plates.get(identity)?.plate ?? null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Newest entry first.
|
||||||
|
out.sort((x, y) => Date.parse(y.enteredAt) - Date.parse(x.enteredAt));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The out-of-window TARIFF-BRIDGE amount a subscriber owes on an OPEN occurrence right
|
||||||
|
* now: the transient cost of the minutes parked OUTSIDE the plan's window over the WHOLE
|
||||||
|
* stay `[entry, now]` (one computation — covers early entry AND late exit without
|
||||||
|
* double-counting), minus whatever they've already paid against the occurrence. null
|
||||||
|
* when the plan has no timeframes / nothing is owed. Single source of truth shared with
|
||||||
|
* the exit gate so the booth quote and the gate agree.
|
||||||
|
*/
|
||||||
|
#subscriptionWindowDue(occurrenceId: string, subscriptionId: string | null): { dueMinor: number; currency: string | null } | null {
|
||||||
|
if (!subscriptionId) return null;
|
||||||
|
const sub = this.#db.select().from(subscriptions).where(eq(subscriptions.id, subscriptionId)).get();
|
||||||
|
if (!sub) return null;
|
||||||
|
|
||||||
|
const rows = this.#db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, occurrenceId)).all();
|
||||||
|
const entryRow = rows.find((r) => r.type === "vehicle_entry");
|
||||||
|
if (!entryRow) return null;
|
||||||
|
|
||||||
|
const owed = windowOwedBetween(this.#db, sub.planVersionId, entryRow.occurredAt, new Date().toISOString());
|
||||||
|
if (!owed) return null;
|
||||||
|
|
||||||
|
let paid = 0;
|
||||||
|
for (const r of rows) {
|
||||||
|
if (r.type !== "payment") continue;
|
||||||
|
const pl = (r.payload ?? {}) as { amountMinor?: number };
|
||||||
|
if (typeof pl.amountMinor === "number") paid += pl.amountMinor;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { dueMinor: owed.amountMinor - paid, currency: owed.currency };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Is this identity an OPEN subscription occurrence that owes a window charge? Returns
|
||||||
|
* the due amount + currency + the tariff version that priced the late-exit charge (for
|
||||||
|
* the payment payload), or null when it's transient / nothing owed. */
|
||||||
|
#payableSubscriptionWindow(
|
||||||
|
identity: string,
|
||||||
|
): { dueMinor: number; currency: string | null; tariffVersionId: string | null } | null {
|
||||||
|
const rows = this.#db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).all();
|
||||||
|
const entry = rows.find((r) => r.type === "vehicle_entry");
|
||||||
|
if (!entry) return null;
|
||||||
|
const ep = (entry.payload ?? {}) as { permit?: boolean; permitId?: string };
|
||||||
|
if (ep.permit !== true && ep.permitId == null) return null; // transient
|
||||||
|
if (rows.some((r) => r.type === "vehicle_exit")) return null; // already out
|
||||||
|
const due = this.#subscriptionWindowDue(identity, ep.permitId ?? null);
|
||||||
|
if (!due || due.dueMinor <= 0) return null;
|
||||||
|
// Tariff version for the payment payload = the one that priced the stay (resolved at
|
||||||
|
// entry inside windowOwedBetween).
|
||||||
|
const owed = windowOwedBetween(this.#db, this.#planVersionOf(ep.permitId ?? null), entry.occurredAt, new Date().toISOString());
|
||||||
|
return { dueMinor: due.dueMinor, currency: due.currency, tariffVersionId: owed?.tariffVersionId ?? null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The planVersionId of a subscription (for resolving its timeframes), or null. */
|
||||||
|
#planVersionOf(subscriptionId: string | null): string | null {
|
||||||
|
if (!subscriptionId) return null;
|
||||||
|
const row = this.#db.select().from(subscriptions).where(eq(subscriptions.id, subscriptionId)).get();
|
||||||
|
return row?.planVersionId ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The subscriber's holder name for a subscription id (for a friendly UI label),
|
||||||
|
* or null. Best-effort: a deleted subscription just yields null. */
|
||||||
|
#holderOf(subscriptionId: string | null): string | null {
|
||||||
|
if (!subscriptionId) return null;
|
||||||
|
try {
|
||||||
|
const row = this.#db.select().from(subscriptions).where(eq(subscriptions.id, subscriptionId)).get();
|
||||||
|
return row?.holderName ?? null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** The vehicle_entry of an OPEN session for this identity (no later exit), or null. */
|
/** The vehicle_entry of an OPEN session for this identity (no later exit), or null. */
|
||||||
#openEntry(identity: string) {
|
#openEntry(identity: string) {
|
||||||
const rows = this.#db
|
const rows = this.#db
|
||||||
|
|||||||
@@ -1,222 +0,0 @@
|
|||||||
import { eq, ledgerEvents, permitCredentials, permitPlates, permits, sessions, type Db, type DeviceRow } from "@parking/db";
|
|
||||||
import { registry, type AccessControlDevice } from "@parking/devices";
|
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
|
||||||
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
|
||||||
import type { EventLog } from "./event-log.js";
|
|
||||||
import { type FlowDirection, type ResolvedRelay } from "./device-resolve.js";
|
|
||||||
import { snapshotAsync } from "./snapshot.js";
|
|
||||||
|
|
||||||
// PERMIT flow: a subscriber identified by card/QR/plate enters/exits without paying.
|
|
||||||
// Reached from the read dispatcher when a read matches a permit (not an open ticket).
|
|
||||||
// See wiki/entities/permit.md.
|
|
||||||
//
|
|
||||||
// Two optional, independent bindings:
|
|
||||||
// - car-count: `maxConcurrent` (default 1, null = unbound) — how many of the
|
|
||||||
// permit's cars may be inside at once; enforced over the session projection.
|
|
||||||
// - plate: optional `plates[]` — when set, a matching plate is an accepted identity
|
|
||||||
// too (card/QR OR plate). When unset, any car may use the permit's card/QR.
|
|
||||||
//
|
|
||||||
// Direction is inferred from session state for THAT car (the read credential value
|
|
||||||
// is the per-car session key): no open session → ENTRY; open session → EXIT. So a
|
|
||||||
// fleet permit can have several cars in at once, each its own session, and
|
|
||||||
// anti-passback falls out (a second "entry" on a car already in becomes its exit).
|
|
||||||
|
|
||||||
export interface PermitMatch {
|
|
||||||
readonly permitId: string;
|
|
||||||
/** The specific credential/plate value read — the per-car session key. */
|
|
||||||
readonly carKey: string;
|
|
||||||
readonly via: "card" | "qr" | "plate";
|
|
||||||
}
|
|
||||||
|
|
||||||
export class PermitFlow {
|
|
||||||
readonly #db: Db;
|
|
||||||
readonly #log: EventLog;
|
|
||||||
readonly #logger: FastifyBaseLogger;
|
|
||||||
readonly #inFlight = new Set<string>();
|
|
||||||
|
|
||||||
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger) {
|
|
||||||
this.#db = db;
|
|
||||||
this.#log = log;
|
|
||||||
this.#logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Resolve a read to a permit (by card/QR credential, or by a bound plate), or null. */
|
|
||||||
match(e: DeviceReadEvent): PermitMatch | null {
|
|
||||||
// Card / QR / generic credential value.
|
|
||||||
const cred = this.#db
|
|
||||||
.select()
|
|
||||||
.from(permitCredentials)
|
|
||||||
.where(eq(permitCredentials.value, e.value))
|
|
||||||
.get();
|
|
||||||
if (cred) {
|
|
||||||
return { permitId: cred.permitId, carKey: e.value, via: cred.kind === "qr" ? "qr" : "card" };
|
|
||||||
}
|
|
||||||
// Plate binding: a read plate that matches a permit's bound plate is an identity.
|
|
||||||
if (e.kind === "plate") {
|
|
||||||
const plate = this.#db.select().from(permitPlates).where(eq(permitPlates.plate, e.value)).get();
|
|
||||||
if (plate) return { permitId: plate.permitId, carKey: e.value, via: "plate" };
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Run the permit entry/exit for a matched read at a barrier. `resolved` is the
|
|
||||||
* reader's bound relay; its direction constrains, "both" defers to session state. */
|
|
||||||
async run(resolved: ResolvedRelay, e: DeviceReadEvent, m: PermitMatch): Promise<ReadOutcome> {
|
|
||||||
const key = `${m.permitId}:${m.carKey}`;
|
|
||||||
if (this.#inFlight.has(key)) return { accepted: false, reason: "duplicate read in flight" };
|
|
||||||
this.#inFlight.add(key);
|
|
||||||
try {
|
|
||||||
return await this.#run(resolved, e, m);
|
|
||||||
} catch (err) {
|
|
||||||
this.#logger.error(`permit-flow failed: ${(err as Error).message}`);
|
|
||||||
return { accepted: false, reason: (err as Error).message };
|
|
||||||
} finally {
|
|
||||||
this.#inFlight.delete(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async #run(resolved: ResolvedRelay, e: DeviceReadEvent, m: PermitMatch): Promise<ReadOutcome> {
|
|
||||||
const permit = this.#db.select().from(permits).where(eq(permits.id, m.permitId)).get();
|
|
||||||
if (!permit) return { accepted: false, reason: "permit not found" };
|
|
||||||
|
|
||||||
// Validity: active + within the coverage window.
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
const invalid =
|
|
||||||
permit.status !== "active" ||
|
|
||||||
(permit.validFrom != null && now < permit.validFrom) ||
|
|
||||||
(permit.validTo != null && now > permit.validTo);
|
|
||||||
if (invalid) {
|
|
||||||
const reason = `permit ${permit.status}/out-of-window`;
|
|
||||||
await this.#reject(m, reason);
|
|
||||||
return { accepted: false, reason };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Direction: the car's open-session state is the natural verb (in→exit, out→entry).
|
|
||||||
// The barrier the car is at (resolved.direction) must AGREE — a car at an exit
|
|
||||||
// barrier that isn't inside (or at an entry barrier while already in) is a
|
|
||||||
// wrong-barrier / anti-passback signal, refused + logged. A "both" barrier follows
|
|
||||||
// the session state.
|
|
||||||
const carOpen = this.#carHasOpenSession(m.carKey);
|
|
||||||
const inferred: FlowDirection = carOpen ? "exit" : "entry";
|
|
||||||
if (resolved.direction !== "both" && resolved.direction !== inferred) {
|
|
||||||
const reason = `permit wrong barrier — ${resolved.direction} barrier but car would ${inferred}`;
|
|
||||||
await this.#reject(m, reason);
|
|
||||||
return { accepted: false, direction: resolved.direction === "exit" ? "exit" : "entry", reason };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (carOpen) {
|
|
||||||
// EXIT: this car is already inside → the read is its exit.
|
|
||||||
await this.#log.append({
|
|
||||||
type: "vehicle_exit",
|
|
||||||
direction: "exit",
|
|
||||||
source: m.via === "plate" ? "lpr" : m.via === "qr" ? "qr" : "wiegand",
|
|
||||||
identity: m.carKey,
|
|
||||||
payload: { sessionRef: m.carKey, permitId: m.permitId },
|
|
||||||
});
|
|
||||||
await this.#open(resolved, "exit", m.carKey, "permit exit");
|
|
||||||
this.#closeCache(m.carKey);
|
|
||||||
return { accepted: true, direction: "exit" };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ENTRY: enforce the car-count binding (maxConcurrent), then sign + open.
|
|
||||||
if (permit.maxConcurrent != null) {
|
|
||||||
const open = this.#permitOpenCount(m.permitId);
|
|
||||||
if (open >= permit.maxConcurrent) {
|
|
||||||
const reason = `permit at capacity (${open}/${permit.maxConcurrent} cars in)`;
|
|
||||||
await this.#reject(m, reason);
|
|
||||||
return { accepted: false, direction: "entry", reason };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.#log.append({
|
|
||||||
type: "vehicle_entry",
|
|
||||||
direction: "entry",
|
|
||||||
source: m.via === "plate" ? "lpr" : m.via === "qr" ? "qr" : "wiegand",
|
|
||||||
identity: m.carKey,
|
|
||||||
// No ticket, no fee — the permit IS the authorization. Recorded for audit.
|
|
||||||
payload: { sessionRef: m.carKey, permitId: m.permitId, permit: true },
|
|
||||||
occurredAt: now,
|
|
||||||
});
|
|
||||||
await this.#open(resolved, "entry", m.carKey, "permit entry");
|
|
||||||
try {
|
|
||||||
this.#db
|
|
||||||
.insert(sessions)
|
|
||||||
.values({ id: m.carKey, identity: m.carKey, source: m.via === "plate" ? "lpr" : "wiegand", permitId: m.permitId, enteredAt: now, state: "open" })
|
|
||||||
.run();
|
|
||||||
} catch (err) {
|
|
||||||
this.#logger.error(`session-cache insert failed for ${m.carKey}: ${(err as Error).message}`);
|
|
||||||
}
|
|
||||||
return { accepted: true, direction: "entry" };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Does this specific car (credential value) have an open session right now? */
|
|
||||||
#carHasOpenSession(carKey: string): boolean {
|
|
||||||
const rows = this.#db
|
|
||||||
.select()
|
|
||||||
.from(ledgerEvents)
|
|
||||||
.where(eq(ledgerEvents.identity, carKey))
|
|
||||||
.orderBy(ledgerEvents.index)
|
|
||||||
.all();
|
|
||||||
const entries = rows.filter((r) => r.type === "vehicle_entry").length;
|
|
||||||
const exits = rows.filter((r) => r.type === "vehicle_exit").length;
|
|
||||||
return entries > exits;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** How many of this permit's cars are inside right now (fold over the ledger). */
|
|
||||||
#permitOpenCount(permitId: string): number {
|
|
||||||
const rows = this.#db
|
|
||||||
.select()
|
|
||||||
.from(ledgerEvents)
|
|
||||||
.where(eq(ledgerEvents.type, "vehicle_entry"))
|
|
||||||
.all()
|
|
||||||
.filter((r) => (r.payload as { permitId?: string } | null)?.permitId === permitId);
|
|
||||||
let open = 0;
|
|
||||||
for (const entry of rows) {
|
|
||||||
if (!this.#carHasOpenSession(entry.identity ?? "")) continue;
|
|
||||||
open += 1;
|
|
||||||
}
|
|
||||||
return open;
|
|
||||||
}
|
|
||||||
|
|
||||||
async #reject(m: PermitMatch, reason: string): Promise<void> {
|
|
||||||
await this.#log.append({
|
|
||||||
type: "anomaly",
|
|
||||||
identity: m.carKey,
|
|
||||||
payload: { reason: `permit refused — ${reason}`, permitId: m.permitId, permitRefused: true },
|
|
||||||
});
|
|
||||||
this.#logger.warn(`permit refused (${m.carKey}): ${reason}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async #open(resolved: ResolvedRelay, dir: FlowDirection, carKey: string, what: string): Promise<void> {
|
|
||||||
const access = this.#buildAccess(resolved.controller);
|
|
||||||
if (access) await access.pulseOpen(resolved.relay);
|
|
||||||
else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`);
|
|
||||||
|
|
||||||
// SNAPSHOT — fire the directional camera(s), never awaited (evidence, not a gate).
|
|
||||||
void snapshotAsync({
|
|
||||||
db: this.#db,
|
|
||||||
direction: dir,
|
|
||||||
identity: carKey,
|
|
||||||
logger: this.#logger,
|
|
||||||
}).catch((err) => this.#logger.error(`permit snapshot error: ${(err as Error).message}`));
|
|
||||||
}
|
|
||||||
|
|
||||||
#closeCache(carKey: string): void {
|
|
||||||
try {
|
|
||||||
this.#db.update(sessions).set({ exitedAt: new Date().toISOString(), state: "closed" }).where(eq(sessions.id, carKey)).run();
|
|
||||||
} catch (err) {
|
|
||||||
this.#logger.error(`session-cache close failed for ${carKey}: ${(err as Error).message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Build a live access adapter from a resolved controller row, or null. */
|
|
||||||
#buildAccess(row: DeviceRow): AccessControlDevice | null {
|
|
||||||
const driver = registry.get(row.driverId);
|
|
||||||
if (!driver) return null;
|
|
||||||
try {
|
|
||||||
return driver.create(row.config as never) as AccessControlDevice;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { and, desc, deviceEvents, eq, type Db } from "@parking/db";
|
||||||
|
|
||||||
|
// READ-TIME plate resolution. A recognized licence plate is ADVISORY evidence — it
|
||||||
|
// lives in the unsigned, prunable `device_events` (kind="read") stream written by the
|
||||||
|
// ANPR-on-snapshot path (snapshot.ts → recognizePlate), keyed to the session `identity`.
|
||||||
|
// It is deliberately NOT on the signed ledger (a fuzzy camera read must never become a
|
||||||
|
// signed fact). To SHOW it next to a feed event or an active session we resolve it here,
|
||||||
|
// at serialize time, the same way subscriber names are resolved (see event-enrich.ts).
|
||||||
|
//
|
||||||
|
// Preference: an ENTRY read over an exit read (the plate as it arrived identifies the
|
||||||
|
// session); within a direction, the newest read wins. Returns the plate text only —
|
||||||
|
// confidence/region detail stays on the snapshot review panel, not the at-a-glance feed.
|
||||||
|
|
||||||
|
/** The best advisory plate observed for a session, for display. */
|
||||||
|
export interface PlateView {
|
||||||
|
readonly plate: string;
|
||||||
|
readonly confidence: number | null;
|
||||||
|
readonly direction: "entry" | "exit" | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ReadDetail {
|
||||||
|
identity?: string;
|
||||||
|
plate?: string;
|
||||||
|
confidence?: number;
|
||||||
|
direction?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Best plate for one identity, or null. Prefers an entry read, then the newest read. */
|
||||||
|
export function plateForIdentity(db: Db, identity: string): PlateView | null {
|
||||||
|
const rows = db
|
||||||
|
.select({ detail: deviceEvents.detail })
|
||||||
|
.from(deviceEvents)
|
||||||
|
.where(and(eq(deviceEvents.category, "camera"), eq(deviceEvents.kind, "read")))
|
||||||
|
.orderBy(desc(deviceEvents.occurredAt))
|
||||||
|
.all();
|
||||||
|
return pickBest(rows.map((r) => (r.detail ?? {}) as ReadDetail), identity);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve plates for MANY identities in one device_events scan (used by the active-
|
||||||
|
* sessions list and the feed page, which each carry tens–hundreds of rows). */
|
||||||
|
export function platesForIdentities(db: Db, identities: Iterable<string>): Map<string, PlateView> {
|
||||||
|
const want = new Set(identities);
|
||||||
|
const out = new Map<string, PlateView>();
|
||||||
|
if (want.size === 0) return out;
|
||||||
|
// Newest first so the first acceptable read per (identity,direction) is the freshest.
|
||||||
|
const rows = db
|
||||||
|
.select({ detail: deviceEvents.detail })
|
||||||
|
.from(deviceEvents)
|
||||||
|
.where(and(eq(deviceEvents.category, "camera"), eq(deviceEvents.kind, "read")))
|
||||||
|
.orderBy(desc(deviceEvents.occurredAt))
|
||||||
|
.all();
|
||||||
|
const byId = new Map<string, ReadDetail[]>();
|
||||||
|
for (const r of rows) {
|
||||||
|
const d = (r.detail ?? {}) as ReadDetail;
|
||||||
|
if (!d.identity || !d.plate || !want.has(d.identity)) continue;
|
||||||
|
let list = byId.get(d.identity);
|
||||||
|
if (!list) byId.set(d.identity, (list = []));
|
||||||
|
list.push(d);
|
||||||
|
}
|
||||||
|
for (const [id, reads] of byId) {
|
||||||
|
const best = pickBest(reads, id);
|
||||||
|
if (best) out.set(id, best);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pick the best read for `identity` from a NEWEST-FIRST list: an entry read beats an
|
||||||
|
* exit read; otherwise the first (newest) acceptable read wins. */
|
||||||
|
function pickBest(reads: ReadDetail[], identity: string): PlateView | null {
|
||||||
|
let fallback: ReadDetail | null = null;
|
||||||
|
for (const d of reads) {
|
||||||
|
if (d.identity !== identity || !d.plate) continue;
|
||||||
|
if (d.direction === "entry") return toView(d);
|
||||||
|
if (!fallback) fallback = d;
|
||||||
|
}
|
||||||
|
return fallback ? toView(fallback) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toView(d: ReadDetail): PlateView {
|
||||||
|
return {
|
||||||
|
plate: d.plate!.trim().toUpperCase(),
|
||||||
|
confidence: typeof d.confidence === "number" ? d.confidence : null,
|
||||||
|
direction: d.direction === "entry" || d.direction === "exit" ? d.direction : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -2,32 +2,32 @@ import { devices, eq, type Db } from "@parking/db";
|
|||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
||||||
import type { ExitFlow } from "./exit-flow.js";
|
import type { ExitFlow } from "./exit-flow.js";
|
||||||
import type { PermitFlow } from "./permit-flow.js";
|
import type { SubscriptionFlow } from "./subscription-flow.js";
|
||||||
import { relayForDevice } from "./device-resolve.js";
|
import { relayForDevice } from "./device-resolve.js";
|
||||||
|
|
||||||
// Routes a credential read (ticket scan / plate / card) to the right flow. A read
|
// Routes a credential read (ticket scan / plate / card) to the right flow. A read
|
||||||
// can mean a permit entry/exit OR a transient exit, so we dispatch by WHAT the
|
// can mean a subscription entry/exit OR a transient exit, so we dispatch by WHAT the
|
||||||
// credential is (decision 2026-06-15):
|
// credential is (decision 2026-06-15):
|
||||||
// - matches a permit (card/QR/bound plate) → PERMIT flow,
|
// - matches a subscription (card/QR/bound plate) → SUBSCRIPTION flow,
|
||||||
// - else → transient EXIT flow (open ticket session → exit, else reject+log).
|
// - else → transient EXIT flow (open ticket session → exit, else reject+log).
|
||||||
//
|
//
|
||||||
// The reader is BOUND to a controller relay (config.controllerId + relay), so a read
|
// The reader is BOUND to a controller relay (config.controllerId + relay), so a read
|
||||||
// resolves to exactly the barrier it sits at, and the direction is inherited from
|
// resolves to exactly the barrier it sits at, and the direction is inherited from
|
||||||
// that relay (see entry-exit-points.md). The resolved relay is handed to the flow so
|
// that relay (see entry-exit-points.md). The resolved relay is handed to the flow so
|
||||||
// it opens that exact barrier. An "entry" reader drives the entry side, an "exit"
|
// it opens that exact barrier. An "entry" reader drives the entry side, an "exit"
|
||||||
// reader the exit side; "both" defers to the flow's own inference (permit: session
|
// reader the exit side; "both" defers to the flow's own inference (subscription:
|
||||||
// state; transient: exit).
|
// session state; transient: exit).
|
||||||
|
|
||||||
export class ReadDispatcher {
|
export class ReadDispatcher {
|
||||||
readonly #db: Db;
|
readonly #db: Db;
|
||||||
readonly #exit: ExitFlow;
|
readonly #exit: ExitFlow;
|
||||||
readonly #permit: PermitFlow;
|
readonly #subscription: SubscriptionFlow;
|
||||||
readonly #logger: FastifyBaseLogger;
|
readonly #logger: FastifyBaseLogger;
|
||||||
|
|
||||||
constructor(db: Db, exit: ExitFlow, permit: PermitFlow, logger: FastifyBaseLogger) {
|
constructor(db: Db, exit: ExitFlow, subscription: SubscriptionFlow, logger: FastifyBaseLogger) {
|
||||||
this.#db = db;
|
this.#db = db;
|
||||||
this.#exit = exit;
|
this.#exit = exit;
|
||||||
this.#permit = permit;
|
this.#subscription = subscription;
|
||||||
this.#logger = logger;
|
this.#logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,13 +41,13 @@ export class ReadDispatcher {
|
|||||||
return { accepted: false, reason: "reader not bound to a barrier (no relay to open)" };
|
return { accepted: false, reason: "reader not bound to a barrier (no relay to open)" };
|
||||||
}
|
}
|
||||||
|
|
||||||
const permit = this.#permit.match(e);
|
const sub = this.#subscription.match(e);
|
||||||
if (permit) {
|
if (sub) {
|
||||||
return this.#permit.run(resolved, e, permit);
|
return this.#subscription.run(resolved, e, sub);
|
||||||
}
|
}
|
||||||
// Not a permit → transient ticket exit. An ENTRY reader can't produce a transient
|
// Not a subscription → transient ticket exit. An ENTRY reader can't produce a
|
||||||
// exit (transient entry is the button flow, not a reader), so reject+log rather
|
// transient exit (transient entry is the button flow, not a reader), so reject+log
|
||||||
// than treat an entry scan as an exit.
|
// rather than treat an entry scan as an exit.
|
||||||
if (resolved.direction === "entry") {
|
if (resolved.direction === "entry") {
|
||||||
return { accepted: false, direction: "entry", reason: "entry reader: no transient entry via reader" };
|
return { accepted: false, direction: "entry", reason: "entry reader: no transient entry via reader" };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import bcrypt from "bcrypt";
|
import bcrypt from "bcrypt";
|
||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance } from "fastify";
|
||||||
import { eq, users, type Db } from "@parking/db";
|
import { eq, roles, users, type Db } from "@parking/db";
|
||||||
import {
|
import {
|
||||||
clearAuthCookies,
|
clearAuthCookies,
|
||||||
newCsrfToken,
|
newCsrfToken,
|
||||||
requireRole,
|
permissionsFor,
|
||||||
|
requireAuth,
|
||||||
setAuthCookies,
|
setAuthCookies,
|
||||||
} from "../auth.js";
|
} from "../auth.js";
|
||||||
|
|
||||||
@@ -16,6 +17,46 @@ interface LoginBody {
|
|||||||
password: string;
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const LANGS = ["sq", "en"] as const;
|
||||||
|
type Lang = (typeof LANGS)[number];
|
||||||
|
interface LanguageBody {
|
||||||
|
language: Lang;
|
||||||
|
}
|
||||||
|
|
||||||
|
const THEMES = ["dark", "light"] as const;
|
||||||
|
type Theme = (typeof THEMES)[number];
|
||||||
|
interface ThemeBody {
|
||||||
|
theme: Theme;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The session shape the SPA bootstraps from: identity + role + its permission
|
||||||
|
* list (so the UI can gate nav/routes) + language. Role NAME is for display; the
|
||||||
|
* permissions are the source of truth. */
|
||||||
|
function sessionView(
|
||||||
|
db: Db,
|
||||||
|
user: {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
roleId: string;
|
||||||
|
language: string;
|
||||||
|
theme: string;
|
||||||
|
fullName?: string | null;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const role = db.select().from(roles).where(eq(roles.id, user.roleId)).get();
|
||||||
|
const permissions = [...permissionsFor(user.roleId)];
|
||||||
|
return {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
roleId: user.roleId,
|
||||||
|
roleName: role?.name ?? user.roleId,
|
||||||
|
permissions,
|
||||||
|
language: user.language,
|
||||||
|
theme: user.theme,
|
||||||
|
fullName: user.fullName ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function authRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
export async function authRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||||
app.post<{ Body: LoginBody }>("/api/auth/login", async (req, reply) => {
|
app.post<{ Body: LoginBody }>("/api/auth/login", async (req, reply) => {
|
||||||
const { username, password } = req.body ?? {};
|
const { username, password } = req.body ?? {};
|
||||||
@@ -33,15 +74,19 @@ export async function authRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const csrf = newCsrfToken();
|
const csrf = newCsrfToken();
|
||||||
// No expiresIn: the token is valid until explicit logout (see auth.ts).
|
// No expiresIn: the token is valid until explicit logout (see auth.ts). The
|
||||||
|
// token carries roleId (not the permission list) — perms resolve per-request,
|
||||||
|
// so a role edit applies immediately with no re-login.
|
||||||
const token = await reply.jwtSign({
|
const token = await reply.jwtSign({
|
||||||
sub: user.id,
|
sub: user.id,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
role: user.role,
|
roleId: user.roleId,
|
||||||
csrf,
|
csrf,
|
||||||
});
|
});
|
||||||
setAuthCookies(reply, token, csrf);
|
setAuthCookies(reply, token, csrf);
|
||||||
return { id: user.id, username: user.username, role: user.role };
|
// `language` is NOT in the JWT (identity/role only) — it's a mutable preference
|
||||||
|
// read from the DB, so changing it needs no token refresh.
|
||||||
|
return sessionView(db, user);
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post("/api/auth/logout", async (_req, reply) => {
|
app.post("/api/auth/logout", async (_req, reply) => {
|
||||||
@@ -49,13 +94,49 @@ export async function authRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
});
|
});
|
||||||
|
|
||||||
// Who am I — used by the SPA to bootstrap session state on load.
|
// Who am I — used by the SPA to bootstrap session state on load. Reads the live
|
||||||
|
// `language` preference from the DB (not the token).
|
||||||
app.get(
|
app.get(
|
||||||
"/api/auth/me",
|
"/api/auth/me",
|
||||||
{ preHandler: requireRole("admin", "operator", "cashier", "readonly") },
|
{ preHandler: requireAuth },
|
||||||
async (req) => {
|
async (req, reply) => {
|
||||||
const { sub, username, role } = req.user;
|
const row = await db.select().from(users).where(eq(users.id, req.user.sub)).get();
|
||||||
return { id: sub, username, role };
|
if (!row) {
|
||||||
|
// The user was deleted while their cookie was still valid — clear it.
|
||||||
|
clearAuthCookies(reply);
|
||||||
|
return reply.code(401).send({ error: "session no longer valid" });
|
||||||
|
}
|
||||||
|
return sessionView(db, row);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Change MY own UI language preference (any signed-in user). Persisted to the
|
||||||
|
// users row so it's restored on the next login, from any booth. See i18n.md.
|
||||||
|
app.put<{ Body: LanguageBody }>(
|
||||||
|
"/api/auth/language",
|
||||||
|
{ preHandler: requireAuth },
|
||||||
|
async (req, reply) => {
|
||||||
|
const language = req.body?.language;
|
||||||
|
if (!language || !LANGS.includes(language)) {
|
||||||
|
return reply.code(400).send({ error: `language must be one of: ${LANGS.join(", ")}` });
|
||||||
|
}
|
||||||
|
await db.update(users).set({ language }).where(eq(users.id, req.user.sub)).run();
|
||||||
|
return { language };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Change MY own UI theme preference (any signed-in user). Persisted to the users
|
||||||
|
// row like `language`, so it's restored on the next login from any booth.
|
||||||
|
app.put<{ Body: ThemeBody }>(
|
||||||
|
"/api/auth/theme",
|
||||||
|
{ preHandler: requireAuth },
|
||||||
|
async (req, reply) => {
|
||||||
|
const theme = req.body?.theme;
|
||||||
|
if (!theme || !THEMES.includes(theme)) {
|
||||||
|
return reply.code(400).send({ error: `theme must be one of: ${THEMES.join(", ")}` });
|
||||||
|
}
|
||||||
|
await db.update(users).set({ theme }).where(eq(users.id, req.user.sub)).run();
|
||||||
|
return { theme };
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { requirePermission } from "../auth.js";
|
||||||
|
import type { DeviceMonitor } from "../device-monitor.js";
|
||||||
|
|
||||||
|
// Unified device-status snapshot for the booth footer. The DeviceMonitor polls all
|
||||||
|
// configured devices (relays/readers/cameras via healthCheck, printers via their
|
||||||
|
// rich readStatus) in the background; this exposes its cache. Live updates ride the
|
||||||
|
// booth WebSocket (kind:"device-status") — this REST route is the initial load /
|
||||||
|
// fallback. Any authenticated role may read (operational, not a setup action).
|
||||||
|
// See wiki/concepts/device-status-monitoring.md, booth-console.md.
|
||||||
|
|
||||||
|
export async function deviceStatusRoutes(
|
||||||
|
app: FastifyInstance,
|
||||||
|
monitor: DeviceMonitor,
|
||||||
|
): Promise<void> {
|
||||||
|
const guard = requirePermission("device:read");
|
||||||
|
|
||||||
|
app.get("/api/devices/status", { preHandler: guard }, async () => ({
|
||||||
|
devices: monitor.snapshot(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance } from "fastify";
|
||||||
import { desc, ledgerEvents, type Db } from "@parking/db";
|
import { and, desc, gte, lte, ledgerEvents, type Db } from "@parking/db";
|
||||||
import { requireRole } from "../auth.js";
|
import type { LedgerEvent } from "@parking/shared";
|
||||||
|
import { requirePermission } from "../auth.js";
|
||||||
|
import { enrichEvents } from "../event-enrich.js";
|
||||||
import type { EventLog } from "../event-log.js";
|
import type { EventLog } from "../event-log.js";
|
||||||
|
|
||||||
// Read access to the append-only signed event log. NO write/update/delete routes
|
// Read access to the append-only signed event log. NO write/update/delete routes
|
||||||
@@ -13,17 +15,38 @@ export async function eventRoutes(
|
|||||||
db: Db,
|
db: Db,
|
||||||
eventLog: EventLog,
|
eventLog: EventLog,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
// Any authenticated role may read the log (it's the audit trail).
|
// Reading the log (the audit trail).
|
||||||
const guard = requireRole("admin", "operator", "cashier", "readonly");
|
const guard = requirePermission("event:read");
|
||||||
|
|
||||||
// Recent events, newest first. `limit` caps the page (default 100, max 1000).
|
// Recent events, newest first. `limit` caps the page (default 100, max 1000).
|
||||||
app.get<{ Querystring: { limit?: string } }>(
|
// Optional `since` (ISO) scopes to events at/after that instant — the booth passes
|
||||||
|
// the current shift's start so the live feed shows ONLY this shift's activity. An
|
||||||
|
// optional `until` (ISO) closes the upper bound — the shift-history screen passes a
|
||||||
|
// selected shift's [start, end] to show just that shift's signed activity log.
|
||||||
|
// (logs are per-shift, not all history). See wiki/concepts/shift.md.
|
||||||
|
app.get<{ Querystring: { limit?: string; since?: string; until?: string } }>(
|
||||||
"/api/events",
|
"/api/events",
|
||||||
{ preHandler: guard },
|
{ preHandler: guard },
|
||||||
async (req) => {
|
async (req) => {
|
||||||
const limit = Math.min(Math.max(Number(req.query.limit) || 100, 1), 1000);
|
const limit = Math.min(Math.max(Number(req.query.limit) || 100, 1), 1000);
|
||||||
const rows = db.select().from(ledgerEvents).orderBy(desc(ledgerEvents.index)).limit(limit).all();
|
const since = (req.query.since ?? "").trim();
|
||||||
return { events: rows };
|
const until = (req.query.until ?? "").trim();
|
||||||
|
const bounds = [
|
||||||
|
since ? gte(ledgerEvents.occurredAt, since) : undefined,
|
||||||
|
until ? lte(ledgerEvents.occurredAt, until) : undefined,
|
||||||
|
].filter(Boolean);
|
||||||
|
const rows = db
|
||||||
|
.select()
|
||||||
|
.from(ledgerEvents)
|
||||||
|
.where(bounds.length ? and(...bounds) : undefined)
|
||||||
|
.orderBy(desc(ledgerEvents.index))
|
||||||
|
.limit(limit)
|
||||||
|
.all();
|
||||||
|
// Attach read-time display fields (subscriber name, advisory plate) without
|
||||||
|
// touching the signed record. One plate scan for the whole page (enrichEvents).
|
||||||
|
// The cast bridges the Drizzle row to the shared LedgerEvent.
|
||||||
|
const events = enrichEvents(db, rows as unknown as LedgerEvent[]);
|
||||||
|
return { events };
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -32,7 +55,7 @@ export async function eventRoutes(
|
|||||||
// reconciliation job / "is the log intact?" check calls.
|
// reconciliation job / "is the log intact?" check calls.
|
||||||
app.get(
|
app.get(
|
||||||
"/api/events/verify",
|
"/api/events/verify",
|
||||||
{ preHandler: requireRole("admin") },
|
{ preHandler: requirePermission("event:read") },
|
||||||
async () => eventLog.verifyChain(),
|
async () => eventLog.verifyChain(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import type { AppLogRecord, ClientLogInput, LogLevel } from "@parking/shared";
|
||||||
|
import { requireAuth, requirePermission } from "../auth.js";
|
||||||
|
import type { LogService } from "../log-service.js";
|
||||||
|
|
||||||
|
// Application/diagnostic logs (app_logs) — see wiki/concepts/app-logs.md. Two ends:
|
||||||
|
// - POST /api/logs : the FRONTEND ships its errors here (failed requests, uncaught
|
||||||
|
// exceptions). Any signed-in user may write (it's their own
|
||||||
|
// browser's diagnostics); CSRF still applies (mutation).
|
||||||
|
// - GET /api/logs : read the store — gated by `log:read` (admin/diagnostic role).
|
||||||
|
// Writes go through the shared LogService (bounded, best-effort, reentrancy-guarded);
|
||||||
|
// the DB sink for BACKEND warn+ is wired at the pino stream, not here.
|
||||||
|
|
||||||
|
const LEVELS: ReadonlySet<string> = new Set(["trace", "debug", "info", "warn", "error", "fatal"]);
|
||||||
|
|
||||||
|
/** Cap a single ingest batch so a misbehaving client can't flood the store. */
|
||||||
|
const MAX_BATCH = 50;
|
||||||
|
|
||||||
|
function isValidEntry(e: unknown): e is ClientLogInput {
|
||||||
|
if (!e || typeof e !== "object") return false;
|
||||||
|
const o = e as Record<string, unknown>;
|
||||||
|
return typeof o.message === "string" && typeof o.level === "string" && LEVELS.has(o.level);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function logRoutes(app: FastifyInstance, logService: LogService): Promise<void> {
|
||||||
|
// INGEST — accept one entry or a small batch ({ entries: [...] }). Returns 204.
|
||||||
|
// Deliberately tolerant: it never 4xx's on a malformed entry (a client erroring
|
||||||
|
// while reporting an error shouldn't get a second error) — invalid items are skipped.
|
||||||
|
app.post<{ Body: ClientLogInput | { entries?: unknown[] } }>(
|
||||||
|
"/api/logs",
|
||||||
|
{ preHandler: requireAuth },
|
||||||
|
async (req, reply) => {
|
||||||
|
const body = req.body as ClientLogInput | { entries?: unknown[] };
|
||||||
|
const raw = Array.isArray((body as { entries?: unknown[] }).entries)
|
||||||
|
? (body as { entries: unknown[] }).entries
|
||||||
|
: [body];
|
||||||
|
const userId = req.user?.sub ?? null;
|
||||||
|
const userAgent = req.headers["user-agent"] ?? null;
|
||||||
|
for (const entry of raw.slice(0, MAX_BATCH)) {
|
||||||
|
if (!isValidEntry(entry)) continue;
|
||||||
|
logService.recordClient(entry, { userId, userAgent });
|
||||||
|
}
|
||||||
|
reply.code(204).send();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// READ — newest first, with optional level/source/since filters + a limit. The
|
||||||
|
// booth Logs viewer calls this. Gated by log:read.
|
||||||
|
app.get<{ Querystring: { limit?: string; level?: string; source?: string; since?: string } }>(
|
||||||
|
"/api/logs",
|
||||||
|
{ preHandler: requirePermission("log:read") },
|
||||||
|
async (req): Promise<{ logs: AppLogRecord[] }> => {
|
||||||
|
const limit = Math.min(Math.max(Number(req.query.limit) || 200, 1), 2000);
|
||||||
|
const level = (req.query.level ?? "").trim();
|
||||||
|
const source = (req.query.source ?? "").trim();
|
||||||
|
const since = (req.query.since ?? "").trim();
|
||||||
|
const logs = logService.query({
|
||||||
|
limit,
|
||||||
|
level: LEVELS.has(level) ? (level as LogLevel) : undefined,
|
||||||
|
source: source === "frontend" || source === "backend" ? source : undefined,
|
||||||
|
since: since || undefined,
|
||||||
|
});
|
||||||
|
return { logs };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,15 +1,22 @@
|
|||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance } from "fastify";
|
||||||
import { requireRole } from "../auth.js";
|
import type { Db } from "@parking/db";
|
||||||
|
import { NoPrinterAvailableError } from "@parking/devices";
|
||||||
|
import { requirePermission } from "../auth.js";
|
||||||
import {
|
import {
|
||||||
NoOpenSessionError,
|
NoOpenSessionError,
|
||||||
NoTariffError,
|
NoTariffError,
|
||||||
type PayStation,
|
type PayStation,
|
||||||
} from "../pay-station.js";
|
} from "../pay-station.js";
|
||||||
|
import type { ExitFlow } from "../exit-flow.js";
|
||||||
|
import { NoShiftOpenError, type ShiftService } from "../shift-service.js";
|
||||||
|
import { printPaymentReceipt } from "../booth-print.js";
|
||||||
|
|
||||||
// Pay-station endpoints (pay-on-foot). The terminal/operator UI quotes a session
|
// Booth endpoints (pay-on-foot): look up a session, quote it, take payment, and —
|
||||||
// then takes payment; the payment becomes a signed ledger event. PCI scope stays
|
// when the booth is at/near the exit — open the barrier. The payment becomes a
|
||||||
// OUT of the app — actual card capture is a standalone P2PE terminal; here `tender`
|
// signed ledger event; PCI scope stays OUT of the app (card capture is a standalone
|
||||||
// just records cash vs. card. See wiki/concepts/tariff.md, parking-session.md, bom.md.
|
// P2PE terminal; `tender` just records cash vs. card). The booth exit reuses the
|
||||||
|
// SAME validation as the reader path — no booth-only bypass admits an unpaid car.
|
||||||
|
// See wiki/concepts/tariff.md, parking-session.md, booth-exit-flow.md, bom.md.
|
||||||
|
|
||||||
interface QuoteQuery {
|
interface QuoteQuery {
|
||||||
identity: string;
|
identity: string;
|
||||||
@@ -20,15 +27,108 @@ interface PayBody {
|
|||||||
/** Operator-set amount (lost ticket / dispute) — overrides the computed fee. */
|
/** Operator-set amount (lost ticket / dispute) — overrides the computed fee. */
|
||||||
overrideMinor?: number;
|
overrideMinor?: number;
|
||||||
}
|
}
|
||||||
|
interface ExitBody {
|
||||||
|
identity: string;
|
||||||
|
}
|
||||||
|
interface VoucherBody {
|
||||||
|
identity: string;
|
||||||
|
}
|
||||||
|
interface ReceiptBody {
|
||||||
|
identity: string;
|
||||||
|
}
|
||||||
|
|
||||||
export async function payRoutes(app: FastifyInstance, payStation: PayStation): Promise<void> {
|
export async function payRoutes(
|
||||||
// Cashier/operator/admin operate the pay station; readonly may not.
|
app: FastifyInstance,
|
||||||
const guard = requireRole("admin", "operator", "cashier");
|
db: Db,
|
||||||
|
payStation: PayStation,
|
||||||
|
exitFlow: ExitFlow,
|
||||||
|
shift: ShiftService,
|
||||||
|
): Promise<void> {
|
||||||
|
// Reads (lookup, active sessions, quote) need session/payment read; the booth
|
||||||
|
// money actions (pay, exit, voucher, receipt, reopen) need payment:create. A
|
||||||
|
// single guard covers the whole booth flow — anyone who takes payment also reads
|
||||||
|
// sessions. Read-only callers (a viewer role) get the reads but not the actions.
|
||||||
|
const guard = requirePermission("payment:create");
|
||||||
|
const readGuard = requirePermission("session:read");
|
||||||
|
|
||||||
|
// Money-path gate: a shift must be open site-wide before any payment/exit/voucher/
|
||||||
|
// re-open is processed, so every taking is attributed to a shift (one operator's
|
||||||
|
// accountability period). Read-only lookups (session/active/quote) stay ungated so
|
||||||
|
// the modal can still DISPLAY the session and prompt the operator to open a shift.
|
||||||
|
// Returns 409 { error, code: "no_shift" } so the UI can show the "open a shift"
|
||||||
|
// prompt rather than a generic failure. See wiki/concepts/shift.md.
|
||||||
|
const requireShift = async (
|
||||||
|
_req: import("fastify").FastifyRequest,
|
||||||
|
reply: import("fastify").FastifyReply,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
shift.requireOpenShift();
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof NoShiftOpenError) {
|
||||||
|
return reply.code(409).send({ error: err.message, code: "no_shift" });
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Active sessions for the booth list: still-open OR exited-but-within-grace
|
||||||
|
// (barrier unconfirmed → a paid/exited car is presumed possibly-present until
|
||||||
|
// grace expires). Read-only. See wiki/concepts/booth-exit-flow.md.
|
||||||
|
app.get("/api/sessions/active", { preHandler: readGuard }, async () => ({
|
||||||
|
sessions: payStation.activeSessions(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Session lookup for the booth pay/exit modal: entry/exit times, paid state,
|
||||||
|
// amount owed now, walk-back-grace status. Read-only (no side effect).
|
||||||
|
app.get<{ Params: { identity: string } }>(
|
||||||
|
"/api/session/:identity",
|
||||||
|
{ preHandler: readGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const identity = (req.params.identity ?? "").trim();
|
||||||
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
||||||
|
return payStation.lookup(identity);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Booth-driven exit: validate (paid + grace, or free entry-grace) THEN sign
|
||||||
|
// vehicle_exit + open the barrier. Maps the discriminated result to HTTP:
|
||||||
|
// - validation reject → 409 with a reason (operator takes payment first),
|
||||||
|
// - exit signed but barrier didn't open → 200 { opened:false } (payment stands;
|
||||||
|
// operator opens manually; an anomaly is already signed),
|
||||||
|
// - clean exit → 200 { opened:true }.
|
||||||
|
app.post<{ Body: ExitBody }>(
|
||||||
|
"/api/exit",
|
||||||
|
{ preHandler: [guard, requireShift] },
|
||||||
|
async (req, reply) => {
|
||||||
|
const identity = (req.body?.identity ?? "").trim();
|
||||||
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
||||||
|
const res = await exitFlow.exitForBooth(identity);
|
||||||
|
if (!res.ok) return reply.code(409).send({ error: res.reason, status: res.status });
|
||||||
|
return reply.code(200).send(res);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Human-intervention barrier re-open for an ACTIVE (paid) session — damaged
|
||||||
|
// ticket / dead scanner / phantom re-close. Re-pulses the exit relay + signs an
|
||||||
|
// anomaly (attributed); NEVER a second vehicle_exit. Refused without a payment
|
||||||
|
// (no-unpaid-bypass). See wiki/concepts/booth-exit-flow.md.
|
||||||
|
app.post<{ Body: ExitBody }>(
|
||||||
|
"/api/barrier/reopen",
|
||||||
|
{ preHandler: [guard, requireShift] },
|
||||||
|
async (req, reply) => {
|
||||||
|
const identity = (req.body?.identity ?? "").trim();
|
||||||
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
||||||
|
const operator = req.user?.username;
|
||||||
|
const res = await exitFlow.reopenBarrier(identity, operator);
|
||||||
|
if (!res.ok) return reply.code(409).send({ error: res.reason });
|
||||||
|
return reply.code(200).send(res);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// Quote: what does this session owe right now? (No side effect.)
|
// Quote: what does this session owe right now? (No side effect.)
|
||||||
app.get<{ Querystring: QuoteQuery }>(
|
app.get<{ Querystring: QuoteQuery }>(
|
||||||
"/api/pay/quote",
|
"/api/pay/quote",
|
||||||
{ preHandler: guard },
|
{ preHandler: readGuard },
|
||||||
async (req, reply) => {
|
async (req, reply) => {
|
||||||
const identity = (req.query.identity ?? "").trim();
|
const identity = (req.query.identity ?? "").trim();
|
||||||
if (!identity) return reply.code(400).send({ error: "identity required" });
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
||||||
@@ -43,7 +143,7 @@ export async function payRoutes(app: FastifyInstance, payStation: PayStation): P
|
|||||||
// Pay: take payment and append the signed `payment` event.
|
// Pay: take payment and append the signed `payment` event.
|
||||||
app.post<{ Body: PayBody }>(
|
app.post<{ Body: PayBody }>(
|
||||||
"/api/pay",
|
"/api/pay",
|
||||||
{ preHandler: guard },
|
{ preHandler: [guard, requireShift] },
|
||||||
async (req, reply) => {
|
async (req, reply) => {
|
||||||
const { identity, tender, overrideMinor } = req.body ?? {};
|
const { identity, tender, overrideMinor } = req.body ?? {};
|
||||||
if (!identity || (tender !== "cash" && tender !== "card")) {
|
if (!identity || (tender !== "cash" && tender !== "card")) {
|
||||||
@@ -60,6 +160,64 @@ export async function payRoutes(app: FastifyInstance, payStation: PayStation): P
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Print an exit voucher (the paid ticket id reprinted as a barcode) on the booth
|
||||||
|
// printer. Used when the booth is far from the exit — the customer self-scans the
|
||||||
|
// voucher at the exit reader, which runs the normal validated exit. Requires the
|
||||||
|
// session to be PAID (no free vouchers for unpaid sessions). See booth-exit-flow.md.
|
||||||
|
app.post<{ Body: VoucherBody }>(
|
||||||
|
"/api/voucher",
|
||||||
|
{ preHandler: [guard, requireShift] },
|
||||||
|
async (req, reply) => {
|
||||||
|
const identity = (req.body?.identity ?? "").trim();
|
||||||
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
||||||
|
const view = payStation.lookup(identity);
|
||||||
|
if (!view.found || !view.open) {
|
||||||
|
return reply.code(404).send({ error: "no open session for ticket" });
|
||||||
|
}
|
||||||
|
if (view.paidAt == null) {
|
||||||
|
return reply.code(409).send({ error: "session not paid — take payment before printing a voucher" });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const printedBy = await printPaymentReceipt(db, identity, { voucher: true }, app.log);
|
||||||
|
return reply.code(200).send({ ok: true, printedBy });
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof NoPrinterAvailableError) {
|
||||||
|
return reply.code(503).send({ error: err.message });
|
||||||
|
}
|
||||||
|
return reply.code(500).send({ error: (err as Error).message });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Print a standalone PAYMENT RECEIPT (transparency: entry/paid/duration/amount,
|
||||||
|
// no barcode) on the booth printer. Used (a) auto, right after a payment when no
|
||||||
|
// voucher is issued, and (b) on-demand "reprint" if the slip jammed. Requires the
|
||||||
|
// session to be PAID. See wiki/concepts/booth-exit-flow.md.
|
||||||
|
app.post<{ Body: ReceiptBody }>(
|
||||||
|
"/api/receipt",
|
||||||
|
{ preHandler: [guard, requireShift] },
|
||||||
|
async (req, reply) => {
|
||||||
|
const identity = (req.body?.identity ?? "").trim();
|
||||||
|
if (!identity) return reply.code(400).send({ error: "identity required" });
|
||||||
|
const view = payStation.lookup(identity);
|
||||||
|
if (!view.found) {
|
||||||
|
return reply.code(404).send({ error: "no session for ticket" });
|
||||||
|
}
|
||||||
|
if (view.paidAt == null) {
|
||||||
|
return reply.code(409).send({ error: "session not paid — nothing to receipt" });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const printedBy = await printPaymentReceipt(db, identity, { voucher: false }, app.log);
|
||||||
|
return reply.code(200).send({ ok: true, printedBy });
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof NoPrinterAvailableError) {
|
||||||
|
return reply.code(503).send({ error: err.message });
|
||||||
|
}
|
||||||
|
return reply.code(500).send({ error: (err as Error).message });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function mapError(reply: import("fastify").FastifyReply, err: unknown) {
|
function mapError(reply: import("fastify").FastifyReply, err: unknown) {
|
||||||
|
|||||||
@@ -1,160 +0,0 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
|
||||||
import type { FastifyInstance } from "fastify";
|
|
||||||
import { eq, permitCredentials, permitPlates, permits, type Db } from "@parking/db";
|
|
||||||
import { requireRole } from "../auth.js";
|
|
||||||
|
|
||||||
// Permit (subscription) admin CRUD. A permit is mutable master data — admins
|
|
||||||
// grant/edit/revoke — but every USE of it is a signed ledger event, so the audit
|
|
||||||
// trail stays append-only (see wiki/entities/permit.md). A permit is an aggregate:
|
|
||||||
// the permit row + its credentials (card/QR) + its bound plates. The API treats them
|
|
||||||
// as one unit (create/update replace the child sets; delete removes all).
|
|
||||||
|
|
||||||
interface Credential {
|
|
||||||
kind: "rf" | "qr";
|
|
||||||
value: string;
|
|
||||||
}
|
|
||||||
interface PermitBody {
|
|
||||||
holderName?: string;
|
|
||||||
contact?: string;
|
|
||||||
/** Car-count binding: cars inside at once. Default 1; null = unbound. */
|
|
||||||
maxConcurrent?: number | null;
|
|
||||||
validFrom?: string | null;
|
|
||||||
validTo?: string | null;
|
|
||||||
status?: "active" | "suspended" | "revoked";
|
|
||||||
credentials?: Credential[];
|
|
||||||
/** Plate binding (optional): bound plates that also serve as identity. */
|
|
||||||
plates?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function permitRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
|
||||||
// Admin manages permits; operator/cashier/readonly may LIST (to look one up).
|
|
||||||
const readGuard = requireRole("admin", "operator", "cashier", "readonly");
|
|
||||||
const writeGuard = requireRole("admin");
|
|
||||||
|
|
||||||
// Validate the body; returns problems (empty = ok). Shared by create + update.
|
|
||||||
function validate(b: PermitBody): string[] {
|
|
||||||
const errs: string[] = [];
|
|
||||||
if (b.maxConcurrent != null) {
|
|
||||||
if (!Number.isInteger(b.maxConcurrent) || b.maxConcurrent < 1) {
|
|
||||||
errs.push("maxConcurrent must be a positive integer, or null for unbound");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (b.status && !["active", "suspended", "revoked"].includes(b.status)) {
|
|
||||||
errs.push("status must be active|suspended|revoked");
|
|
||||||
}
|
|
||||||
for (const c of b.credentials ?? []) {
|
|
||||||
if ((c.kind !== "rf" && c.kind !== "qr") || !c.value?.trim()) {
|
|
||||||
errs.push("each credential needs kind (rf|qr) and a non-empty value");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ((b.credentials?.length ?? 0) === 0 && (b.plates?.length ?? 0) === 0) {
|
|
||||||
errs.push("a permit needs at least one credential or one bound plate (else nothing identifies it)");
|
|
||||||
}
|
|
||||||
return errs;
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadAggregate(id: string) {
|
|
||||||
const permit = db.select().from(permits).where(eq(permits.id, id)).get();
|
|
||||||
if (!permit) return null;
|
|
||||||
const credentials = db.select().from(permitCredentials).where(eq(permitCredentials.permitId, id)).all();
|
|
||||||
const plates = db.select().from(permitPlates).where(eq(permitPlates.permitId, id)).all();
|
|
||||||
return {
|
|
||||||
...permit,
|
|
||||||
credentials: credentials.map((c) => ({ kind: c.kind, value: c.value })),
|
|
||||||
plates: plates.map((p) => p.plate),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Replace a permit's child rows (credentials + plates) from the body.
|
|
||||||
function writeChildren(id: string, b: PermitBody) {
|
|
||||||
db.delete(permitCredentials).where(eq(permitCredentials.permitId, id)).run();
|
|
||||||
db.delete(permitPlates).where(eq(permitPlates.permitId, id)).run();
|
|
||||||
for (const c of b.credentials ?? []) {
|
|
||||||
db.insert(permitCredentials).values({ id: randomUUID(), permitId: id, kind: c.kind, value: c.value.trim() }).run();
|
|
||||||
}
|
|
||||||
for (const p of b.plates ?? []) {
|
|
||||||
if (p.trim()) db.insert(permitPlates).values({ id: randomUUID(), permitId: id, plate: p.trim() }).run();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// List all permits (with their credentials + plates).
|
|
||||||
app.get("/api/permits", { preHandler: readGuard }, async () => {
|
|
||||||
const rows = db.select().from(permits).all();
|
|
||||||
return { permits: rows.map((r) => loadAggregate(r.id)) };
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create a permit.
|
|
||||||
app.post<{ Body: PermitBody }>("/api/permits", { preHandler: writeGuard }, async (req, reply) => {
|
|
||||||
const b = req.body ?? {};
|
|
||||||
const problems = validate(b);
|
|
||||||
if (problems.length) return reply.code(400).send({ error: "invalid permit", problems });
|
|
||||||
const id = randomUUID();
|
|
||||||
db.insert(permits)
|
|
||||||
.values({
|
|
||||||
id,
|
|
||||||
holderName: b.holderName ?? null,
|
|
||||||
contact: b.contact ?? null,
|
|
||||||
maxConcurrent: b.maxConcurrent === undefined ? 1 : b.maxConcurrent,
|
|
||||||
validFrom: b.validFrom ?? null,
|
|
||||||
validTo: b.validTo ?? null,
|
|
||||||
status: b.status ?? "active",
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
writeChildren(id, b);
|
|
||||||
return reply.code(201).send(loadAggregate(id));
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update a permit (replaces fields + child sets).
|
|
||||||
app.put<{ Params: { id: string }; Body: PermitBody }>(
|
|
||||||
"/api/permits/:id",
|
|
||||||
{ preHandler: writeGuard },
|
|
||||||
async (req, reply) => {
|
|
||||||
const existing = db.select().from(permits).where(eq(permits.id, req.params.id)).get();
|
|
||||||
if (!existing) return reply.code(404).send({ error: "permit not found" });
|
|
||||||
const b = req.body ?? {};
|
|
||||||
const problems = validate(b);
|
|
||||||
if (problems.length) return reply.code(400).send({ error: "invalid permit", problems });
|
|
||||||
db.update(permits)
|
|
||||||
.set({
|
|
||||||
holderName: b.holderName ?? null,
|
|
||||||
contact: b.contact ?? null,
|
|
||||||
maxConcurrent: b.maxConcurrent === undefined ? existing.maxConcurrent : b.maxConcurrent,
|
|
||||||
validFrom: b.validFrom ?? null,
|
|
||||||
validTo: b.validTo ?? null,
|
|
||||||
status: b.status ?? existing.status,
|
|
||||||
})
|
|
||||||
.where(eq(permits.id, req.params.id))
|
|
||||||
.run();
|
|
||||||
writeChildren(req.params.id, b);
|
|
||||||
return loadAggregate(req.params.id);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
// Revoke (soft): the common case — keeps the permit + its history, just bars it.
|
|
||||||
// A revoked permit fails the entry check (see permit-flow.ts). Use DELETE only to
|
|
||||||
// fully remove a permit created in error.
|
|
||||||
app.post<{ Params: { id: string } }>(
|
|
||||||
"/api/permits/:id/revoke",
|
|
||||||
{ preHandler: writeGuard },
|
|
||||||
async (req, reply) => {
|
|
||||||
const r = db.update(permits).set({ status: "revoked" }).where(eq(permits.id, req.params.id)).run();
|
|
||||||
if (r.changes === 0) return reply.code(404).send({ error: "permit not found" });
|
|
||||||
return loadAggregate(req.params.id);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
// Hard delete a permit + its child rows. (Past ledger events that reference it
|
|
||||||
// are untouched — the audit trail is append-only and independent of this row.)
|
|
||||||
app.delete<{ Params: { id: string } }>(
|
|
||||||
"/api/permits/:id",
|
|
||||||
{ preHandler: writeGuard },
|
|
||||||
async (req, reply) => {
|
|
||||||
const r = db.delete(permits).where(eq(permits.id, req.params.id)).run();
|
|
||||||
if (r.changes === 0) return reply.code(404).send({ error: "permit not found" });
|
|
||||||
db.delete(permitCredentials).where(eq(permitCredentials.permitId, req.params.id)).run();
|
|
||||||
db.delete(permitPlates).where(eq(permitPlates.permitId, req.params.id)).run();
|
|
||||||
return reply.code(204).send();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance } from "fastify";
|
||||||
import { requireRole } from "../auth.js";
|
import { requirePermission } from "../auth.js";
|
||||||
import { deviceEvents } from "../device-events.js";
|
import { deviceEvents } from "../device-events.js";
|
||||||
import type { PrinterMonitor } from "../printer-monitor.js";
|
import type { PrinterMonitor } from "../printer-monitor.js";
|
||||||
|
|
||||||
@@ -12,7 +12,7 @@ export async function printerRoutes(
|
|||||||
app: FastifyInstance,
|
app: FastifyInstance,
|
||||||
monitor: PrinterMonitor,
|
monitor: PrinterMonitor,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const guard = requireRole("admin", "operator", "cashier", "readonly");
|
const guard = requirePermission("device:read");
|
||||||
|
|
||||||
// Current status of every monitored printer (cached — no device round-trip).
|
// Current status of every monitored printer (cached — no device round-trip).
|
||||||
app.get("/api/printers/status", { preHandler: guard }, async () => ({
|
app.get("/api/printers/status", { preHandler: guard }, async () => ({
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { FastifyInstance } from "fastify";
|
|||||||
import { eq, devices, type Db } from "@parking/db";
|
import { eq, devices, type Db } from "@parking/db";
|
||||||
import type { DeviceReadEvent } from "../device-events.js";
|
import type { DeviceReadEvent } from "../device-events.js";
|
||||||
import type { ReadDispatcher } from "../read-dispatch.js";
|
import type { ReadDispatcher } from "../read-dispatch.js";
|
||||||
|
import type { CredentialCapture } from "../credential-capture.js";
|
||||||
|
|
||||||
// GEE/Dingtian QR reader endpoint. The reader is configured (vendor tool) with our
|
// GEE/Dingtian QR reader endpoint. The reader is configured (vendor tool) with our
|
||||||
// host as its "server"; on each scan it sends an HTTP GET and BEEPS/acts based on
|
// host as its "server"; on each scan it sends an HTTP GET and BEEPS/acts based on
|
||||||
@@ -30,6 +31,7 @@ export async function qrReaderRoutes(
|
|||||||
app: FastifyInstance,
|
app: FastifyInstance,
|
||||||
db: Db,
|
db: Db,
|
||||||
dispatcher: ReadDispatcher,
|
dispatcher: ReadDispatcher,
|
||||||
|
capture: CredentialCapture,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
// Resolve the lane_devices row whose config.serial matches the reader's reported
|
// Resolve the lane_devices row whose config.serial matches the reader's reported
|
||||||
// serial (cjihao). The row id is a normal UUID; the serial is config the admin
|
// serial (cjihao). The row id is a normal UUID; the serial is config the admin
|
||||||
@@ -59,10 +61,19 @@ export async function qrReaderRoutes(
|
|||||||
// Map the reader's serial → its assigned lane_devices row id (the dispatcher
|
// Map the reader's serial → its assigned lane_devices row id (the dispatcher
|
||||||
// resolves the lane from that row). If unassigned, deviceId stays the serial so
|
// resolves the lane from that row). If unassigned, deviceId stays the serial so
|
||||||
// the dispatcher simply finds no lane and rejects (status:0) — never crashes.
|
// the dispatcher simply finds no lane and rejects (status:0) — never crashes.
|
||||||
const deviceId = readerRowIdForSerial(serial) ?? serial;
|
const matchedRowId = readerRowIdForSerial(serial);
|
||||||
|
const deviceId = matchedRowId ?? serial;
|
||||||
|
|
||||||
let accepted = false;
|
let accepted = false;
|
||||||
if (cardid) {
|
if (cardid) {
|
||||||
|
// ENROLLMENT INTERCEPT: if THIS reader is armed for credential capture, grab the
|
||||||
|
// value for the subscription form and do NOT run the access flow (we must not
|
||||||
|
// open a barrier for a card being enrolled). Single-shot — capture auto-disarms.
|
||||||
|
// Reads from the OTHER reader are untouched and dispatch normally below.
|
||||||
|
if (capture.tryConsume(deviceId, cardid)) {
|
||||||
|
app.log.info(`CAPTURE serial=${serial || "?"} device=${matchedRowId ? matchedRowId.slice(0, 8) : "?"} value=${cardid}`);
|
||||||
|
accepted = true; // beep "ok" so the operator knows the card was read
|
||||||
|
} else {
|
||||||
const read: DeviceReadEvent = {
|
const read: DeviceReadEvent = {
|
||||||
driverId: "gee-qr-reader",
|
driverId: "gee-qr-reader",
|
||||||
deviceId,
|
deviceId,
|
||||||
@@ -73,10 +84,18 @@ export async function qrReaderRoutes(
|
|||||||
try {
|
try {
|
||||||
const outcome = await dispatcher.dispatch(read);
|
const outcome = await dispatcher.dispatch(read);
|
||||||
accepted = outcome.accepted;
|
accepted = outcome.accepted;
|
||||||
if (!accepted) app.log.info(`QR ${cardid} rejected: ${outcome.reason ?? "?"}`);
|
// Per-read diagnostic: which reader (serial) sent it, which configured device
|
||||||
|
// it mapped to, and the verdict — so a barrier/serial mismatch is visible in
|
||||||
|
// the logs (e.g. an entry-side scan resolving to the exit relay).
|
||||||
|
app.log.info(
|
||||||
|
`READ serial=${serial || "?"} → device=${matchedRowId ? matchedRowId.slice(0, 8) : "UNASSIGNED"} ` +
|
||||||
|
`card=${cardid} verdict=${accepted ? "ACCEPT" : "REJECT"}${outcome.direction ? ` dir=${outcome.direction}` : ""}` +
|
||||||
|
`${accepted ? "" : ` reason="${outcome.reason ?? "?"}"`}`,
|
||||||
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
app.log.error(`QR dispatch failed for ${cardid}: ${(err as Error).message}`);
|
app.log.error(`QR dispatch failed for ${cardid}: ${(err as Error).message}`);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reply the SDK verdict. status 1 → beep 2× (valid) / 0 → beep 1× (invalid).
|
// Reply the SDK verdict. status 1 → beep 2× (valid) / 0 → beep 1× (invalid).
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { eq, rolePermissions, roles, users, type Db } from "@parking/db";
|
||||||
|
import { ADMIN_ROLE_ID, PERMISSIONS, type Permission } from "@parking/shared";
|
||||||
|
import { bumpPermsCache, permissionsFor, requirePermission } from "../auth.js";
|
||||||
|
|
||||||
|
// Role management (admin). Roles are DATA: an admin composes a role from the
|
||||||
|
// code-defined PERMISSIONS grid (resource:action), and users are assigned one
|
||||||
|
// role. The built-in `admin` role (id ADMIN_ROLE_ID) is PROTECTED — it can't be
|
||||||
|
// edited or deleted and always resolves to every permission in code. Every write
|
||||||
|
// here bumps the in-memory permission cache so changes take effect on the next
|
||||||
|
// request. See @parking/shared PERMISSIONS and ../auth.ts.
|
||||||
|
//
|
||||||
|
// PRIVILEGE-ESCALATION GUARD: `role:update`/`role:create` must NOT let a caller
|
||||||
|
// grant a permission they don't themselves hold — otherwise a non-admin with
|
||||||
|
// `role:*` could edit their own role to add (say) `tariff:update`, or mint a role
|
||||||
|
// that grants admin-equivalent powers, and escalate. So a non-admin caller may
|
||||||
|
// only put permissions they ALREADY hold onto a role. An admin (full set) is
|
||||||
|
// unrestricted, which is the intended behaviour.
|
||||||
|
|
||||||
|
interface RoleBody {
|
||||||
|
name: string;
|
||||||
|
permissions: string[];
|
||||||
|
}
|
||||||
|
interface UpdateBody {
|
||||||
|
name?: string;
|
||||||
|
permissions?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const VALID = new Set<string>(PERMISSIONS);
|
||||||
|
|
||||||
|
/** Validate + dedupe a requested permission list against the code-defined grid. */
|
||||||
|
function cleanPermissions(input: unknown): { ok: true; perms: Permission[] } | { ok: false; bad: string } {
|
||||||
|
if (!Array.isArray(input)) return { ok: false, bad: "permissions must be an array" };
|
||||||
|
const out = new Set<Permission>();
|
||||||
|
for (const p of input) {
|
||||||
|
if (typeof p !== "string" || !VALID.has(p)) return { ok: false, bad: `unknown permission: ${String(p)}` };
|
||||||
|
out.add(p as Permission);
|
||||||
|
}
|
||||||
|
return { ok: true, perms: [...out] };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function roleRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||||
|
const readGuard = requirePermission("role:read");
|
||||||
|
const createGuard = requirePermission("role:create");
|
||||||
|
const updateGuard = requirePermission("role:update");
|
||||||
|
const deleteGuard = requirePermission("role:delete");
|
||||||
|
|
||||||
|
/** A role + its permission list + how many users hold it. */
|
||||||
|
function roleView(roleId: string) {
|
||||||
|
const role = db.select().from(roles).where(eq(roles.id, roleId)).get();
|
||||||
|
if (!role) return null;
|
||||||
|
const perms = db
|
||||||
|
.select({ permission: rolePermissions.permission })
|
||||||
|
.from(rolePermissions)
|
||||||
|
.where(eq(rolePermissions.roleId, roleId))
|
||||||
|
.all()
|
||||||
|
.map((r) => r.permission);
|
||||||
|
const userCount = db.select().from(users).where(eq(users.roleId, roleId)).all().length;
|
||||||
|
// The admin role always reports the full grid (it's enforced in code).
|
||||||
|
return {
|
||||||
|
id: role.id,
|
||||||
|
name: role.name,
|
||||||
|
builtin: role.builtin === 1,
|
||||||
|
permissions: role.id === ADMIN_ROLE_ID ? [...PERMISSIONS] : perms,
|
||||||
|
userCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replace a role's permission rows with `perms` (in a single pass). */
|
||||||
|
function setPermissions(roleId: string, perms: Permission[]): void {
|
||||||
|
db.delete(rolePermissions).where(eq(rolePermissions.roleId, roleId)).run();
|
||||||
|
for (const p of perms) {
|
||||||
|
db.insert(rolePermissions).values({ roleId, permission: p }).run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The full permission grid (for the role-composer checkbox UI) + every role.
|
||||||
|
app.get("/api/roles", { preHandler: readGuard }, async () => {
|
||||||
|
const all = db.select().from(roles).all();
|
||||||
|
return {
|
||||||
|
catalog: PERMISSIONS,
|
||||||
|
roles: all.map((r) => roleView(r.id)).filter((r) => r != null),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Reject any permission in `perms` the caller does not themselves hold — so a
|
||||||
|
* non-admin can't grant privileges beyond their own. Returns the offending
|
||||||
|
* permission, or null if all are within the caller's set. (Admin holds the full
|
||||||
|
* set, so it never trips.) */
|
||||||
|
function escalates(callerRoleId: string, perms: Permission[]): Permission | null {
|
||||||
|
const held = permissionsFor(callerRoleId);
|
||||||
|
return perms.find((p) => !held.has(p)) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a composable role from a name + a permission set.
|
||||||
|
app.post<{ Body: RoleBody }>("/api/roles", { preHandler: createGuard }, async (req, reply) => {
|
||||||
|
const name = (req.body?.name ?? "").trim();
|
||||||
|
if (!name) return reply.code(400).send({ error: "name required" });
|
||||||
|
if (db.select().from(roles).where(eq(roles.name, name)).get()) {
|
||||||
|
return reply.code(409).send({ error: "a role with that name already exists" });
|
||||||
|
}
|
||||||
|
const cleaned = cleanPermissions(req.body?.permissions ?? []);
|
||||||
|
if (!cleaned.ok) return reply.code(400).send({ error: cleaned.bad });
|
||||||
|
const over = escalates(req.user.roleId, cleaned.perms);
|
||||||
|
if (over) return reply.code(403).send({ error: `cannot grant a permission you do not hold: ${over}` });
|
||||||
|
|
||||||
|
const id = randomUUID();
|
||||||
|
db.insert(roles).values({ id, name, builtin: 0 }).run();
|
||||||
|
setPermissions(id, cleaned.perms);
|
||||||
|
bumpPermsCache();
|
||||||
|
return reply.code(201).send(roleView(id));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Edit a role's name and/or permission set. The built-in admin role is locked.
|
||||||
|
app.put<{ Params: { id: string }; Body: UpdateBody }>(
|
||||||
|
"/api/roles/:id",
|
||||||
|
{ preHandler: updateGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const id = req.params.id;
|
||||||
|
const role = db.select().from(roles).where(eq(roles.id, id)).get();
|
||||||
|
if (!role) return reply.code(404).send({ error: "role not found" });
|
||||||
|
if (role.builtin === 1) {
|
||||||
|
return reply.code(409).send({ error: "the built-in admin role cannot be edited" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.body?.name != null) {
|
||||||
|
const name = req.body.name.trim();
|
||||||
|
if (!name) return reply.code(400).send({ error: "name cannot be empty" });
|
||||||
|
const clash = db.select().from(roles).where(eq(roles.name, name)).get();
|
||||||
|
if (clash && clash.id !== id) return reply.code(409).send({ error: "a role with that name already exists" });
|
||||||
|
db.update(roles).set({ name }).where(eq(roles.id, id)).run();
|
||||||
|
}
|
||||||
|
if (req.body?.permissions != null) {
|
||||||
|
const cleaned = cleanPermissions(req.body.permissions);
|
||||||
|
if (!cleaned.ok) return reply.code(400).send({ error: cleaned.bad });
|
||||||
|
const over = escalates(req.user.roleId, cleaned.perms);
|
||||||
|
if (over) return reply.code(403).send({ error: `cannot grant a permission you do not hold: ${over}` });
|
||||||
|
setPermissions(id, cleaned.perms);
|
||||||
|
}
|
||||||
|
bumpPermsCache();
|
||||||
|
return roleView(id);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Delete a role. Refused if it's built-in or any user still holds it.
|
||||||
|
app.delete<{ Params: { id: string } }>(
|
||||||
|
"/api/roles/:id",
|
||||||
|
{ preHandler: deleteGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const id = req.params.id;
|
||||||
|
const role = db.select().from(roles).where(eq(roles.id, id)).get();
|
||||||
|
if (!role) return reply.code(404).send({ error: "role not found" });
|
||||||
|
if (role.builtin === 1) {
|
||||||
|
return reply.code(409).send({ error: "the built-in admin role cannot be deleted" });
|
||||||
|
}
|
||||||
|
const holders = db.select().from(users).where(eq(users.roleId, id)).all().length;
|
||||||
|
if (holders > 0) {
|
||||||
|
return reply.code(409).send({ error: `cannot delete a role still assigned to ${holders} user(s)` });
|
||||||
|
}
|
||||||
|
db.delete(rolePermissions).where(eq(rolePermissions.roleId, id)).run();
|
||||||
|
db.delete(roles).where(eq(roles.id, id)).run();
|
||||||
|
bumpPermsCache();
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
type DeviceCategory,
|
type DeviceCategory,
|
||||||
type DeviceConfig,
|
type DeviceConfig,
|
||||||
} from "@parking/devices";
|
} from "@parking/devices";
|
||||||
import { requireRole } from "../auth.js";
|
import { requirePermission } from "../auth.js";
|
||||||
import { backendIpCandidates, backendIpForDevice, backendPort } from "../net.js";
|
import { backendIpCandidates, backendIpForDevice, backendPort } from "../net.js";
|
||||||
|
|
||||||
// First-run setup API. The admin reads the driver catalog and assigns devices
|
// First-run setup API. The admin reads the driver catalog and assigns devices
|
||||||
@@ -51,12 +51,134 @@ function redactSecrets(config: Record<string, unknown>): Record<string, unknown>
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Result of the device configure pipeline: a ready-to-persist config, or an
|
||||||
|
* HTTP error to send back. Shared by assign (create) and patch (edit). */
|
||||||
|
type ConfigureOutcome =
|
||||||
|
| { config: Record<string, unknown>; warnings: string[] }
|
||||||
|
| { error: { code: number; message: string } };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate + configure a device, returning the config to persist. Runs the same
|
||||||
|
* pipeline for both create and edit: validate the driver config, fix
|
||||||
|
* preconditions, harden (relay password + protocol lockdown), and set up input
|
||||||
|
* push (Digest creds + push URLs). Each step is a device write (the device
|
||||||
|
* reboots on apply). The caller owns the DB row; this never touches the DB.
|
||||||
|
*
|
||||||
|
* `id` is the assignment id (stable across an edit) — it's baked into the push
|
||||||
|
* URL, so editing in place keeps the device pushing to the same path.
|
||||||
|
* `existingConfig` carries forward secrets the client never sees on edit
|
||||||
|
* (push/relay passwords), so a PATCH that omits them doesn't wipe them.
|
||||||
|
*/
|
||||||
|
async function configureDevice(
|
||||||
|
app: FastifyInstance,
|
||||||
|
args: {
|
||||||
|
id: string;
|
||||||
|
driverId: string;
|
||||||
|
config: DeviceConfig;
|
||||||
|
backendIp?: string;
|
||||||
|
existingConfig?: Record<string, unknown>;
|
||||||
|
},
|
||||||
|
): Promise<ConfigureOutcome> {
|
||||||
|
const { id, driverId, config, backendIp, existingConfig } = args;
|
||||||
|
|
||||||
|
// Start from any machine-only secrets already on the row (push/relay passwords
|
||||||
|
// are redacted out of the client's copy, so an edit would otherwise drop them),
|
||||||
|
// then layer the submitted config on top.
|
||||||
|
const fullConfig: Record<string, unknown> = { ...existingConfig, ...config };
|
||||||
|
// The web password the admin typed is a DESIRED value, not a stored fact:
|
||||||
|
// it's passed to the driver (via create(config) below) as the rotation
|
||||||
|
// target, but we do NOT persist it from the form. Only harden()'s VERIFIED
|
||||||
|
// secrets.webPassword gets saved — otherwise a failed rotation would leave
|
||||||
|
// the DB claiming a password the device never accepted (login stays old).
|
||||||
|
delete fullConfig.webPassword;
|
||||||
|
// webPasswordCurrent is an input-only credential (the OLD password used to
|
||||||
|
// authorize the change) — never persist it as typed.
|
||||||
|
delete fullConfig.webPasswordCurrent;
|
||||||
|
// Residual-risk warnings from device hardening (shown to the admin; the
|
||||||
|
// save still succeeds — these are "configured, but note X" advisories).
|
||||||
|
const hardenWarnings: string[] = [];
|
||||||
|
|
||||||
|
let device;
|
||||||
|
try {
|
||||||
|
device = registry.create(driverId, config); // validates required fields
|
||||||
|
} catch (err) {
|
||||||
|
return { error: { code: 400, message: (err as Error).message } };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure the device on save (before persisting, so we don't store a row
|
||||||
|
// for a device we couldn't configure):
|
||||||
|
// 1. fix preconditions (e.g. disable input_link_relay so a button press
|
||||||
|
// doesn't auto-fire its relay — host must decide first),
|
||||||
|
// 2. harden (relay password + disable unused protocol channels), and
|
||||||
|
// 3. set up input push (Digest creds + push URLs).
|
||||||
|
// Each step is a device config write (the device reboots on apply).
|
||||||
|
try {
|
||||||
|
if (hasPreconditions(device)) {
|
||||||
|
const fixed = await device.fixPreconditions();
|
||||||
|
if (!fixed.ok) {
|
||||||
|
const unfixable = fixed.issues.find((i) => !i.fixable);
|
||||||
|
return {
|
||||||
|
error: {
|
||||||
|
code: 502,
|
||||||
|
message: `device precondition not satisfied: ${unfixable?.message ?? fixed.issues[0]?.message}`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isHardenable(device)) {
|
||||||
|
const { secrets, warnings } = await device.harden();
|
||||||
|
Object.assign(fullConfig, secrets); // e.g. relayPassword
|
||||||
|
// Surface residual-risk warnings (e.g. firmware that won't disable the
|
||||||
|
// password-less string protocol) so the admin can act (web-UI step).
|
||||||
|
for (const w of warnings ?? []) {
|
||||||
|
app.log.warn(`harden(${driverId} ${id}): ${w}`);
|
||||||
|
hardenWarnings.push(w);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasPushConfig(device)) {
|
||||||
|
const host = String(config.host ?? "");
|
||||||
|
// Admin-provided backend IP wins; else auto-derive (on-subnet NIC).
|
||||||
|
const pushHost = backendIp ?? backendIpForDevice(host);
|
||||||
|
if (!pushHost) {
|
||||||
|
return {
|
||||||
|
error: {
|
||||||
|
code: 400,
|
||||||
|
message: `cannot determine the backend IP on the device's subnet (${host}). Pick one in setup or set BACKEND_HOST_IP.`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const pushUser = "dingtian";
|
||||||
|
// 24 hex chars = 96 bits. The Dingtian `pass` field caps at 31 chars
|
||||||
|
// (longer is silently truncated → auth mismatch), so keep it short.
|
||||||
|
const pushPassword = randomBytes(12).toString("hex");
|
||||||
|
await device.configureInputPush({
|
||||||
|
host: pushHost,
|
||||||
|
port: backendPort(),
|
||||||
|
pathBase: `/api/devices/${driverId}/${id}/input`,
|
||||||
|
auth: { user: pushUser, password: pushPassword },
|
||||||
|
});
|
||||||
|
fullConfig.pushUser = pushUser;
|
||||||
|
fullConfig.pushPassword = pushPassword;
|
||||||
|
// Record the backend IP the device was told to push to — lets us detect
|
||||||
|
// a later mismatch if the host's IP changes.
|
||||||
|
fullConfig.backendIp = pushHost;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
return { error: { code: 502, message: `device configuration failed: ${(err as Error).message}` } };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { config: fullConfig, warnings: hardenWarnings };
|
||||||
|
}
|
||||||
|
|
||||||
export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||||
registerBuiltinDrivers();
|
registerBuiltinDrivers();
|
||||||
setDeviceLogSink((line) => app.log.info(line));
|
setDeviceLogSink((line) => app.log.info(line));
|
||||||
|
|
||||||
// Setup endpoints require an admin (cookie-based JWT — see ../auth.ts).
|
// Device setup is site administration — it changes which hardware the site runs
|
||||||
const adminGuard = requireRole("admin");
|
// and how readers bind to relays. Gated on site:update. See ../auth.ts.
|
||||||
|
const adminGuard = requirePermission("site:update");
|
||||||
|
|
||||||
// Catalog of selectable drivers per category (no secrets — schema only).
|
// Catalog of selectable drivers per category (no secrets — schema only).
|
||||||
// `discoverable` flags drivers that can scan the LAN; `pushCapable` flags
|
// `discoverable` flags drivers that can scan the LAN; `pushCapable` flags
|
||||||
@@ -166,100 +288,69 @@ export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const id = randomUUID();
|
const id = randomUUID();
|
||||||
const fullConfig: Record<string, unknown> = { ...config };
|
const outcome = await configureDevice(app, { id, driverId, config, backendIp });
|
||||||
// The web password the admin typed is a DESIRED value, not a stored fact:
|
if ("error" in outcome) {
|
||||||
// it's passed to the driver (via create(config) below) as the rotation
|
return reply.code(outcome.error.code).send({ error: outcome.error.message });
|
||||||
// target, but we do NOT persist it from the form. Only harden()'s VERIFIED
|
|
||||||
// secrets.webPassword gets saved — otherwise a failed rotation would leave
|
|
||||||
// the DB claiming a password the device never accepted (login stays old).
|
|
||||||
delete fullConfig.webPassword;
|
|
||||||
// webPasswordCurrent is an input-only credential (the OLD password used to
|
|
||||||
// authorize the change) — never persist it as typed.
|
|
||||||
delete fullConfig.webPasswordCurrent;
|
|
||||||
// Residual-risk warnings from device hardening (shown to the admin; the
|
|
||||||
// save still succeeds — these are "configured, but note X" advisories).
|
|
||||||
const hardenWarnings: string[] = [];
|
|
||||||
|
|
||||||
let device;
|
|
||||||
try {
|
|
||||||
device = registry.create(driverId, config); // validates required fields
|
|
||||||
} catch (err) {
|
|
||||||
return reply.code(400).send({ error: (err as Error).message });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Configure the device on save (before persisting, so we don't store a row
|
|
||||||
// for a device we couldn't configure):
|
|
||||||
// 1. fix preconditions (e.g. disable input_link_relay so a button press
|
|
||||||
// doesn't auto-fire its relay — host must decide first),
|
|
||||||
// 2. harden (relay password + disable unused protocol channels), and
|
|
||||||
// 3. set up input push (Digest creds + push URLs).
|
|
||||||
// Each step is a device config write (the device reboots on apply).
|
|
||||||
try {
|
|
||||||
if (hasPreconditions(device)) {
|
|
||||||
const fixed = await device.fixPreconditions();
|
|
||||||
if (!fixed.ok) {
|
|
||||||
const unfixable = fixed.issues.find((i) => !i.fixable);
|
|
||||||
return reply.code(502).send({
|
|
||||||
error: `device precondition not satisfied: ${unfixable?.message ?? fixed.issues[0]?.message}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isHardenable(device)) {
|
|
||||||
const { secrets, warnings } = await device.harden();
|
|
||||||
Object.assign(fullConfig, secrets); // e.g. relayPassword
|
|
||||||
// Surface residual-risk warnings (e.g. firmware that won't disable the
|
|
||||||
// password-less string protocol) so the admin can act (web-UI step).
|
|
||||||
for (const w of warnings ?? []) {
|
|
||||||
app.log.warn(`harden(${driverId} ${id}): ${w}`);
|
|
||||||
hardenWarnings.push(w);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasPushConfig(device)) {
|
|
||||||
const host = String(config.host ?? "");
|
|
||||||
// Admin-provided backend IP wins; else auto-derive (on-subnet NIC).
|
|
||||||
const pushHost = backendIp ?? backendIpForDevice(host);
|
|
||||||
if (!pushHost) {
|
|
||||||
return reply.code(400).send({
|
|
||||||
error: `cannot determine the backend IP on the device's subnet (${host}). Pick one in setup or set BACKEND_HOST_IP.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const pushUser = "dingtian";
|
|
||||||
// 24 hex chars = 96 bits. The Dingtian `pass` field caps at 31 chars
|
|
||||||
// (longer is silently truncated → auth mismatch), so keep it short.
|
|
||||||
const pushPassword = randomBytes(12).toString("hex");
|
|
||||||
await device.configureInputPush({
|
|
||||||
host: pushHost,
|
|
||||||
port: backendPort(),
|
|
||||||
pathBase: `/api/devices/${driverId}/${id}/input`,
|
|
||||||
auth: { user: pushUser, password: pushPassword },
|
|
||||||
});
|
|
||||||
fullConfig.pushUser = pushUser;
|
|
||||||
fullConfig.pushPassword = pushPassword;
|
|
||||||
// Record the backend IP the device was told to push to — lets us detect
|
|
||||||
// a later mismatch if the host's IP changes.
|
|
||||||
fullConfig.backendIp = pushHost;
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
return reply
|
|
||||||
.code(502)
|
|
||||||
.send({ error: `device configuration failed: ${(err as Error).message}` });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const row = {
|
const row = {
|
||||||
id,
|
id,
|
||||||
category,
|
category,
|
||||||
driverId,
|
driverId,
|
||||||
config: fullConfig,
|
config: outcome.config,
|
||||||
enabled: true,
|
enabled: true,
|
||||||
};
|
};
|
||||||
await db.insert(devices).values(row);
|
await db.insert(devices).values(row);
|
||||||
// Don't echo device secrets back (push Digest password, web-UI login, …).
|
// Don't echo device secrets back (push Digest password, web-UI login, …).
|
||||||
return reply.code(201).send({
|
return reply.code(201).send({
|
||||||
...row,
|
...row,
|
||||||
config: redactSecrets(fullConfig),
|
config: redactSecrets(outcome.config),
|
||||||
...(hardenWarnings.length ? { warnings: hardenWarnings } : {}),
|
...(outcome.warnings.length ? { warnings: outcome.warnings } : {}),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Edit an assigned device in place. Same configure pipeline as assign, but it
|
||||||
|
// UPDATEs the existing row and KEEPS the id — which matters for controllers,
|
||||||
|
// since the id is baked into the device's input-push URL
|
||||||
|
// (/api/devices/:driverId/:id/input). Delete+re-add would mint a new id and
|
||||||
|
// break push until reconfigured; PATCH re-runs harden/push against the same id.
|
||||||
|
// The category and driver are fixed at create time (an edit can't change what
|
||||||
|
// KIND of device a slot is); only config changes. Admin-only.
|
||||||
|
app.patch<{ Params: { id: string }; Body: Omit<AssignBody, "category" | "driverId"> }>(
|
||||||
|
"/api/setup/assign/:id",
|
||||||
|
{ preHandler: adminGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const existing = await db
|
||||||
|
.select()
|
||||||
|
.from(devices)
|
||||||
|
.where(eq(devices.id, req.params.id))
|
||||||
|
.get();
|
||||||
|
if (!existing) return reply.code(404).send({ error: "no such device assignment" });
|
||||||
|
|
||||||
|
const { config, backendIp } = req.body;
|
||||||
|
const outcome = await configureDevice(app, {
|
||||||
|
id: existing.id,
|
||||||
|
driverId: existing.driverId,
|
||||||
|
config,
|
||||||
|
backendIp,
|
||||||
|
// Carry forward machine-only secrets the client never received, so an
|
||||||
|
// edit that omits them doesn't blank out push/relay passwords.
|
||||||
|
existingConfig: existing.config,
|
||||||
|
});
|
||||||
|
if ("error" in outcome) {
|
||||||
|
return reply.code(outcome.error.code).send({ error: outcome.error.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.update(devices).set({ config: outcome.config }).where(eq(devices.id, existing.id));
|
||||||
|
app.log.info(`reconfigured device ${existing.id} (${existing.category}/${existing.driverId})`);
|
||||||
|
return reply.code(200).send({
|
||||||
|
id: existing.id,
|
||||||
|
category: existing.category,
|
||||||
|
driverId: existing.driverId,
|
||||||
|
config: redactSecrets(outcome.config),
|
||||||
|
enabled: existing.enabled,
|
||||||
|
...(outcome.warnings.length ? { warnings: outcome.warnings } : {}),
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,26 +1,136 @@
|
|||||||
|
import bcrypt from "bcrypt";
|
||||||
|
import { eq, users, type Db } from "@parking/db";
|
||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance } from "fastify";
|
||||||
import { requireRole } from "../auth.js";
|
import { requirePermission, roleHasPermissions } from "../auth.js";
|
||||||
import {
|
import {
|
||||||
|
InvalidCashMovementError,
|
||||||
NoOpenShiftError,
|
NoOpenShiftError,
|
||||||
ShiftAlreadyOpenError,
|
ShiftAlreadyOpenError,
|
||||||
type ShiftService,
|
type ShiftService,
|
||||||
} from "../shift-service.js";
|
} from "../shift-service.js";
|
||||||
|
|
||||||
|
interface CashVoucherBody {
|
||||||
|
/** Direction is the document TYPE, not a sign: cash_in = Mandat Arkëtimi (pay-IN),
|
||||||
|
* cash_out = Mandat Pagese (pay-OUT). */
|
||||||
|
type: "cash_in" | "cash_out";
|
||||||
|
/** POSITIVE minor units (magnitude). The direction comes from `type`. */
|
||||||
|
amountMinor: number;
|
||||||
|
reason?: string;
|
||||||
|
currency?: string;
|
||||||
|
/** The admin who authorizes this voucher (operator-raised / admin-authorized). */
|
||||||
|
authorizedBy: string;
|
||||||
|
/** That admin's password — re-entered to sign off on the drawer movement. */
|
||||||
|
authorizerPassword: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ShiftsQuery {
|
||||||
|
/** Filter to one operator (admin-only; non-admins are forced to themselves). */
|
||||||
|
operator?: string;
|
||||||
|
/** ISO window over shift START time. */
|
||||||
|
from?: string;
|
||||||
|
to?: string;
|
||||||
|
}
|
||||||
|
|
||||||
// Shift endpoints (manned mode). The operator is the logged-in user; a shift is
|
// 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
|
// 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.
|
// local-jwt-auth.md "until logout"). End Shift signs a shift_z_report + prints it.
|
||||||
|
|
||||||
export async function shiftRoutes(app: FastifyInstance, shift: ShiftService): Promise<void> {
|
export async function shiftRoutes(app: FastifyInstance, shift: ShiftService, db: Db): Promise<void> {
|
||||||
// Cashier/operator/admin run shifts; readonly can't.
|
// Reading the shift state vs. opening/closing one's own shift.
|
||||||
const guard = requireRole("admin", "operator", "cashier");
|
const readGuard = requirePermission("shift:read");
|
||||||
|
const guard = requirePermission("shift:create");
|
||||||
|
|
||||||
// Is the current operator's shift open? (For the UI to show Start vs. End.)
|
// The SITE-WIDE shift state (at most one shift open at a time). The UI uses this
|
||||||
app.get("/api/shift/current", { preHandler: guard }, async (req) => {
|
// to render the header control: no shift → "Open"; my shift → "Close" (enabled);
|
||||||
const operator = req.user.username;
|
// someone else's shift → disabled. Also returns the live drawer balance.
|
||||||
const open = shift.openShiftFor(operator);
|
// - open: the open shift { startedAt, operator } or null (site-wide)
|
||||||
return { operator, open: open ? { startedAt: open.occurredAt } : null };
|
// - 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 heldBy = open?.identity ?? null;
|
||||||
|
const drawer = shift.drawerBalance();
|
||||||
|
return {
|
||||||
|
operator: me,
|
||||||
|
open: open ? { startedAt: open.occurredAt, operator: heldBy } : null,
|
||||||
|
isMine: open != null && heldBy === me,
|
||||||
|
drawerMinor: drawer.balanceMinor,
|
||||||
|
currency: drawer.currency,
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 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();
|
||||||
|
if (!report) return reply.code(204).send();
|
||||||
|
return report;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Completed shift history. SCOPED by permission:
|
||||||
|
// - `shift:read` (operators) → own shifts only; operator/from/to params ignored.
|
||||||
|
// - `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) => {
|
||||||
|
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 });
|
||||||
|
return { shifts, scope: canSeeAll ? "all" : "self" };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Drawer cash VOUCHER — Mandat Arkëtimi (cash_in / pay-IN) or Mandat Pagese
|
||||||
|
// (cash_out / pay-OUT). The direction is the document TYPE, not a signed amount.
|
||||||
|
// OPERATOR-RAISED, ADMIN-AUTHORIZED: any holder of `shift:create` (operator-grade)
|
||||||
|
// may RAISE the voucher, but it only commits if `authorizedBy` is a real admin
|
||||||
|
// (`shift:cash`) who re-enters their password. This keeps the float control —
|
||||||
|
// an operator cannot move the float alone — while letting them raise the slip.
|
||||||
|
// See wiki/concepts/shift.md.
|
||||||
|
app.post<{ Body: CashVoucherBody }>(
|
||||||
|
"/api/cash-voucher",
|
||||||
|
{ preHandler: guard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const b = req.body ?? ({} as CashVoucherBody);
|
||||||
|
if (b.type !== "cash_in" && b.type !== "cash_out") {
|
||||||
|
return reply.code(400).send({ error: "type must be cash_in or cash_out" });
|
||||||
|
}
|
||||||
|
const authName = (b.authorizedBy ?? "").trim();
|
||||||
|
if (!authName || !b.authorizerPassword) {
|
||||||
|
return reply.code(400).send({ error: "authorizedBy and authorizerPassword are required" });
|
||||||
|
}
|
||||||
|
// Verify the authorizer: a real user, admin-grade (shift:cash), correct password.
|
||||||
|
const authUser = await db.select().from(users).where(eq(users.username, authName)).get();
|
||||||
|
// Always run a bcrypt compare (constant-time wrt whether the user exists).
|
||||||
|
const hash = authUser?.passwordHash ?? "$2b$10$invalidinvalidinvalidinvalidinvalidinvalidinv";
|
||||||
|
const passwordOk = await bcrypt.compare(b.authorizerPassword, hash);
|
||||||
|
const isAdminGrade = authUser != null && roleHasPermissions(authUser.roleId, ["shift:cash"]);
|
||||||
|
if (!authUser || !passwordOk || !isAdminGrade) {
|
||||||
|
return reply.code(403).send({ error: "authorizer must be an admin with a correct password" });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await shift.recordVoucher({
|
||||||
|
type: b.type,
|
||||||
|
operator: req.user.username, // who RAISED it
|
||||||
|
authorizedBy: authUser.username, // who signed off (canonical case)
|
||||||
|
amountMinor: b.amountMinor,
|
||||||
|
reason: b.reason ?? "",
|
||||||
|
currency: b.currency,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof InvalidCashMovementError) return reply.code(400).send({ error: err.message });
|
||||||
|
return reply.code(500).send({ error: (err as Error).message });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
app.post("/api/shift/open", { preHandler: guard }, async (req, reply) => {
|
app.post("/api/shift/open", { preHandler: guard }, async (req, reply) => {
|
||||||
try {
|
try {
|
||||||
return await shift.open(req.user.username);
|
return await shift.open(req.user.username);
|
||||||
|
|||||||
@@ -1,43 +1,123 @@
|
|||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance } from "fastify";
|
||||||
import { eq, siteConfig, type Db } from "@parking/db";
|
import { eq, siteConfig, type Db } from "@parking/db";
|
||||||
import { requireRole } from "../auth.js";
|
import { requirePermission } from "../auth.js";
|
||||||
import { getOccupancy } from "../occupancy.js";
|
import { getOccupancy } from "../occupancy.js";
|
||||||
|
|
||||||
// Site config (capacity) + live occupancy. Occupancy is a fold over the signed
|
// Site config (capacity) + live occupancy. Occupancy is a fold over the signed
|
||||||
// ledger; capacity is an admin-set knob. The FULL gate (refuse transient entry at
|
// ledger; capacity is an admin-set knob. The FULL gate (refuse transient entry at
|
||||||
// capacity) lives in the entry flow. See wiki/concepts/capacity-occupancy.md.
|
// capacity) lives in the entry flow. See wiki/concepts/capacity-occupancy.md.
|
||||||
|
|
||||||
interface SiteConfigBody {
|
// Optional park-metadata text fields (all nullable). Trimmed; "" → null.
|
||||||
|
const TEXT_FIELDS = [
|
||||||
|
"parkName",
|
||||||
|
"operatorName",
|
||||||
|
"nius",
|
||||||
|
"address",
|
||||||
|
"phone",
|
||||||
|
"email",
|
||||||
|
// IANA timezone for tariff wall-clock windows (copied into each published version).
|
||||||
|
"timezone",
|
||||||
|
// Default vehicle/customer category frozen onto each transient entry.
|
||||||
|
"defaultVehicleCategory",
|
||||||
|
] as const;
|
||||||
|
type TextField = (typeof TEXT_FIELDS)[number];
|
||||||
|
|
||||||
|
interface SiteConfigBody extends Partial<Record<TextField, string | null>> {
|
||||||
/** Nominal capacity; null = no limit. */
|
/** Nominal capacity; null = no limit. */
|
||||||
|
capacity?: number | null;
|
||||||
|
/** Default for the booth "print exit ticket" checkbox (booth-geography knob). */
|
||||||
|
exitVoucherDefault?: boolean;
|
||||||
|
/** Site default monthly subscription price in minor units (pre-fills the form). */
|
||||||
|
subscriptionMonthlyPriceMinor?: number | null;
|
||||||
|
/** Reserve a spot in occupancy for each active subscriber's car(s), even when not
|
||||||
|
* parked — so transients see "full" sooner and the subscriber's spot is held. */
|
||||||
|
reserveSubscriberSpots?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Shape returned by GET/PUT: capacity + the booth flag + the subscription default
|
||||||
|
* + every metadata field. */
|
||||||
|
type SiteConfig = {
|
||||||
capacity: number | null;
|
capacity: number | null;
|
||||||
|
exitVoucherDefault: boolean;
|
||||||
|
subscriptionMonthlyPriceMinor: number | null;
|
||||||
|
reserveSubscriberSpots: boolean;
|
||||||
|
} & Record<TextField, string | null>;
|
||||||
|
|
||||||
|
function toSiteConfig(row: typeof siteConfig.$inferSelect | undefined): SiteConfig {
|
||||||
|
const out = {
|
||||||
|
capacity: row?.capacity ?? null,
|
||||||
|
exitVoucherDefault: row?.exitVoucherDefault ?? false,
|
||||||
|
subscriptionMonthlyPriceMinor: row?.subscriptionMonthlyPriceMinor ?? null,
|
||||||
|
reserveSubscriberSpots: row?.reserveSubscriberSpots ?? false,
|
||||||
|
} as SiteConfig;
|
||||||
|
for (const f of TEXT_FIELDS) out[f] = row?.[f] ?? null;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Trim a text field; empty string becomes null so blank input clears it. */
|
||||||
|
function normText(v: unknown): string | null {
|
||||||
|
if (v == null) return null;
|
||||||
|
const s = String(v).trim();
|
||||||
|
return s === "" ? null : s;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function siteRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
export async function siteRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||||
const readGuard = requireRole("admin", "operator", "cashier", "readonly");
|
const readGuard = requirePermission("site:read");
|
||||||
const writeGuard = requireRole("admin");
|
const writeGuard = requirePermission("site:update");
|
||||||
|
|
||||||
// Live occupancy: cars inside, capacity, free, full. Any signed-in role.
|
// Live occupancy: cars inside, capacity, free, full. Any signed-in role.
|
||||||
app.get("/api/occupancy", { preHandler: readGuard }, async () => getOccupancy(db));
|
app.get("/api/occupancy", { preHandler: readGuard }, async () => getOccupancy(db));
|
||||||
|
|
||||||
// Read site config (capacity).
|
// Read site config (capacity + park metadata).
|
||||||
app.get("/api/site-config", { preHandler: readGuard }, async () => {
|
app.get("/api/site-config", { preHandler: readGuard }, async () => {
|
||||||
const row = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
const row = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||||
return { capacity: row?.capacity ?? null };
|
return toSiteConfig(row);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Set capacity (admin). null or 0+ integer.
|
// Set site config (admin). Capacity: null or 0+ integer. Metadata: optional text
|
||||||
|
// (only the fields PRESENT in the body are updated; absent fields are untouched).
|
||||||
app.put<{ Body: SiteConfigBody }>("/api/site-config", { preHandler: writeGuard }, async (req, reply) => {
|
app.put<{ Body: SiteConfigBody }>("/api/site-config", { preHandler: writeGuard }, async (req, reply) => {
|
||||||
const { capacity } = req.body ?? ({} as SiteConfigBody);
|
const body = req.body ?? ({} as SiteConfigBody);
|
||||||
if (capacity != null && (!Number.isInteger(capacity) || capacity < 0)) {
|
|
||||||
return reply.code(400).send({ error: "capacity must be a non-negative integer or null" });
|
const patch: Partial<typeof siteConfig.$inferInsert> = {};
|
||||||
|
if ("capacity" in body) {
|
||||||
|
const c = body.capacity;
|
||||||
|
if (c != null && (!Number.isInteger(c) || c < 0)) {
|
||||||
|
return reply.code(400).send({ error: "capacity must be a non-negative integer or null" });
|
||||||
|
}
|
||||||
|
patch.capacity = c ?? null;
|
||||||
}
|
}
|
||||||
|
if ("exitVoucherDefault" in body) {
|
||||||
|
if (typeof body.exitVoucherDefault !== "boolean") {
|
||||||
|
return reply.code(400).send({ error: "exitVoucherDefault must be a boolean" });
|
||||||
|
}
|
||||||
|
patch.exitVoucherDefault = body.exitVoucherDefault;
|
||||||
|
}
|
||||||
|
if ("subscriptionMonthlyPriceMinor" in body) {
|
||||||
|
const p = body.subscriptionMonthlyPriceMinor;
|
||||||
|
if (p != null && (!Number.isInteger(p) || p < 0)) {
|
||||||
|
return reply.code(400).send({ error: "subscriptionMonthlyPriceMinor must be a non-negative integer or null" });
|
||||||
|
}
|
||||||
|
patch.subscriptionMonthlyPriceMinor = p ?? null;
|
||||||
|
}
|
||||||
|
if ("reserveSubscriberSpots" in body) {
|
||||||
|
if (typeof body.reserveSubscriberSpots !== "boolean") {
|
||||||
|
return reply.code(400).send({ error: "reserveSubscriberSpots must be a boolean" });
|
||||||
|
}
|
||||||
|
patch.reserveSubscriberSpots = body.reserveSubscriberSpots;
|
||||||
|
}
|
||||||
|
for (const f of TEXT_FIELDS) {
|
||||||
|
if (f in body) patch[f] = normText(body[f]);
|
||||||
|
}
|
||||||
|
|
||||||
const existing = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
const existing = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||||
const updatedAt = new Date().toISOString();
|
const updatedAt = new Date().toISOString();
|
||||||
if (existing) {
|
if (existing) {
|
||||||
db.update(siteConfig).set({ capacity: capacity ?? null, updatedAt }).where(eq(siteConfig.id, 1)).run();
|
db.update(siteConfig).set({ ...patch, updatedAt }).where(eq(siteConfig.id, 1)).run();
|
||||||
} else {
|
} else {
|
||||||
db.insert(siteConfig).values({ id: 1, capacity: capacity ?? null, updatedAt }).run();
|
db.insert(siteConfig).values({ id: 1, ...patch, updatedAt }).run();
|
||||||
}
|
}
|
||||||
return { capacity: capacity ?? null };
|
const row = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||||
|
return toSiteConfig(row);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance } from "fastify";
|
||||||
import { desc, eq, snapshots, type Db } from "@parking/db";
|
import { and, desc, eq, deviceEvents, snapshots, type Db } from "@parking/db";
|
||||||
import { requireRole } from "../auth.js";
|
import { requirePermission } from "../auth.js";
|
||||||
|
|
||||||
// Read access to captured entry/exit snapshots (the BLOB-in-DB image store, see
|
// Read access to captured entry/exit snapshots (the BLOB-in-DB image store, see
|
||||||
// packages/db schema + wiki/concepts/lane-direction.md). Snapshots are evidence
|
// packages/db schema + wiki/concepts/lane-direction.md). Snapshots are evidence
|
||||||
@@ -9,14 +9,18 @@ import { requireRole } from "../auth.js";
|
|||||||
// never via the API.
|
// never via the API.
|
||||||
|
|
||||||
export async function snapshotRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
export async function snapshotRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||||
const guard = requireRole("admin", "operator", "cashier", "readonly");
|
const guard = requirePermission("session:read");
|
||||||
|
|
||||||
// Snapshot metadata for one session/credential identity (NOT the bytes), newest
|
// Snapshot metadata for one session/credential identity (NOT the bytes), newest
|
||||||
// first — lets the UI show "entry/exit image" links beside an event.
|
// first — lets the UI show "entry/exit image" links beside an event. We also return
|
||||||
|
// FAILED capture attempts (from snapshot telemetry) so the operator can tell a
|
||||||
|
// camera that was offline from a direction that simply has no camera — otherwise a
|
||||||
|
// missing shot is a silent gap. See snapshot.ts (recordFailure).
|
||||||
app.get<{ Params: { identity: string } }>(
|
app.get<{ Params: { identity: string } }>(
|
||||||
"/api/snapshots/by-identity/:identity",
|
"/api/snapshots/by-identity/:identity",
|
||||||
{ preHandler: guard },
|
{ preHandler: guard },
|
||||||
async (req) => {
|
async (req) => {
|
||||||
|
const identity = req.params.identity;
|
||||||
const rows = db
|
const rows = db
|
||||||
.select({
|
.select({
|
||||||
id: snapshots.id,
|
id: snapshots.id,
|
||||||
@@ -27,10 +31,81 @@ export async function snapshotRoutes(app: FastifyInstance, db: Db): Promise<void
|
|||||||
capturedAt: snapshots.capturedAt,
|
capturedAt: snapshots.capturedAt,
|
||||||
})
|
})
|
||||||
.from(snapshots)
|
.from(snapshots)
|
||||||
.where(eq(snapshots.identity, req.params.identity))
|
.where(eq(snapshots.identity, identity))
|
||||||
.orderBy(desc(snapshots.capturedAt))
|
.orderBy(desc(snapshots.capturedAt))
|
||||||
.all();
|
.all();
|
||||||
return { snapshots: rows };
|
|
||||||
|
// Failed attempts: kind="snapshot" telemetry whose detail.identity matches and
|
||||||
|
// detail.ok === false. There may be both a failure and (on a retry) a success
|
||||||
|
// for the same direction; we keep only failures with NO successful shot in the
|
||||||
|
// same direction, so a recovered capture doesn't show a stale warning.
|
||||||
|
const haveDir = new Set<string | null>(rows.map((r) => r.direction));
|
||||||
|
const telemetry = db
|
||||||
|
.select({ detail: deviceEvents.detail, deviceId: deviceEvents.deviceId, occurredAt: deviceEvents.occurredAt })
|
||||||
|
.from(deviceEvents)
|
||||||
|
.where(and(eq(deviceEvents.category, "camera"), eq(deviceEvents.kind, "snapshot")))
|
||||||
|
.orderBy(desc(deviceEvents.occurredAt))
|
||||||
|
.all();
|
||||||
|
const failures: {
|
||||||
|
direction: "entry" | "exit" | null;
|
||||||
|
deviceId: string;
|
||||||
|
error: string;
|
||||||
|
occurredAt: string;
|
||||||
|
}[] = [];
|
||||||
|
const seenFailDir = new Set<string>();
|
||||||
|
for (const row of telemetry) {
|
||||||
|
const d = (row.detail ?? {}) as { identity?: string; ok?: boolean; error?: string; direction?: string };
|
||||||
|
if (d.identity !== identity || d.ok !== false) continue;
|
||||||
|
const dir = d.direction === "entry" || d.direction === "exit" ? d.direction : null;
|
||||||
|
const dirKey = dir ?? "both";
|
||||||
|
if (haveDir.has(dir) || seenFailDir.has(dirKey)) continue; // a success exists, or already shown
|
||||||
|
seenFailDir.add(dirKey);
|
||||||
|
failures.push({
|
||||||
|
direction: dir,
|
||||||
|
deviceId: row.deviceId ?? "",
|
||||||
|
error: d.error ?? "capture failed",
|
||||||
|
occurredAt: row.occurredAt ?? "",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recognized PLATES for this session: kind="read" telemetry from the ANPR-on-
|
||||||
|
// snapshot path (snapshot.ts → recognizePlate). Advisory — a record of the plate
|
||||||
|
// observed for the session, shown beside the image. Newest first.
|
||||||
|
const plateRows = db
|
||||||
|
.select({ detail: deviceEvents.detail, occurredAt: deviceEvents.occurredAt })
|
||||||
|
.from(deviceEvents)
|
||||||
|
.where(and(eq(deviceEvents.category, "camera"), eq(deviceEvents.kind, "read")))
|
||||||
|
.orderBy(desc(deviceEvents.occurredAt))
|
||||||
|
.all();
|
||||||
|
const plates: {
|
||||||
|
plate: string;
|
||||||
|
confidence: number | null;
|
||||||
|
region: string | null;
|
||||||
|
direction: "entry" | "exit" | null;
|
||||||
|
snapshotId: string | null;
|
||||||
|
at: string;
|
||||||
|
}[] = [];
|
||||||
|
for (const row of plateRows) {
|
||||||
|
const d = (row.detail ?? {}) as {
|
||||||
|
identity?: string;
|
||||||
|
plate?: string;
|
||||||
|
confidence?: number;
|
||||||
|
region?: string | null;
|
||||||
|
direction?: string;
|
||||||
|
snapshotId?: string;
|
||||||
|
};
|
||||||
|
if (d.identity !== identity || !d.plate) continue;
|
||||||
|
plates.push({
|
||||||
|
plate: d.plate,
|
||||||
|
confidence: typeof d.confidence === "number" ? d.confidence : null,
|
||||||
|
region: d.region ?? null,
|
||||||
|
direction: d.direction === "entry" || d.direction === "exit" ? d.direction : null,
|
||||||
|
snapshotId: d.snapshotId ?? null,
|
||||||
|
at: row.occurredAt ?? "",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { snapshots: rows, failures, plates };
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { desc, eq, subscriptionPlans, subscriptions, type Db } from "@parking/db";
|
||||||
|
import { SUBSCRIPTION_PERIODS, type PlanTimeframes, type SubscriptionPeriod } from "@parking/shared";
|
||||||
|
import { requirePermission } from "../auth.js";
|
||||||
|
import { siteTz } from "../subscription-window.js";
|
||||||
|
|
||||||
|
// Subscription PLAN catalog — admin-composed, versioned config the operator SELLS
|
||||||
|
// from (so they never type a price). Mirrors the tariff composer: plans are
|
||||||
|
// EFFECTIVE-DATED IMMUTABLE VERSIONS keyed by a stable `planId`; editing a plan
|
||||||
|
// PUBLISHES A NEW VERSION (new row, new effectiveFrom), never mutates an old one, so
|
||||||
|
// a past sale reprices identically against its recorded planVersionId. Retire =
|
||||||
|
// active=0 (soft, keeps history). Admin-only (`subscription:plan`); selling stays
|
||||||
|
// operator-grade (`subscription:create`). See wiki/entities/subscription.md.
|
||||||
|
|
||||||
|
interface PlanBody {
|
||||||
|
/** Stable identity across versions (e.g. "hotel-daily"). New on create; reused to
|
||||||
|
* publish a new version of an existing plan. Slugified server-side. */
|
||||||
|
planId?: string;
|
||||||
|
name?: string;
|
||||||
|
period?: SubscriptionPeriod;
|
||||||
|
pricePerPeriodMinor?: number;
|
||||||
|
currency?: string;
|
||||||
|
/** When this version takes effect (ISO-8601). Defaults to now. */
|
||||||
|
effectiveFrom?: string;
|
||||||
|
/** Allowed-time windows (tariff bridge); null/omitted = 24/7. */
|
||||||
|
timeframes?: PlanTimeframes | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Validate the optional timeframes blob (minutes-of-day 0–1439, days 0–6, sane grace). */
|
||||||
|
function validTimeframes(tf: PlanTimeframes | null | undefined): string | null {
|
||||||
|
if (tf == null) return null;
|
||||||
|
const okMin = (v: unknown) => Number.isInteger(v) && (v as number) >= 0 && (v as number) <= 1439;
|
||||||
|
if (!okMin(tf.fromMin) || !okMin(tf.toMin)) return "window times must be minutes-of-day (0–1439)";
|
||||||
|
if (tf.days != null && (!Array.isArray(tf.days) || tf.days.some((d) => !Number.isInteger(d) || d < 0 || d > 6))) {
|
||||||
|
return "days must be integers 0–6 (0=Sun..6=Sat)";
|
||||||
|
}
|
||||||
|
if (tf.graceMin != null && (!Number.isInteger(tf.graceMin) || tf.graceMin < 0)) return "graceMin must be ≥ 0";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lowercase, hyphenate, strip junk — a stable slug for the plan identity. */
|
||||||
|
function slugify(s: string): string {
|
||||||
|
return s
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, "-")
|
||||||
|
.replace(/^-+|-+$/g, "")
|
||||||
|
.slice(0, 48);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function subscriptionPlanRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||||
|
const readGuard = requirePermission("subscription:read");
|
||||||
|
const planGuard = requirePermission("subscription:plan");
|
||||||
|
|
||||||
|
function validate(b: PlanBody): string[] {
|
||||||
|
const errs: string[] = [];
|
||||||
|
if (!b.name?.trim()) errs.push("name is required");
|
||||||
|
if (!b.period || !SUBSCRIPTION_PERIODS.includes(b.period)) {
|
||||||
|
errs.push(`period must be one of: ${SUBSCRIPTION_PERIODS.join(", ")}`);
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(b.pricePerPeriodMinor) || (b.pricePerPeriodMinor ?? 0) <= 0) {
|
||||||
|
errs.push("pricePerPeriodMinor must be a positive integer (minor units)");
|
||||||
|
}
|
||||||
|
if (!b.currency?.trim()) errs.push("currency is required");
|
||||||
|
if (b.effectiveFrom != null && Number.isNaN(Date.parse(b.effectiveFrom))) {
|
||||||
|
errs.push("effectiveFrom must be a valid ISO-8601 timestamp");
|
||||||
|
}
|
||||||
|
const tfErr = validTimeframes(b.timeframes);
|
||||||
|
if (tfErr) errs.push(tfErr);
|
||||||
|
return errs;
|
||||||
|
}
|
||||||
|
|
||||||
|
// List plans. ?all=1 → every version (history); default → the CURRENT sellable plan
|
||||||
|
// per planId (latest active version with effectiveFrom ≤ now). Operators selling
|
||||||
|
// need the current list; the admin catalog screen asks for ?all=1.
|
||||||
|
app.get<{ Querystring: { all?: string } }>("/api/subscription-plans", { preHandler: readGuard }, async (req) => {
|
||||||
|
const rows = db.select().from(subscriptionPlans).orderBy(desc(subscriptionPlans.effectiveFrom)).all();
|
||||||
|
if (req.query?.all) return { plans: rows };
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
// Newest-effective active version wins per planId.
|
||||||
|
const current = new Map<string, (typeof rows)[number]>();
|
||||||
|
for (const r of rows) {
|
||||||
|
if (!r.active || r.effectiveFrom > now) continue;
|
||||||
|
if (!current.has(r.planId)) current.set(r.planId, r); // rows are newest-first
|
||||||
|
}
|
||||||
|
return { plans: [...current.values()] };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Publish a plan version (create a plan, or a new version of an existing planId).
|
||||||
|
app.post<{ Body: PlanBody }>("/api/subscription-plans", { preHandler: planGuard }, async (req, reply) => {
|
||||||
|
const b = req.body ?? ({} as PlanBody);
|
||||||
|
const problems = validate(b);
|
||||||
|
if (problems.length) return reply.code(400).send({ error: "invalid plan", problems });
|
||||||
|
|
||||||
|
const planId = (b.planId?.trim() ? slugify(b.planId) : slugify(b.name!)) || randomUUID();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const effectiveFrom = b.effectiveFrom?.trim() || now;
|
||||||
|
// Backdating would retroactively reprice — refuse (mirrors tariff publish).
|
||||||
|
if (Date.parse(effectiveFrom) < Date.parse(now) - 60_000) {
|
||||||
|
return reply.code(400).send({
|
||||||
|
error: "effectiveFrom cannot be in the past — backdating a plan would retroactively reprice sales",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Stamp the site tz into the timeframes so the windows evaluate in the site's
|
||||||
|
// wall-clock, FROZEN in this version (mirrors how tariff V2 freezes its tz).
|
||||||
|
const timeframes =
|
||||||
|
b.timeframes != null ? { ...b.timeframes, tz: b.timeframes.tz || siteTz(db) } : null;
|
||||||
|
|
||||||
|
const row = {
|
||||||
|
id: randomUUID(),
|
||||||
|
planId,
|
||||||
|
name: b.name!.trim(),
|
||||||
|
period: b.period!,
|
||||||
|
pricePerPeriodMinor: b.pricePerPeriodMinor!,
|
||||||
|
currency: b.currency!.trim(),
|
||||||
|
effectiveFrom,
|
||||||
|
timeframes,
|
||||||
|
active: true,
|
||||||
|
createdBy: req.user?.username ?? null,
|
||||||
|
};
|
||||||
|
db.insert(subscriptionPlans).values(row as typeof subscriptionPlans.$inferInsert).run();
|
||||||
|
return reply.code(201).send(row);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Retire a plan (soft): mark every version of this planId inactive so it's no longer
|
||||||
|
// sellable. History (and past sales' planVersionId) is preserved. Reactivate to revive.
|
||||||
|
app.post<{ Params: { planId: string } }>(
|
||||||
|
"/api/subscription-plans/:planId/retire",
|
||||||
|
{ preHandler: planGuard },
|
||||||
|
async (req) => {
|
||||||
|
db.update(subscriptionPlans)
|
||||||
|
.set({ active: false })
|
||||||
|
.where(eq(subscriptionPlans.planId, req.params.planId))
|
||||||
|
.run();
|
||||||
|
return { planId: req.params.planId, retired: true };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// REACTIVATE a retired plan: mark its versions active again so it's sellable. The
|
||||||
|
// latest-effective version becomes "in force" again. (The inverse of retire.)
|
||||||
|
app.post<{ Params: { planId: string } }>(
|
||||||
|
"/api/subscription-plans/:planId/reactivate",
|
||||||
|
{ preHandler: planGuard },
|
||||||
|
async (req) => {
|
||||||
|
db.update(subscriptionPlans)
|
||||||
|
.set({ active: true })
|
||||||
|
.where(eq(subscriptionPlans.planId, req.params.planId))
|
||||||
|
.run();
|
||||||
|
return { planId: req.params.planId, reactivated: true };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// DELETE a plan entirely — allowed ONLY when NO subscription references it (any
|
||||||
|
// version). A referenced plan version MUST survive: a subscription's planVersionId is
|
||||||
|
// needed to reprice/audit that sale, so deleting it would dangle. 409 with the count
|
||||||
|
// when in use (the admin should retire instead). Removes all versions of the planId.
|
||||||
|
app.delete<{ Params: { planId: string } }>(
|
||||||
|
"/api/subscription-plans/:planId",
|
||||||
|
{ preHandler: planGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const refs = db.select().from(subscriptions).where(eq(subscriptions.planId, req.params.planId)).all();
|
||||||
|
if (refs.length > 0) {
|
||||||
|
return reply.code(409).send({
|
||||||
|
error: "plan is in use and cannot be deleted",
|
||||||
|
code: "plan_in_use",
|
||||||
|
subscribers: refs.length,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
db.delete(subscriptionPlans).where(eq(subscriptionPlans.planId, req.params.planId)).run();
|
||||||
|
return { planId: req.params.planId, deleted: true };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,510 @@
|
|||||||
|
import { randomBytes, randomUUID } from "node:crypto";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { eq, devices, subscriptionCredentials, subscriptionPlates, subscriptions, type Db } from "@parking/db";
|
||||||
|
import { NoPrinterAvailableError } from "@parking/devices";
|
||||||
|
import type { SubscriptionPlan, SubscriptionQuote, Tender } from "@parking/shared";
|
||||||
|
import { requirePermission } from "../auth.js";
|
||||||
|
import { invalidateHolder } from "../event-enrich.js";
|
||||||
|
import { printSubscriptionCard } from "../booth-print.js";
|
||||||
|
import type { CredentialCapture } from "../credential-capture.js";
|
||||||
|
import type { EventLog } from "../event-log.js";
|
||||||
|
import type { ShiftService } from "../shift-service.js";
|
||||||
|
import { directionOf } from "../device-resolve.js";
|
||||||
|
import { priceSubscriptionSpan, resolvePlanVersion } from "../subscription-pricing.js";
|
||||||
|
|
||||||
|
// Subscription admin CRUD. A subscription is mutable master data — admins
|
||||||
|
// grant/edit/revoke — but every USE of it is a signed ledger event, so the audit
|
||||||
|
// trail stays append-only (see wiki/entities/subscription.md). A subscription is an
|
||||||
|
// aggregate: the row + its credentials (card/QR) + its bound plates. The API treats
|
||||||
|
// them as one unit (create/update replace the child sets; delete removes all).
|
||||||
|
//
|
||||||
|
// Pricing & THE SALE. priceMinor + period ("monthly") + currency record the recurring
|
||||||
|
// plan (e.g. 10,000 ALL / month). When a subscription is SOLD (created with a price),
|
||||||
|
// the operator collects real money — so we append a SIGNED `payment` ledger event for
|
||||||
|
// the amount actually taken (priceMinor × months for a multi-month prepay), with the
|
||||||
|
// tender the operator chose. That is the ONLY accountability mechanism: without it the
|
||||||
|
// sale leaves no trace in the live feed, the drawer, or the shift Z-report, and the
|
||||||
|
// operator could pocket the cash untraceably (the exact booth-operator-as-adversary
|
||||||
|
// gap this system exists to close). The `subscriptions` row is mutable master data and
|
||||||
|
// is NOT the financial record; the signed payment event is. See wiki/concepts/shift.md.
|
||||||
|
|
||||||
|
interface Credential {
|
||||||
|
kind: "rf" | "qr";
|
||||||
|
/** For RF: the physical card/tag id (required). For QR: optional — left blank, the
|
||||||
|
* server AUTO-GENERATES an unguessable code (the customer never picks it). */
|
||||||
|
value?: string;
|
||||||
|
}
|
||||||
|
interface SubscriptionBody {
|
||||||
|
holderName?: string;
|
||||||
|
contact?: string;
|
||||||
|
/** PRICED SALE: the plan the operator selected. The price is LOOKED UP from the
|
||||||
|
* plan version (periods × per-period price) — the operator never types an amount.
|
||||||
|
* Omit for a free/comp subscription (no plan, no charge). */
|
||||||
|
planId?: string | null;
|
||||||
|
/** Coverage window. For a priced sale: `validFrom` defaults to now, `validTo` is
|
||||||
|
* REQUIRED (the span priced against the plan). For a comp sub, both optional. */
|
||||||
|
validFrom?: string | null;
|
||||||
|
validTo?: string | null;
|
||||||
|
/** How many cars this subscription covers (a family pays once for N cars). Sale =
|
||||||
|
* plan span price × quantity; maxConcurrent defaults to it. ≥ 1, default 1. */
|
||||||
|
quantity?: number | null;
|
||||||
|
/** Car-count binding: cars inside at once. Default = quantity; null = unbound. */
|
||||||
|
maxConcurrent?: number | null;
|
||||||
|
status?: "active" | "suspended" | "revoked";
|
||||||
|
credentials?: Credential[];
|
||||||
|
/** Plate binding (optional): bound plates that also serve as identity. */
|
||||||
|
plates?: string[];
|
||||||
|
/** How the sale fee was tendered (cash → drawer, card → bank). Used at CREATE when a
|
||||||
|
* plan is sold; ignored on update (master-data edit, no money moves). Default "cash". */
|
||||||
|
tender?: Tender;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Body for POST /api/subscriptions/quote — price a span against a plan, no write. */
|
||||||
|
interface QuoteBody {
|
||||||
|
planId?: string;
|
||||||
|
validFrom?: string;
|
||||||
|
validTo?: string;
|
||||||
|
quantity?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mint an unguessable QR credential value. Namespaced + crypto-random; the reader
|
||||||
|
* delivers the full string over TCP/IP (the host-in-the-loop path), so length is
|
||||||
|
* free. base32 (Crockford-ish, no 0/1/O/I ambiguity), uppercased. */
|
||||||
|
function newQrCode(): string {
|
||||||
|
const alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||||
|
const bytes = randomBytes(15);
|
||||||
|
let out = "";
|
||||||
|
for (const b of bytes) out += alphabet[b % 32];
|
||||||
|
return `SUB-${out}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function subscriptionRoutes(
|
||||||
|
app: FastifyInstance,
|
||||||
|
db: Db,
|
||||||
|
capture: CredentialCapture,
|
||||||
|
eventLog: EventLog,
|
||||||
|
shift: ShiftService,
|
||||||
|
): Promise<void> {
|
||||||
|
// Reading/looking up subscriptions vs. managing them. Revoke folds into update.
|
||||||
|
const readGuard = requirePermission("subscription:read");
|
||||||
|
const createGuard = requirePermission("subscription:create");
|
||||||
|
const updateGuard = requirePermission("subscription:update");
|
||||||
|
const deleteGuard = requirePermission("subscription:delete");
|
||||||
|
|
||||||
|
// Validate the body; returns problems (empty = ok). Shared by create + update.
|
||||||
|
function validate(b: SubscriptionBody): string[] {
|
||||||
|
const errs: string[] = [];
|
||||||
|
if (b.maxConcurrent != null) {
|
||||||
|
if (!Number.isInteger(b.maxConcurrent) || b.maxConcurrent < 1) {
|
||||||
|
errs.push("maxConcurrent must be a positive integer, or null for unbound");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// PRICED SALE: a plan is selected → the span must be valid and price > 0. The
|
||||||
|
// amount is derived from the plan (operator never types it), so there's no
|
||||||
|
// priceMinor to validate.
|
||||||
|
if (b.planId != null && b.planId.trim()) {
|
||||||
|
const from = b.validFrom?.trim() || new Date().toISOString();
|
||||||
|
const to = b.validTo?.trim();
|
||||||
|
if (!to) {
|
||||||
|
errs.push("validTo (end date) is required when selling a plan");
|
||||||
|
} else if (Number.isNaN(Date.parse(to)) || Number.isNaN(Date.parse(from))) {
|
||||||
|
errs.push("validFrom/validTo must be valid ISO-8601 dates");
|
||||||
|
} else if (Date.parse(to) <= Date.parse(from)) {
|
||||||
|
errs.push("validTo must be after validFrom");
|
||||||
|
} else {
|
||||||
|
// Resolve the plan version at the SALE instant (now) — the customer buys today's
|
||||||
|
// published plan/price. (validFrom is the coverage start, which may be midnight
|
||||||
|
// today and predate a plan published this afternoon.)
|
||||||
|
const plan = resolvePlanVersion(db, b.planId.trim(), new Date().toISOString());
|
||||||
|
if (!plan) errs.push("no active plan found for the selected planId");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (b.quantity != null && (!Number.isInteger(b.quantity) || b.quantity < 1)) {
|
||||||
|
errs.push("quantity must be a positive integer (cars covered)");
|
||||||
|
}
|
||||||
|
if (b.status && !["active", "suspended", "revoked"].includes(b.status)) {
|
||||||
|
errs.push("status must be active|suspended|revoked");
|
||||||
|
}
|
||||||
|
if (b.tender != null && b.tender !== "cash" && b.tender !== "card") {
|
||||||
|
errs.push("tender must be cash|card");
|
||||||
|
}
|
||||||
|
for (const c of b.credentials ?? []) {
|
||||||
|
if (c.kind !== "rf" && c.kind !== "qr") {
|
||||||
|
errs.push("each credential needs kind (rf|qr)");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// RF must carry the physical card id; QR may be blank (server auto-generates).
|
||||||
|
if (c.kind === "rf" && !c.value?.trim()) {
|
||||||
|
errs.push("an RF credential needs a non-empty value (the card/tag id)");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((b.credentials?.length ?? 0) === 0 && (b.plates?.length ?? 0) === 0) {
|
||||||
|
errs.push("a subscription needs at least one credential or one bound plate (else nothing identifies it)");
|
||||||
|
}
|
||||||
|
return errs;
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadAggregate(id: string) {
|
||||||
|
const sub = db.select().from(subscriptions).where(eq(subscriptions.id, id)).get();
|
||||||
|
if (!sub) return null;
|
||||||
|
const credentials = db.select().from(subscriptionCredentials).where(eq(subscriptionCredentials.subscriptionId, id)).all();
|
||||||
|
const plates = db.select().from(subscriptionPlates).where(eq(subscriptionPlates.subscriptionId, id)).all();
|
||||||
|
return {
|
||||||
|
...sub,
|
||||||
|
credentials: credentials.map((c) => ({ kind: c.kind, value: c.value })),
|
||||||
|
plates: plates.map((p) => p.plate),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Is this credential value already used by ANY subscription? (Global uniqueness —
|
||||||
|
* a value is the lane identity, so it must resolve to one subscription.) */
|
||||||
|
function valueTaken(value: string): boolean {
|
||||||
|
return db.select().from(subscriptionCredentials).where(eq(subscriptionCredentials.value, value)).get() != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A fresh, collision-free QR code (retries on the astronomically unlikely clash). */
|
||||||
|
function mintQrCode(): string {
|
||||||
|
for (let i = 0; i < 5; i += 1) {
|
||||||
|
const code = newQrCode();
|
||||||
|
if (!valueTaken(code)) return code;
|
||||||
|
}
|
||||||
|
throw new Error("could not mint a unique QR code");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace a subscription's child rows (credentials + plates) from the body. QR
|
||||||
|
// credentials with no value are SERVER-GENERATED here (the customer never picks the
|
||||||
|
// code). The generated value is returned via loadAggregate so the UI can print it.
|
||||||
|
function writeChildren(id: string, b: SubscriptionBody) {
|
||||||
|
db.delete(subscriptionCredentials).where(eq(subscriptionCredentials.subscriptionId, id)).run();
|
||||||
|
db.delete(subscriptionPlates).where(eq(subscriptionPlates.subscriptionId, id)).run();
|
||||||
|
for (const c of b.credentials ?? []) {
|
||||||
|
const supplied = c.value?.trim();
|
||||||
|
// QR + blank → auto-generate; otherwise use the supplied value (RF card id, or a
|
||||||
|
// QR being preserved on edit).
|
||||||
|
const value = supplied && supplied.length > 0 ? supplied : c.kind === "qr" ? mintQrCode() : "";
|
||||||
|
if (!value) continue; // guarded by validate(); defensive
|
||||||
|
db.insert(subscriptionCredentials).values({ id: randomUUID(), subscriptionId: id, kind: c.kind, value }).run();
|
||||||
|
}
|
||||||
|
for (const p of b.plates ?? []) {
|
||||||
|
if (p.trim()) db.insert(subscriptionPlates).values({ id: randomUUID(), subscriptionId: id, plate: p.trim() }).run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve the coverage end: an explicit validTo (the span end the operator picked).
|
||||||
|
* Falls back to the existing value on an update that doesn't touch it. */
|
||||||
|
function resolveValidTo(b: SubscriptionBody, fallback: string | null): string | null {
|
||||||
|
if (b.validTo !== undefined) return b.validTo ?? null;
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve + price a priced sale: returns the plan version, the effective span, the
|
||||||
|
* quantity (cars covered), and the server-computed quote with the amount already
|
||||||
|
* MULTIPLIED by quantity (a family paying once for N cars). Returns null for a comp
|
||||||
|
* sub (no planId). validate() guards the happy path. */
|
||||||
|
function priceSale(
|
||||||
|
b: SubscriptionBody,
|
||||||
|
): { plan: SubscriptionPlan; validFrom: string; validTo: string; quantity: number; quote: SubscriptionQuote } | null {
|
||||||
|
if (!b.planId?.trim() || !b.validTo?.trim()) return null;
|
||||||
|
const validFrom = b.validFrom?.trim() || new Date().toISOString();
|
||||||
|
const validTo = b.validTo.trim();
|
||||||
|
// Plan version is resolved at the SALE instant (now), not validFrom (which is the
|
||||||
|
// coverage start and may predate a plan published later today).
|
||||||
|
const plan = resolvePlanVersion(db, b.planId.trim(), new Date().toISOString());
|
||||||
|
if (!plan) return null;
|
||||||
|
const quantity = b.quantity != null && b.quantity > 0 ? Math.round(b.quantity) : 1;
|
||||||
|
const base = priceSubscriptionSpan(plan, validFrom, validTo);
|
||||||
|
// Price ×N: the whole sale covers N cars on one subscription.
|
||||||
|
const quote: SubscriptionQuote = { ...base, amountMinor: base.amountMinor * quantity };
|
||||||
|
return { plan, validFrom, validTo, quantity, quote };
|
||||||
|
}
|
||||||
|
|
||||||
|
// List all subscriptions (with their credentials + plates).
|
||||||
|
app.get("/api/subscriptions", { preHandler: readGuard }, async () => {
|
||||||
|
const rows = db.select().from(subscriptions).all();
|
||||||
|
return { subscriptions: rows.map((r) => loadAggregate(r.id)) };
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Credential capture ("enroll a card") -------------------------------
|
||||||
|
// The operator picks a reader and presents an RFID card to it; the next read on
|
||||||
|
// that reader is captured for the form instead of opening a barrier. The OTHER
|
||||||
|
// reader keeps serving the live flow. Single-shot + TTL. See credential-capture.ts.
|
||||||
|
|
||||||
|
// The readers the operator can capture on (entry/exit by their bound relay).
|
||||||
|
app.get("/api/subscriptions/readers", { preHandler: readGuard }, async () => {
|
||||||
|
const rows = db.select().from(devices).where(eq(devices.category, "reader")).all();
|
||||||
|
return {
|
||||||
|
readers: rows
|
||||||
|
.filter((r) => r.enabled)
|
||||||
|
.map((r) => ({ id: r.id, driverId: r.driverId, direction: directionOf(db, r) })),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Arm capture on a reader (by devices.id). Operator-or-admin (booth action).
|
||||||
|
app.post<{ Body: { deviceId?: string } }>(
|
||||||
|
"/api/subscriptions/capture/arm",
|
||||||
|
{ preHandler: readGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const deviceId = (req.body?.deviceId ?? "").trim();
|
||||||
|
if (!deviceId) return reply.code(400).send({ error: "deviceId required" });
|
||||||
|
const reader = db.select().from(devices).where(eq(devices.id, deviceId)).get();
|
||||||
|
if (!reader || reader.category !== "reader" || !reader.enabled) {
|
||||||
|
return reply.code(404).send({ error: "no such enabled reader" });
|
||||||
|
}
|
||||||
|
return capture.arm(deviceId);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Poll the capture state (idle | armed | captured | expired). The form polls this
|
||||||
|
// and, on "captured", reads `value` into the credential field then clears it.
|
||||||
|
app.get("/api/subscriptions/capture", { preHandler: readGuard }, async () => capture.state());
|
||||||
|
|
||||||
|
// Operator cancelled / closed the form — disarm and clear any result.
|
||||||
|
app.post("/api/subscriptions/capture/cancel", { preHandler: readGuard }, async () => {
|
||||||
|
capture.cancel();
|
||||||
|
capture.clear();
|
||||||
|
return { ok: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create a subscription.
|
||||||
|
// Price a span against a plan WITHOUT writing anything — the live quote the sell form
|
||||||
|
// shows ("3 nights · 2,400 ALL"). Server-computed so the operator can't fudge it.
|
||||||
|
app.post<{ Body: QuoteBody }>("/api/subscriptions/quote", { preHandler: readGuard }, async (req, reply) => {
|
||||||
|
const b = req.body ?? {};
|
||||||
|
if (!b.planId?.trim()) return reply.code(400).send({ error: "planId is required" });
|
||||||
|
const validFrom = b.validFrom?.trim() || new Date().toISOString();
|
||||||
|
const validTo = b.validTo?.trim();
|
||||||
|
if (!validTo) return reply.code(400).send({ error: "validTo is required" });
|
||||||
|
if (Number.isNaN(Date.parse(validFrom)) || Number.isNaN(Date.parse(validTo))) {
|
||||||
|
return reply.code(400).send({ error: "validFrom/validTo must be valid ISO-8601 dates" });
|
||||||
|
}
|
||||||
|
if (Date.parse(validTo) <= Date.parse(validFrom)) {
|
||||||
|
return reply.code(400).send({ error: "validTo must be after validFrom" });
|
||||||
|
}
|
||||||
|
// Resolve at the sale instant (now), not validFrom — see priceSale.
|
||||||
|
const plan = resolvePlanVersion(db, b.planId.trim(), new Date().toISOString());
|
||||||
|
if (!plan) return reply.code(404).send({ error: "no active plan for that planId" });
|
||||||
|
const quantity = b.quantity != null && b.quantity > 0 ? Math.round(b.quantity) : 1;
|
||||||
|
const base = priceSubscriptionSpan(plan, validFrom, validTo);
|
||||||
|
// Echo the ×quantity total so the form previews the family's combined price.
|
||||||
|
return { ...base, amountMinor: base.amountMinor * quantity, quantity, plan };
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post<{ Body: SubscriptionBody }>("/api/subscriptions", { preHandler: createGuard }, async (req, reply) => {
|
||||||
|
const b = req.body ?? {};
|
||||||
|
const problems = validate(b);
|
||||||
|
if (problems.length) return reply.code(400).send({ error: "invalid subscription", problems });
|
||||||
|
const id = randomUUID();
|
||||||
|
// Price is LOOKED UP from the chosen plan (periods × per-period price) — never typed
|
||||||
|
// by the operator. A comp sub (no plan) carries no price. Persist the plan + version
|
||||||
|
// so the sale reprices identically later.
|
||||||
|
const priced = priceSale(b);
|
||||||
|
db.insert(subscriptions)
|
||||||
|
.values({
|
||||||
|
id,
|
||||||
|
holderName: b.holderName ?? null,
|
||||||
|
contact: b.contact ?? null,
|
||||||
|
priceMinor: priced ? priced.quote.amountMinor : null,
|
||||||
|
period: priced ? priced.plan.period : "month",
|
||||||
|
currency: priced ? priced.quote.currency : null,
|
||||||
|
planId: priced ? priced.plan.planId : null,
|
||||||
|
planVersionId: priced ? priced.plan.id : null,
|
||||||
|
quantity: priced ? priced.quantity : (b.quantity != null && b.quantity > 0 ? Math.round(b.quantity) : 1),
|
||||||
|
// maxConcurrent defaults to the quantity (the family's N cars can all be inside),
|
||||||
|
// unless the operator set it explicitly (null = unbound).
|
||||||
|
maxConcurrent:
|
||||||
|
b.maxConcurrent !== undefined
|
||||||
|
? b.maxConcurrent
|
||||||
|
: priced
|
||||||
|
? priced.quantity
|
||||||
|
: (b.quantity != null && b.quantity > 0 ? Math.round(b.quantity) : 1),
|
||||||
|
validFrom: priced ? priced.validFrom : (b.validFrom ?? null),
|
||||||
|
validTo: priced ? priced.validTo : resolveValidTo(b, null),
|
||||||
|
status: b.status ?? "active",
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
writeChildren(id, b);
|
||||||
|
const sub = loadAggregate(id);
|
||||||
|
// THE SALE: a priced subscription means the operator collected money. Append a
|
||||||
|
// SIGNED `payment` event so the takings show up in the live feed, the drawer, and
|
||||||
|
// the shift Z-report — never an untraceable cash grab. Best-effort wrt the response,
|
||||||
|
// but the append is the whole point, so a failure is logged loudly.
|
||||||
|
const sale = await recordSale(id, priced, b.tender, req.user?.username ?? "?");
|
||||||
|
// Auto-print the QR card so the operator can hand it to the customer. Best-effort:
|
||||||
|
// a print failure NEVER fails the create (the subscription + its code are saved);
|
||||||
|
// the response carries { printed, printError } so the UI can warn + offer reprint.
|
||||||
|
const printResult = await tryPrintCard(sub);
|
||||||
|
return reply.code(201).send({ ...sub, ...sale, ...printResult });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Append the SIGNED `payment` ledger event for a subscription sale, so the money is
|
||||||
|
* accounted for exactly like a parking payment (live feed + drawer + Z-report). The
|
||||||
|
* amount comes from the PLAN quote (periods × per-period price) — never an
|
||||||
|
* operator-typed number. No plan → no sale → nothing appended (free/comp). The event
|
||||||
|
* carries `subscriptionSale: true` + the subscription id + the plan version so the
|
||||||
|
* feed/audit can label it and the price is reproducible. We do NOT hard-require an
|
||||||
|
* open shift (a subscription can be sold outside the booth money path), but the
|
||||||
|
* operator IS recorded and the payment folds into whichever shift window contains its
|
||||||
|
* timestamp — so it can never be silently pocketed. Returns { sale } or {}.
|
||||||
|
*/
|
||||||
|
async function recordSale(
|
||||||
|
id: string,
|
||||||
|
priced: ReturnType<typeof priceSale>,
|
||||||
|
tenderIn: Tender | undefined,
|
||||||
|
operator: string,
|
||||||
|
): Promise<{ sale?: { amountMinor: number; currency: string | null; tender: Tender; periods: number; inShift: boolean } }> {
|
||||||
|
if (!priced || priced.quote.amountMinor <= 0) return {}; // free/comp — nothing collected
|
||||||
|
const { plan, quote } = priced;
|
||||||
|
const amountMinor = quote.amountMinor;
|
||||||
|
const tender: Tender = tenderIn ?? "cash";
|
||||||
|
const currency = quote.currency;
|
||||||
|
const inShift = shift.currentOpenShift() != null;
|
||||||
|
try {
|
||||||
|
await eventLog.append({
|
||||||
|
type: "payment",
|
||||||
|
source: "manual",
|
||||||
|
// Key the payment to the subscription so the feed can resolve the holder label
|
||||||
|
// and the audit can trace WHICH subscription was sold.
|
||||||
|
identity: id,
|
||||||
|
payload: {
|
||||||
|
sessionRef: id,
|
||||||
|
amountMinor,
|
||||||
|
currency,
|
||||||
|
tender,
|
||||||
|
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
|
||||||
|
// and reproducible repricing.
|
||||||
|
subscriptionSale: true,
|
||||||
|
permitId: id,
|
||||||
|
planId: plan.planId,
|
||||||
|
planVersionId: plan.id,
|
||||||
|
periods: quote.periods,
|
||||||
|
...(priced.quantity > 1 ? { quantity: priced.quantity } : {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
app.log.info(
|
||||||
|
`subscription sale ${amountMinor} ${currency} (${tender}, ${quote.periods}×${plan.period}×${priced.quantity}car) for ${id} by ${operator}` +
|
||||||
|
(inShift ? "" : " [no open shift]"),
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
// A failed append is serious — the money would be untraceable. Surface it.
|
||||||
|
app.log.error(`subscription-sale payment append FAILED for ${id}: ${(err as Error).message}`);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return { sale: { amountMinor, currency, tender, periods: quote.periods, inShift } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first QR credential's code for a subscription aggregate, or null. */
|
||||||
|
function qrCodeOf(sub: ReturnType<typeof loadAggregate>): string | null {
|
||||||
|
const cred = sub?.credentials.find((c) => c.kind === "qr");
|
||||||
|
return cred?.value ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Best-effort print of a subscription's QR card. Returns a flag + optional error
|
||||||
|
* (never throws). No QR credential → nothing to print (printed:false, no error). */
|
||||||
|
async function tryPrintCard(
|
||||||
|
sub: ReturnType<typeof loadAggregate>,
|
||||||
|
): Promise<{ printed: boolean; printedBy?: string; printError?: string }> {
|
||||||
|
const code = qrCodeOf(sub);
|
||||||
|
if (!sub || !code) return { printed: false };
|
||||||
|
try {
|
||||||
|
const printedBy = await printSubscriptionCard(
|
||||||
|
db,
|
||||||
|
{ code, holderName: sub.holderName, validFrom: sub.validFrom, validTo: sub.validTo },
|
||||||
|
app.log,
|
||||||
|
);
|
||||||
|
return { printed: true, printedBy };
|
||||||
|
} catch (err) {
|
||||||
|
const printError = err instanceof NoPrinterAvailableError ? err.message : (err as Error).message;
|
||||||
|
app.log.warn(`subscription card print failed for ${sub.id}: ${printError}`);
|
||||||
|
return { printed: false, printError };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update a subscription (replaces fields + child sets).
|
||||||
|
app.put<{ Params: { id: string }; Body: SubscriptionBody }>(
|
||||||
|
"/api/subscriptions/:id",
|
||||||
|
{ preHandler: updateGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const existing = db.select().from(subscriptions).where(eq(subscriptions.id, req.params.id)).get();
|
||||||
|
if (!existing) return reply.code(404).send({ error: "subscription not found" });
|
||||||
|
const b = req.body ?? {};
|
||||||
|
const problems = validate(b);
|
||||||
|
if (problems.length) return reply.code(400).send({ error: "invalid subscription", problems });
|
||||||
|
// An update is a MASTER-DATA edit — it never re-sells or re-prices. The price,
|
||||||
|
// plan, version and currency are FROZEN as the original sale recorded them (a new
|
||||||
|
// price means a new sale = a new subscription). Editable here: holder/contact,
|
||||||
|
// car-count, the validity window, status, and credentials/plates.
|
||||||
|
db.update(subscriptions)
|
||||||
|
.set({
|
||||||
|
holderName: b.holderName ?? null,
|
||||||
|
contact: b.contact ?? null,
|
||||||
|
maxConcurrent: b.maxConcurrent === undefined ? existing.maxConcurrent : b.maxConcurrent,
|
||||||
|
validFrom: b.validFrom === undefined ? existing.validFrom : (b.validFrom ?? null),
|
||||||
|
validTo: resolveValidTo(b, existing.validTo),
|
||||||
|
status: b.status ?? existing.status,
|
||||||
|
})
|
||||||
|
.where(eq(subscriptions.id, req.params.id))
|
||||||
|
.run();
|
||||||
|
writeChildren(req.params.id, b);
|
||||||
|
// The holder name may have changed — drop the feed-label cache for this sub.
|
||||||
|
invalidateHolder(req.params.id);
|
||||||
|
return loadAggregate(req.params.id);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Re-print the subscription's QR card (failed auto-print, lost card, re-hand to the
|
||||||
|
// customer). Operator-or-admin (it's a booth action, not a master-data edit). 404 if
|
||||||
|
// the subscription is gone; 409 if it has no QR credential; 503 if no printer.
|
||||||
|
app.post<{ Params: { id: string } }>(
|
||||||
|
"/api/subscriptions/:id/print",
|
||||||
|
{ preHandler: readGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const sub = loadAggregate(req.params.id);
|
||||||
|
if (!sub) return reply.code(404).send({ error: "subscription not found" });
|
||||||
|
const code = qrCodeOf(sub);
|
||||||
|
if (!code) return reply.code(409).send({ error: "subscription has no QR credential to print" });
|
||||||
|
try {
|
||||||
|
const printedBy = await printSubscriptionCard(
|
||||||
|
db,
|
||||||
|
{ code, holderName: sub.holderName, validFrom: sub.validFrom, validTo: sub.validTo },
|
||||||
|
app.log,
|
||||||
|
);
|
||||||
|
return reply.code(200).send({ ok: true, printedBy });
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof NoPrinterAvailableError) return reply.code(503).send({ error: err.message });
|
||||||
|
return reply.code(500).send({ error: (err as Error).message });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Revoke (soft): the common case — keeps the subscription + its history, just bars
|
||||||
|
// it. A revoked subscription fails the entry check (see subscription-flow.ts). Use
|
||||||
|
// DELETE only to fully remove one created in error.
|
||||||
|
app.post<{ Params: { id: string } }>(
|
||||||
|
"/api/subscriptions/:id/revoke",
|
||||||
|
{ preHandler: updateGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const r = db.update(subscriptions).set({ status: "revoked" }).where(eq(subscriptions.id, req.params.id)).run();
|
||||||
|
if (r.changes === 0) return reply.code(404).send({ error: "subscription not found" });
|
||||||
|
return loadAggregate(req.params.id);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Hard delete a subscription + its child rows. (Past ledger events that reference it
|
||||||
|
// are untouched — the audit trail is append-only and independent of this row.)
|
||||||
|
app.delete<{ Params: { id: string } }>(
|
||||||
|
"/api/subscriptions/:id",
|
||||||
|
{ preHandler: deleteGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const r = db.delete(subscriptions).where(eq(subscriptions.id, req.params.id)).run();
|
||||||
|
if (r.changes === 0) return reply.code(404).send({ error: "subscription not found" });
|
||||||
|
db.delete(subscriptionCredentials).where(eq(subscriptionCredentials.subscriptionId, req.params.id)).run();
|
||||||
|
db.delete(subscriptionPlates).where(eq(subscriptionPlates.subscriptionId, req.params.id)).run();
|
||||||
|
invalidateHolder(req.params.id);
|
||||||
|
return reply.code(204).send();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,8 +1,18 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance } from "fastify";
|
||||||
import { desc, eq, tariffVersions, tariffs, type Db } from "@parking/db";
|
import { desc, eq, ledgerEvents, siteConfig, tariffVersions, tariffs, type Db } from "@parking/db";
|
||||||
import { validateTariffStructure, type TariffStructure } from "@parking/shared";
|
import {
|
||||||
import { requireRole } from "../auth.js";
|
computeFee,
|
||||||
|
isTariffV2,
|
||||||
|
priceSession,
|
||||||
|
validateTariffStructure,
|
||||||
|
type SessionPayment,
|
||||||
|
type TariffStructure,
|
||||||
|
} from "@parking/shared";
|
||||||
|
import { requirePermission } from "../auth.js";
|
||||||
|
|
||||||
|
/** Default site timezone for wall-clock tariff windows when none is configured. */
|
||||||
|
const DEFAULT_TZ = "Europe/Tirane";
|
||||||
|
|
||||||
// Tariff composer API — the admin builds + edits the rate card at runtime. Tariffs
|
// Tariff composer API — the admin builds + edits the rate card at runtime. Tariffs
|
||||||
// are EFFECTIVE-DATED IMMUTABLE VERSIONS: editing publishes a new version, never
|
// are EFFECTIVE-DATED IMMUTABLE VERSIONS: editing publishes a new version, never
|
||||||
@@ -19,11 +29,24 @@ interface PublishBody {
|
|||||||
|
|
||||||
const SITE_TARIFF_NAME = "Site tariff";
|
const SITE_TARIFF_NAME = "Site tariff";
|
||||||
|
|
||||||
|
/** Body for POST /api/tariff/simulate — price a hypothetical session, no ledger write.
|
||||||
|
* Provide a structure source (one of): `tariffVersionId`, inline `structure`, or
|
||||||
|
* neither (uses the active version). */
|
||||||
|
interface SimulateBody {
|
||||||
|
enteredAt: string; // ISO-8601
|
||||||
|
asOf: string; // ISO-8601 (the "now"/exit instant being simulated)
|
||||||
|
payments?: SessionPayment[]; // hypothetical payment history (latest grants grace)
|
||||||
|
category?: string;
|
||||||
|
tariffVersionId?: string;
|
||||||
|
structure?: TariffStructure;
|
||||||
|
currency?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export async function tariffRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
export async function tariffRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||||
// Any signed-in role may READ the tariff (the pay station / operator UI needs it).
|
// Reading the rate card (pay station / operator UI needs it).
|
||||||
const readGuard = requireRole("admin", "operator", "cashier", "readonly");
|
const readGuard = requirePermission("tariff:read");
|
||||||
// Only an admin may PUBLISH a new version (it changes what customers are charged).
|
// Publishing a new version changes what customers are charged.
|
||||||
const writeGuard = requireRole("admin");
|
const writeGuard = requirePermission("tariff:update");
|
||||||
|
|
||||||
// The single site tariff row, created on first read/publish.
|
// The single site tariff row, created on first read/publish.
|
||||||
function ensureSiteTariff(): string {
|
function ensureSiteTariff(): string {
|
||||||
@@ -58,22 +81,163 @@ export async function tariffRoutes(app: FastifyInstance, db: Db): Promise<void>
|
|||||||
if (!currency || typeof currency !== "string" || currency.length < 3) {
|
if (!currency || typeof currency !== "string" || currency.length < 3) {
|
||||||
return reply.code(400).send({ error: "currency (ISO 4217) required" });
|
return reply.code(400).send({ error: "currency (ISO 4217) required" });
|
||||||
}
|
}
|
||||||
const problems = validateTariffStructure(structure);
|
// For a windowed (V2) structure, stamp the wall-clock timezone from SITE config
|
||||||
|
// (not the client) BEFORE validating — so the frozen tz is authoritative and the
|
||||||
|
// validation that requires tz passes. A V1 (bare) structure is left untouched.
|
||||||
|
let toStore: TariffStructure = structure;
|
||||||
|
if (structure && isTariffV2(structure)) {
|
||||||
|
const cfg = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||||
|
const tz = cfg?.timezone && cfg.timezone.length > 0 ? cfg.timezone : DEFAULT_TZ;
|
||||||
|
toStore = { ...structure, tz };
|
||||||
|
}
|
||||||
|
|
||||||
|
const problems = validateTariffStructure(toStore);
|
||||||
if (problems.length) {
|
if (problems.length) {
|
||||||
return reply.code(400).send({ error: "invalid tariff structure", problems });
|
return reply.code(400).send({ error: "invalid tariff structure", problems });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// effectiveFrom must NOT be in the past. A version is selected by
|
||||||
|
// "latest effectiveFrom <= entry time", so a backdated effectiveFrom would
|
||||||
|
// retroactively reprice already-entered sessions — exactly the immutability
|
||||||
|
// the versioning exists to prevent (wiki/concepts/tariff.md). So we forbid
|
||||||
|
// backdating: a new version applies only from publish (now) forward; a future
|
||||||
|
// effectiveFrom (scheduling a price change) is allowed. A small skew tolerance
|
||||||
|
// absorbs client/server clock drift + request round-trip. Once a car has
|
||||||
|
// entered, no later publish can reprice it (no effectiveFrom can predate it).
|
||||||
|
const now = Date.now();
|
||||||
|
const SKEW_MS = 60_000; // 1 min: clock skew + round-trip slack
|
||||||
|
let effective = new Date().toISOString();
|
||||||
|
if (effectiveFrom != null) {
|
||||||
|
const t = Date.parse(effectiveFrom);
|
||||||
|
if (Number.isNaN(t)) {
|
||||||
|
return reply.code(400).send({ error: "effectiveFrom must be a valid ISO-8601 timestamp" });
|
||||||
|
}
|
||||||
|
if (t < now - SKEW_MS) {
|
||||||
|
return reply.code(400).send({
|
||||||
|
error: "effectiveFrom cannot be in the past — backdating a tariff would retroactively reprice entered sessions",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
effective = new Date(t).toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
const tariffId = ensureSiteTariff();
|
const tariffId = ensureSiteTariff();
|
||||||
const id = randomUUID();
|
const id = randomUUID();
|
||||||
const row = {
|
const row = {
|
||||||
id,
|
id,
|
||||||
tariffId,
|
tariffId,
|
||||||
effectiveFrom: effectiveFrom ?? new Date().toISOString(),
|
effectiveFrom: effective,
|
||||||
currency,
|
currency,
|
||||||
structure: structure as unknown as Record<string, unknown>,
|
structure: toStore as unknown as Record<string, unknown>,
|
||||||
createdBy: req.user?.username ?? null,
|
createdBy: req.user?.username ?? null,
|
||||||
};
|
};
|
||||||
db.insert(tariffVersions).values(row).run();
|
db.insert(tariffVersions).values(row).run();
|
||||||
return reply.code(201).send(row);
|
return reply.code(201).send(row);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// --- Tariff Lab (simulator) -------------------------------------------------
|
||||||
|
// Price a HYPOTHETICAL session at arbitrary times against any tariff version —
|
||||||
|
// pure, no ledger writes. Lets an admin test rates "in time" (overnight windows,
|
||||||
|
// daily caps, overstay) in seconds instead of waiting hours. Also used to quote a
|
||||||
|
// customer dispute on-site. tariff:read (admins always have it). See tariff.md.
|
||||||
|
app.post<{ Body: SimulateBody }>("/api/tariff/simulate", { preHandler: readGuard }, async (req, reply) => {
|
||||||
|
const b = req.body ?? ({} as SimulateBody);
|
||||||
|
if (!b.enteredAt || !b.asOf) {
|
||||||
|
return reply.code(400).send({ error: "enteredAt and asOf (ISO-8601) required" });
|
||||||
|
}
|
||||||
|
if (!(Date.parse(b.enteredAt) <= Date.parse(b.asOf))) {
|
||||||
|
return reply.code(400).send({ error: "asOf must be at or after enteredAt" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve the structure: an explicit version id, or the active version, or an
|
||||||
|
// inline structure (preview unpublished edits). A version carries its currency.
|
||||||
|
let structure: TariffStructure | undefined = b.structure;
|
||||||
|
let currency = b.currency ?? null;
|
||||||
|
if (b.tariffVersionId) {
|
||||||
|
const v = db.select().from(tariffVersions).where(eq(tariffVersions.id, b.tariffVersionId)).get();
|
||||||
|
if (!v) return reply.code(404).send({ error: "tariff version not found" });
|
||||||
|
structure = v.structure as unknown as TariffStructure;
|
||||||
|
currency = v.currency;
|
||||||
|
} else if (!structure) {
|
||||||
|
const tariffId = ensureSiteTariff();
|
||||||
|
const nowIso = new Date().toISOString();
|
||||||
|
const active =
|
||||||
|
db
|
||||||
|
.select()
|
||||||
|
.from(tariffVersions)
|
||||||
|
.where(eq(tariffVersions.tariffId, tariffId))
|
||||||
|
.orderBy(desc(tariffVersions.effectiveFrom))
|
||||||
|
.all()
|
||||||
|
.find((v) => v.effectiveFrom <= nowIso) ?? null;
|
||||||
|
if (!active) return reply.code(404).send({ error: "no active tariff to simulate against" });
|
||||||
|
structure = active.structure as unknown as TariffStructure;
|
||||||
|
currency = active.currency;
|
||||||
|
}
|
||||||
|
|
||||||
|
const problems = validateTariffStructure(structure);
|
||||||
|
if (problems.length) return reply.code(400).send({ error: "invalid tariff structure", problems });
|
||||||
|
|
||||||
|
const payments = Array.isArray(b.payments) ? b.payments : [];
|
||||||
|
const pricing = priceSession(b.enteredAt, b.asOf, structure, payments, b.category);
|
||||||
|
|
||||||
|
// A duration curve from entry: handy to SEE where the cap flattens / windows shift.
|
||||||
|
const SAMPLES_MIN = [30, 60, 120, 180, 360, 720, 1440, 2880, 4320];
|
||||||
|
const enteredMs = Date.parse(b.enteredAt);
|
||||||
|
const curve = SAMPLES_MIN.map((min) => ({
|
||||||
|
minutes: min,
|
||||||
|
amountMinor: computeFee(b.enteredAt, new Date(enteredMs + min * 60_000).toISOString(), structure!, b.category),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return { currency, pricing, curve, gracePeriodExitMin: structure.gracePeriodExitMin };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Prefill the lab from a REAL session: fold its ledger into entry + payments so the
|
||||||
|
// admin can re-evaluate an actual ticket (e.g. an overstay) at any chosen `asOf`.
|
||||||
|
app.get<{ Params: { identity: string } }>(
|
||||||
|
"/api/tariff/simulate/session/:identity",
|
||||||
|
{ preHandler: readGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const id = (req.params.identity ?? "").trim();
|
||||||
|
if (!id) return reply.code(400).send({ error: "identity required" });
|
||||||
|
const rows = db
|
||||||
|
.select()
|
||||||
|
.from(ledgerEvents)
|
||||||
|
.where(eq(ledgerEvents.identity, id))
|
||||||
|
.orderBy(ledgerEvents.index)
|
||||||
|
.all();
|
||||||
|
const entry = rows.find((r) => r.type === "vehicle_entry");
|
||||||
|
if (!entry) return reply.code(404).send({ error: "no session for identity" });
|
||||||
|
const payments: { paidAt: string; graceExitMin: number | null }[] = [];
|
||||||
|
for (const r of rows) {
|
||||||
|
if (r.type !== "payment") continue;
|
||||||
|
const g = (r.payload as { graceExitMin?: number } | null)?.graceExitMin;
|
||||||
|
payments.push({ paidAt: r.occurredAt, graceExitMin: typeof g === "number" ? g : null });
|
||||||
|
}
|
||||||
|
const exit = rows.find((r) => r.type === "vehicle_exit");
|
||||||
|
const category = (entry.payload as { category?: string } | null)?.category ?? null;
|
||||||
|
return {
|
||||||
|
identity: id,
|
||||||
|
enteredAt: entry.occurredAt,
|
||||||
|
exitedAt: exit?.occurredAt ?? null,
|
||||||
|
payments,
|
||||||
|
category,
|
||||||
|
// The version frozen at entry — the rate card this session actually keeps.
|
||||||
|
tariffVersionId: tariffVersionIdFor(entry.occurredAt),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
/** The tariff version in force at a given instant (latest effectiveFrom ≤ when). */
|
||||||
|
function tariffVersionIdFor(whenIso: string): string | null {
|
||||||
|
const tariffId = ensureSiteTariff();
|
||||||
|
const v =
|
||||||
|
db
|
||||||
|
.select()
|
||||||
|
.from(tariffVersions)
|
||||||
|
.where(eq(tariffVersions.tariffId, tariffId))
|
||||||
|
.orderBy(desc(tariffVersions.effectiveFrom))
|
||||||
|
.all()
|
||||||
|
.find((row) => row.effectiveFrom <= whenIso) ?? null;
|
||||||
|
return v?.id ?? null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,245 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import bcrypt from "bcrypt";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { eq, roles, users, type Db } from "@parking/db";
|
||||||
|
import { ADMIN_ROLE_ID } from "@parking/shared";
|
||||||
|
import { permissionsFor, requirePermission } from "../auth.js";
|
||||||
|
|
||||||
|
// User management (admin). Users are created/edited at runtime here — the
|
||||||
|
// install-time seed-admin.mjs only bootstraps the FIRST admin. Each user has one
|
||||||
|
// role (RBAC); the role resolves to a permission set at request time. Passwords
|
||||||
|
// are bcrypt-hashed (cost 12) and never returned. See @parking/shared PERMISSIONS.
|
||||||
|
//
|
||||||
|
// NO-LOCKOUT INVARIANT: the app refuses to delete, or move off the `admin` role,
|
||||||
|
// the LAST user still holding `admin`. Administration can therefore never be
|
||||||
|
// locked out of the appliance. See wiki/entities/local-jwt-auth.md.
|
||||||
|
//
|
||||||
|
// PRIVILEGE-ESCALATION GUARD: a non-admin caller with `user:*` must NOT be able to
|
||||||
|
// (a) ASSIGN a role whose permissions exceed their own (e.g. hand themselves or a
|
||||||
|
// peer the admin role, or any role broader than theirs), nor (b) MODIFY a user who
|
||||||
|
// already holds a role broader than the caller's (resetting an admin's password is
|
||||||
|
// account takeover; deleting an admin is sabotage). Both are blocked below by
|
||||||
|
// comparing permission SETS. An admin holds the full set, so it is unrestricted.
|
||||||
|
|
||||||
|
// Optional profile metadata accepted on create/update. All nullable; "" is treated
|
||||||
|
// as "clear" (→ null). Trimmed before persisting.
|
||||||
|
interface ProfileBody {
|
||||||
|
fullName?: string | null;
|
||||||
|
phone?: string | null;
|
||||||
|
email?: string | null;
|
||||||
|
address?: string | null;
|
||||||
|
}
|
||||||
|
interface CreateBody extends ProfileBody {
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
roleId: string;
|
||||||
|
}
|
||||||
|
interface UpdateBody extends ProfileBody {
|
||||||
|
username?: string;
|
||||||
|
roleId?: string;
|
||||||
|
}
|
||||||
|
interface PasswordBody {
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIN_PASSWORD = 8;
|
||||||
|
const PROFILE_FIELDS = ["fullName", "phone", "email", "address"] as const;
|
||||||
|
|
||||||
|
/** Pull the optional profile fields out of a body → a patch of trimmed values
|
||||||
|
* ("" → null). Absent keys are omitted (so an update only touches what's sent). */
|
||||||
|
function profilePatch(body: ProfileBody): Record<string, string | null> {
|
||||||
|
const out: Record<string, string | null> = {};
|
||||||
|
for (const k of PROFILE_FIELDS) {
|
||||||
|
const v = body[k];
|
||||||
|
if (v === undefined) continue;
|
||||||
|
const trimmed = typeof v === "string" ? v.trim() : "";
|
||||||
|
out[k] = trimmed === "" ? null : trimmed;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function userRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||||
|
const readGuard = requirePermission("user:read");
|
||||||
|
const createGuard = requirePermission("user:create");
|
||||||
|
const updateGuard = requirePermission("user:update");
|
||||||
|
const deleteGuard = requirePermission("user:delete");
|
||||||
|
|
||||||
|
/** Count users currently holding the protected admin role. */
|
||||||
|
function adminCount(): number {
|
||||||
|
return db.select().from(users).where(eq(users.roleId, ADMIN_ROLE_ID)).all().length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True if removing/relocating `userId` from admin would leave zero admins. */
|
||||||
|
function isLastAdmin(userId: string): boolean {
|
||||||
|
const u = db.select().from(users).where(eq(users.id, userId)).get();
|
||||||
|
return u?.roleId === ADMIN_ROLE_ID && adminCount() <= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A user row safe to return — never the password hash. */
|
||||||
|
function publicUser(u: {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
roleId: string;
|
||||||
|
language: string;
|
||||||
|
createdAt: string;
|
||||||
|
fullName?: string | null;
|
||||||
|
phone?: string | null;
|
||||||
|
email?: string | null;
|
||||||
|
address?: string | null;
|
||||||
|
}) {
|
||||||
|
return {
|
||||||
|
id: u.id,
|
||||||
|
username: u.username,
|
||||||
|
roleId: u.roleId,
|
||||||
|
language: u.language,
|
||||||
|
createdAt: u.createdAt,
|
||||||
|
fullName: u.fullName ?? null,
|
||||||
|
phone: u.phone ?? null,
|
||||||
|
email: u.email ?? null,
|
||||||
|
address: u.address ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True if `targetRoleId` grants any permission the caller's role does NOT hold,
|
||||||
|
* i.e. assigning or touching it would let the caller act beyond their own
|
||||||
|
* privileges. (Admin holds the full set, so it never trips.) */
|
||||||
|
function exceedsCaller(callerRoleId: string, targetRoleId: string): boolean {
|
||||||
|
if (callerRoleId === targetRoleId) return false;
|
||||||
|
const held = permissionsFor(callerRoleId);
|
||||||
|
for (const p of permissionsFor(targetRoleId)) {
|
||||||
|
if (!held.has(p)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// List all users (no password hashes) + their role names for display.
|
||||||
|
app.get("/api/users", { preHandler: readGuard }, async () => {
|
||||||
|
const rows = db.select().from(users).all();
|
||||||
|
const roleRows = db.select().from(roles).all();
|
||||||
|
const roleName = new Map(roleRows.map((r) => [r.id, r.name]));
|
||||||
|
return {
|
||||||
|
users: rows.map((u) => ({ ...publicUser(u), roleName: roleName.get(u.roleId) ?? u.roleId })),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create a user. Username unique; password >= 8 chars; roleId must exist.
|
||||||
|
app.post<{ Body: CreateBody }>("/api/users", { preHandler: createGuard }, async (req, reply) => {
|
||||||
|
const username = (req.body?.username ?? "").trim();
|
||||||
|
const password = req.body?.password ?? "";
|
||||||
|
const roleId = (req.body?.roleId ?? "").trim();
|
||||||
|
if (!username || !roleId) {
|
||||||
|
return reply.code(400).send({ error: "username and roleId required" });
|
||||||
|
}
|
||||||
|
if (password.length < MIN_PASSWORD) {
|
||||||
|
return reply.code(400).send({ error: `password must be at least ${MIN_PASSWORD} characters` });
|
||||||
|
}
|
||||||
|
if (!db.select().from(roles).where(eq(roles.id, roleId)).get()) {
|
||||||
|
return reply.code(400).send({ error: "unknown roleId" });
|
||||||
|
}
|
||||||
|
// No-escalation: can't create a user with a role broader than your own.
|
||||||
|
if (exceedsCaller(req.user.roleId, roleId)) {
|
||||||
|
return reply.code(403).send({ error: "cannot assign a role with permissions beyond your own" });
|
||||||
|
}
|
||||||
|
if (db.select().from(users).where(eq(users.username, username)).get()) {
|
||||||
|
return reply.code(409).send({ error: "username already exists" });
|
||||||
|
}
|
||||||
|
const id = randomUUID();
|
||||||
|
const passwordHash = await bcrypt.hash(password, 12);
|
||||||
|
db.insert(users).values({ id, username, passwordHash, roleId, ...profilePatch(req.body) }).run();
|
||||||
|
const created = db.select().from(users).where(eq(users.id, id)).get()!;
|
||||||
|
return reply.code(201).send(publicUser(created));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update a user's username and/or role. Guarded against orphaning admin.
|
||||||
|
app.put<{ Params: { id: string }; Body: UpdateBody }>(
|
||||||
|
"/api/users/:id",
|
||||||
|
{ preHandler: updateGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const id = req.params.id;
|
||||||
|
const existing = db.select().from(users).where(eq(users.id, id)).get();
|
||||||
|
if (!existing) return reply.code(404).send({ error: "user not found" });
|
||||||
|
// No-escalation: can't modify a user who already outranks you.
|
||||||
|
if (exceedsCaller(req.user.roleId, existing.roleId)) {
|
||||||
|
return reply.code(403).send({ error: "cannot modify a user whose role exceeds your own" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const next: { username?: string; roleId?: string } & Record<string, string | null> = {
|
||||||
|
...profilePatch(req.body ?? {}),
|
||||||
|
};
|
||||||
|
if (req.body?.username != null) {
|
||||||
|
const username = req.body.username.trim();
|
||||||
|
if (!username) return reply.code(400).send({ error: "username cannot be empty" });
|
||||||
|
const clash = db.select().from(users).where(eq(users.username, username)).get();
|
||||||
|
if (clash && clash.id !== id) return reply.code(409).send({ error: "username already exists" });
|
||||||
|
next.username = username;
|
||||||
|
}
|
||||||
|
if (req.body?.roleId != null) {
|
||||||
|
const roleId = req.body.roleId.trim();
|
||||||
|
if (!db.select().from(roles).where(eq(roles.id, roleId)).get()) {
|
||||||
|
return reply.code(400).send({ error: "unknown roleId" });
|
||||||
|
}
|
||||||
|
// No-escalation: can't promote a user into a role broader than your own.
|
||||||
|
if (exceedsCaller(req.user.roleId, roleId)) {
|
||||||
|
return reply.code(403).send({ error: "cannot assign a role with permissions beyond your own" });
|
||||||
|
}
|
||||||
|
// No-lockout: don't move the last admin off the admin role.
|
||||||
|
if (roleId !== ADMIN_ROLE_ID && isLastAdmin(id)) {
|
||||||
|
return reply.code(409).send({ error: "cannot change the role of the last admin" });
|
||||||
|
}
|
||||||
|
next.roleId = roleId;
|
||||||
|
}
|
||||||
|
if (Object.keys(next).length === 0) {
|
||||||
|
return reply.code(400).send({ error: "nothing to update" });
|
||||||
|
}
|
||||||
|
db.update(users).set(next).where(eq(users.id, id)).run();
|
||||||
|
return publicUser(db.select().from(users).where(eq(users.id, id)).get()!);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Reset a user's password (admin sets a new one; >= 8 chars).
|
||||||
|
app.put<{ Params: { id: string }; Body: PasswordBody }>(
|
||||||
|
"/api/users/:id/password",
|
||||||
|
{ preHandler: updateGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const id = req.params.id;
|
||||||
|
const target = db.select().from(users).where(eq(users.id, id)).get();
|
||||||
|
if (!target) {
|
||||||
|
return reply.code(404).send({ error: "user not found" });
|
||||||
|
}
|
||||||
|
// No-escalation: can't reset the password of a user who outranks you
|
||||||
|
// (that would be account takeover of a more-privileged account).
|
||||||
|
if (exceedsCaller(req.user.roleId, target.roleId)) {
|
||||||
|
return reply.code(403).send({ error: "cannot reset the password of a user whose role exceeds your own" });
|
||||||
|
}
|
||||||
|
const password = req.body?.password ?? "";
|
||||||
|
if (password.length < MIN_PASSWORD) {
|
||||||
|
return reply.code(400).send({ error: `password must be at least ${MIN_PASSWORD} characters` });
|
||||||
|
}
|
||||||
|
const passwordHash = await bcrypt.hash(password, 12);
|
||||||
|
db.update(users).set({ passwordHash }).where(eq(users.id, id)).run();
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Delete a user. Refused if it's the last admin (no-lockout).
|
||||||
|
app.delete<{ Params: { id: string } }>(
|
||||||
|
"/api/users/:id",
|
||||||
|
{ preHandler: deleteGuard },
|
||||||
|
async (req, reply) => {
|
||||||
|
const id = req.params.id;
|
||||||
|
const target = db.select().from(users).where(eq(users.id, id)).get();
|
||||||
|
if (!target) {
|
||||||
|
return reply.code(404).send({ error: "user not found" });
|
||||||
|
}
|
||||||
|
// No-escalation: can't delete a user who outranks you.
|
||||||
|
if (exceedsCaller(req.user.roleId, target.roleId)) {
|
||||||
|
return reply.code(403).send({ error: "cannot delete a user whose role exceeds your own" });
|
||||||
|
}
|
||||||
|
if (isLastAdmin(id)) {
|
||||||
|
return reply.code(409).send({ error: "cannot delete the last admin" });
|
||||||
|
}
|
||||||
|
db.delete(users).where(eq(users.id, id)).run();
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import type { Db } from "@parking/db";
|
||||||
|
import type { LedgerEvent } from "@parking/shared";
|
||||||
|
import { roleHasPermissions } from "../auth.js";
|
||||||
|
import { deviceEvents } from "../device-events.js";
|
||||||
|
import { enrichEvent } from "../event-enrich.js";
|
||||||
|
import type { DeviceMonitor } from "../device-monitor.js";
|
||||||
|
import { getOccupancy } from "../occupancy.js";
|
||||||
|
|
||||||
|
// Live booth feed over a WebSocket. The booth UI opens ONE socket and receives
|
||||||
|
// server-pushed updates instead of polling: each signed ledger append (entry,
|
||||||
|
// exit, payment, void) is fanned out, and the recomputed occupancy rides along
|
||||||
|
// so the screen's count stays exact (occupancy is a fold over the same ledger,
|
||||||
|
// never a counter). Printer-status changes are forwarded too.
|
||||||
|
//
|
||||||
|
// Auth: the handshake is a normal GET through Fastify's lifecycle, so the same
|
||||||
|
// HttpOnly JWT cookie that guards the REST API guards this. We verify the JWT and
|
||||||
|
// role here. A browser's WebSocket constructor cannot set custom headers, so the
|
||||||
|
// CSRF double-submit header the REST mutations use is unavailable — which would
|
||||||
|
// leave the socket open to Cross-Site WebSocket Hijacking: a malicious page in the
|
||||||
|
// operator's browser could open ws://<booth>/api/ws, the browser would auto-attach
|
||||||
|
// the HttpOnly cookie, and the attacker would receive the live entry/exit/payment
|
||||||
|
// stream. The cookie alone is NOT a control here. So we replace the CSRF check with
|
||||||
|
// an Origin allowlist: the handshake's Origin must be same-origin (or an explicitly
|
||||||
|
// allowed booth UI origin). Non-browser clients (no Origin) are rejected too.
|
||||||
|
// See auth.ts, event-log.ts (emitLedger), capacity-occupancy.md.
|
||||||
|
|
||||||
|
/** Permission required to watch the live feed (a read-only stream of ledger +
|
||||||
|
* device status). Any role granted `report:read` may watch. */
|
||||||
|
const WATCH_PERMISSION = "report:read" as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Is the handshake's Origin trusted? Same-origin (Origin host === Host header) is
|
||||||
|
* always allowed; additional origins can be allowlisted via WS_ALLOWED_ORIGINS
|
||||||
|
* (comma-separated) for a booth UI served from a different origin. A missing or
|
||||||
|
* mismatched Origin is rejected — that is the anti-CSWSH control.
|
||||||
|
*/
|
||||||
|
function isAllowedOrigin(origin: string | undefined, host: string | undefined): boolean {
|
||||||
|
if (!origin) return false; // no Origin → not a same-origin browser request
|
||||||
|
let originHost: string;
|
||||||
|
try {
|
||||||
|
originHost = new URL(origin).host;
|
||||||
|
} catch {
|
||||||
|
return false; // malformed Origin
|
||||||
|
}
|
||||||
|
if (host && originHost === host) return true; // same-origin (any scheme/port match via host)
|
||||||
|
const allow = (process.env.WS_ALLOWED_ORIGINS ?? "")
|
||||||
|
.split(",")
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
return allow.includes(origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
type OutMsg =
|
||||||
|
| { kind: "hello"; occupancy: ReturnType<typeof getOccupancy>; devices: unknown }
|
||||||
|
| { kind: "ledger"; event: unknown; occupancy: ReturnType<typeof getOccupancy> }
|
||||||
|
| { kind: "printer-status"; event: unknown }
|
||||||
|
| { kind: "device-status"; event: unknown };
|
||||||
|
|
||||||
|
export async function wsRoutes(app: FastifyInstance, db: Db, deviceMonitor: DeviceMonitor): Promise<void> {
|
||||||
|
app.get(
|
||||||
|
"/api/ws",
|
||||||
|
{
|
||||||
|
websocket: true,
|
||||||
|
// Origin allowlist (anti-CSWSH, replaces CSRF — see file header) THEN JWT +
|
||||||
|
// role. Reject a cross/absent origin before touching the token, so a hijack
|
||||||
|
// attempt never reaches an authenticated socket. jwtVerify reads the cookie.
|
||||||
|
preHandler: async (req) => {
|
||||||
|
if (!isAllowedOrigin(req.headers.origin, req.headers.host)) {
|
||||||
|
throw Object.assign(new Error("forbidden origin"), { statusCode: 403 });
|
||||||
|
}
|
||||||
|
await req.jwtVerify();
|
||||||
|
if (!req.user || !roleHasPermissions(req.user.roleId, [WATCH_PERMISSION])) {
|
||||||
|
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
(socket) => {
|
||||||
|
const send = (msg: OutMsg) => {
|
||||||
|
// readyState 1 = OPEN; never throw out of an event-bus callback.
|
||||||
|
if (socket.readyState === 1) {
|
||||||
|
try {
|
||||||
|
socket.send(JSON.stringify(msg));
|
||||||
|
} catch {
|
||||||
|
/* drop on a broken socket */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Initial snapshot so the client renders immediately, before any event:
|
||||||
|
// occupancy AND the current device-status set (for the footer).
|
||||||
|
send({ kind: "hello", occupancy: getOccupancy(db), devices: deviceMonitor.snapshot() });
|
||||||
|
|
||||||
|
// Subscribe to the live buses. Each handler recomputes occupancy from the
|
||||||
|
// ledger (cheap fold) so the pushed count is always authoritative.
|
||||||
|
const offLedger = deviceEvents.onLedger((event) => {
|
||||||
|
// Enrich with read-time display fields (subscriber name) before fan-out.
|
||||||
|
const enriched = enrichEvent(db, event as unknown as LedgerEvent);
|
||||||
|
send({ kind: "ledger", event: enriched, occupancy: getOccupancy(db) });
|
||||||
|
});
|
||||||
|
const offPrinter = deviceEvents.onPrinterStatus((event) => {
|
||||||
|
send({ kind: "printer-status", event });
|
||||||
|
});
|
||||||
|
// Unified device status (all categories) for the booth footer — pushed on
|
||||||
|
// change; the initial set rode the hello above.
|
||||||
|
const offDevice = deviceEvents.onDeviceStatus((event) => {
|
||||||
|
send({ kind: "device-status", event });
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("close", () => {
|
||||||
|
offLedger();
|
||||||
|
offPrinter();
|
||||||
|
offDevice();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,24 +1,33 @@
|
|||||||
import cookie from "@fastify/cookie";
|
import cookie from "@fastify/cookie";
|
||||||
import jwt from "@fastify/jwt";
|
import jwt from "@fastify/jwt";
|
||||||
|
import websocket from "@fastify/websocket";
|
||||||
import Fastify, { type FastifyInstance } from "fastify";
|
import Fastify, { type FastifyInstance } from "fastify";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { createDb, deviceEvents as deviceEventsTable, type Db } from "@parking/db";
|
import { createDb, deviceEvents as deviceEventsTable, type Db } from "@parking/db";
|
||||||
import { TOKEN_COOKIE, requireJwtSecret } from "./auth.js";
|
import { TOKEN_COOKIE, requireJwtSecret, initAuth } from "./auth.js";
|
||||||
import { deviceEvents } from "./device-events.js";
|
import { deviceEvents } from "./device-events.js";
|
||||||
import { EntryFlow } from "./entry-flow.js";
|
import { EntryFlow } from "./entry-flow.js";
|
||||||
import { EventLog } from "./event-log.js";
|
import { EventLog } from "./event-log.js";
|
||||||
import { ExitFlow } from "./exit-flow.js";
|
import { ExitFlow } from "./exit-flow.js";
|
||||||
import { PayStation } from "./pay-station.js";
|
import { PayStation } from "./pay-station.js";
|
||||||
import { PermitFlow } from "./permit-flow.js";
|
import { SubscriptionFlow } from "./subscription-flow.js";
|
||||||
import { ShiftService } from "./shift-service.js";
|
import { ShiftService } from "./shift-service.js";
|
||||||
import { ReadDispatcher } from "./read-dispatch.js";
|
import { ReadDispatcher } from "./read-dispatch.js";
|
||||||
|
import { CredentialCapture } from "./credential-capture.js";
|
||||||
import { PrinterMonitor } from "./printer-monitor.js";
|
import { PrinterMonitor } from "./printer-monitor.js";
|
||||||
import { buildSigner } from "./signer.js";
|
import { DeviceMonitor } from "./device-monitor.js";
|
||||||
|
import { buildSigner, buildVerifier } from "./signer.js";
|
||||||
|
import { LogService, pinoDbStream } from "./log-service.js";
|
||||||
|
import { logRoutes } from "./routes/logs.js";
|
||||||
|
import { VisionClient } from "./vision-client.js";
|
||||||
import { authRoutes } from "./routes/auth.js";
|
import { authRoutes } from "./routes/auth.js";
|
||||||
|
import { userRoutes } from "./routes/users.js";
|
||||||
|
import { roleRoutes } from "./routes/roles.js";
|
||||||
import { deviceRoutes } from "./routes/devices.js";
|
import { deviceRoutes } from "./routes/devices.js";
|
||||||
import { eventRoutes } from "./routes/events.js";
|
import { eventRoutes } from "./routes/events.js";
|
||||||
import { payRoutes } from "./routes/pay.js";
|
import { payRoutes } from "./routes/pay.js";
|
||||||
import { permitRoutes } from "./routes/permits.js";
|
import { subscriptionRoutes } from "./routes/subscriptions.js";
|
||||||
|
import { subscriptionPlanRoutes } from "./routes/subscription-plans.js";
|
||||||
import { qrReaderRoutes } from "./routes/qr-reader.js";
|
import { qrReaderRoutes } from "./routes/qr-reader.js";
|
||||||
import { shiftRoutes } from "./routes/shift.js";
|
import { shiftRoutes } from "./routes/shift.js";
|
||||||
import { siteRoutes } from "./routes/site.js";
|
import { siteRoutes } from "./routes/site.js";
|
||||||
@@ -26,6 +35,8 @@ import { snapshotRoutes } from "./routes/snapshots.js";
|
|||||||
import { tariffRoutes } from "./routes/tariffs.js";
|
import { tariffRoutes } from "./routes/tariffs.js";
|
||||||
import { printerRoutes } from "./routes/printers.js";
|
import { printerRoutes } from "./routes/printers.js";
|
||||||
import { setupRoutes } from "./routes/setup.js";
|
import { setupRoutes } from "./routes/setup.js";
|
||||||
|
import { deviceStatusRoutes } from "./routes/device-status.js";
|
||||||
|
import { wsRoutes } from "./routes/ws.js";
|
||||||
|
|
||||||
// The backend is Fastify (Node). Hardware drivers live as isolated Fastify
|
// The backend is Fastify (Node). Hardware drivers live as isolated Fastify
|
||||||
// plugins emitting onto a shared internal event bus; auth is fully local
|
// plugins emitting onto a shared internal event bus; auth is fully local
|
||||||
@@ -36,14 +47,30 @@ export interface BuildOptions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInstance> {
|
export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInstance> {
|
||||||
const app = Fastify({
|
// DB first — the logger's DB sink needs it before Fastify is constructed.
|
||||||
logger: { level: process.env.LOG_LEVEL ?? "info" },
|
|
||||||
});
|
|
||||||
|
|
||||||
const db = opts.db ?? createDb();
|
const db = opts.db ?? createDb();
|
||||||
|
|
||||||
|
// Application-log store: a pino stream tees warn+ lines into app_logs (and still
|
||||||
|
// writes them to stdout), so backend warnings/errors are queryable from the booth
|
||||||
|
// alongside frontend errors. See log-service.ts + wiki/concepts/app-logs.md.
|
||||||
|
const logService = new LogService(db);
|
||||||
|
const app = Fastify({
|
||||||
|
logger: {
|
||||||
|
level: process.env.LOG_LEVEL ?? "info",
|
||||||
|
stream: pinoDbStream(logService, process.stdout),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wire the RBAC permission resolver to this DB (route guards resolve a user's
|
||||||
|
// role → permission set through it). See auth.ts.
|
||||||
|
initAuth(db);
|
||||||
|
|
||||||
await app.register(cookie);
|
await app.register(cookie);
|
||||||
|
|
||||||
|
// WebSocket support for the live booth feed (/api/ws). Registered before the
|
||||||
|
// routes so the `{ websocket: true }` route option is available.
|
||||||
|
await app.register(websocket);
|
||||||
|
|
||||||
// Local JWT signing with a local secret — no external identity provider.
|
// Local JWT signing with a local secret — no external identity provider.
|
||||||
// Fail fast rather than fall back to a known default: a booth machine started
|
// Fail fast rather than fall back to a known default: a booth machine started
|
||||||
// without a real secret would sign tokens anyone could forge (incl. an admin
|
// without a real secret would sign tokens anyone could forge (incl. an admin
|
||||||
@@ -61,6 +88,11 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
|||||||
// Local username/password login → JWT in an HttpOnly cookie + CSRF cookie.
|
// Local username/password login → JWT in an HttpOnly cookie + CSRF cookie.
|
||||||
await authRoutes(app, db);
|
await authRoutes(app, db);
|
||||||
|
|
||||||
|
// RBAC administration: compose roles (role:*) + manage users (user:*). The
|
||||||
|
// built-in admin role is protected; the last admin can't be removed. See auth.ts.
|
||||||
|
await userRoutes(app, db);
|
||||||
|
await roleRoutes(app, db);
|
||||||
|
|
||||||
// Device-agnostic setup: the admin adds controllers (with their relays + entry
|
// Device-agnostic setup: the admin adds controllers (with their relays + entry
|
||||||
// button) and binds readers/cameras to a controller relay at first-run. There is
|
// button) and binds readers/cameras to a controller relay at first-run. There is
|
||||||
// no lane — a parking lot is one pool with a flexible set of entry/exit points.
|
// no lane — a parking lot is one pool with a flexible set of entry/exit points.
|
||||||
@@ -80,15 +112,38 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
|||||||
app.addHook("onReady", async () => printerMonitor.start());
|
app.addHook("onReady", async () => printerMonitor.start());
|
||||||
app.addHook("onClose", async () => printerMonitor.stop());
|
app.addHook("onClose", async () => printerMonitor.stop());
|
||||||
|
|
||||||
|
// Vision (ANPR) client — built early so the device monitor can include the vision
|
||||||
|
// service's health in the footer. Opt-in (VISION_ENABLED) + fail-soft; advisory only.
|
||||||
|
// See wiki/entities/opencv-anpr-service.md.
|
||||||
|
const visionClient = new VisionClient(app.log);
|
||||||
|
if (visionClient.enabled) app.log.info("vision client enabled");
|
||||||
|
|
||||||
|
// Unified device-status monitor: polls EVERY configured device (relays/readers/
|
||||||
|
// cameras via healthCheck, printers via rich readStatus) PLUS the vision service's
|
||||||
|
// /health, and feeds the booth's device-status footer over the WS. Read-only.
|
||||||
|
// See wiki/concepts/device-status-monitoring.md.
|
||||||
|
const deviceMonitor = new DeviceMonitor(db, app.log, undefined, visionClient);
|
||||||
|
await deviceStatusRoutes(app, deviceMonitor);
|
||||||
|
app.addHook("onReady", async () => deviceMonitor.start());
|
||||||
|
app.addHook("onClose", async () => deviceMonitor.stop());
|
||||||
|
|
||||||
// Append-only signed business LEDGER (ledger_events). Holds only business facts
|
// Append-only signed business LEDGER (ledger_events). Holds only business facts
|
||||||
// (vehicle_entry/exit, payment, void, …) — the anti-fraud audit trail. A raw
|
// (vehicle_entry/exit, payment, void, …) — the anti-fraud audit trail. A raw
|
||||||
// button press is NOT a business fact: it's device telemetry, recorded UNSIGNED
|
// button press is NOT a business fact: it's device telemetry, recorded UNSIGNED
|
||||||
// in device_events. The entry flow (TODO) turns an input into a signed
|
// in device_events. The entry flow (TODO) turns an input into a signed
|
||||||
// vehicle_entry once a ticket prints + the barrier is commanded.
|
// vehicle_entry once a ticket prints + the barrier is commanded.
|
||||||
// See wiki/decisions/event-streams-split.md.
|
// See wiki/decisions/event-streams-split.md.
|
||||||
const eventLog = new EventLog(db, buildSigner(app.log));
|
// The 4th arg is a read-side fan-out fired AFTER each durable append — used to
|
||||||
|
// push the event to live booth clients (WS). It cannot affect the sign/chain path.
|
||||||
|
const eventLog = new EventLog(db, buildSigner(app.log), buildVerifier, (row) =>
|
||||||
|
deviceEvents.emitLedger(row),
|
||||||
|
);
|
||||||
await eventRoutes(app, db, eventLog);
|
await eventRoutes(app, db, eventLog);
|
||||||
|
|
||||||
|
// Live booth feed: server-pushed ledger + occupancy + printer-status over a
|
||||||
|
// single authenticated WebSocket (/api/ws). See routes/ws.ts.
|
||||||
|
await wsRoutes(app, db, deviceMonitor);
|
||||||
|
|
||||||
// Entry/exit camera snapshots (BLOB-in-DB), read-only. See snapshot.ts.
|
// Entry/exit camera snapshots (BLOB-in-DB), read-only. See snapshot.ts.
|
||||||
await snapshotRoutes(app, db);
|
await snapshotRoutes(app, db);
|
||||||
|
|
||||||
@@ -96,49 +151,81 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
|||||||
// Subscribes to the SAME input bus as the telemetry writer below; the two are
|
// Subscribes to the SAME input bus as the telemetry writer below; the two are
|
||||||
// independent (telemetry always records; the entry flow acts only on an access
|
// independent (telemetry always records; the entry flow acts only on an access
|
||||||
// device's rising edge). See wiki/concepts/device-input-flow.md + parking-session.md.
|
// device's rising edge). See wiki/concepts/device-input-flow.md + parking-session.md.
|
||||||
const entryFlow = new EntryFlow(db, eventLog, app.log);
|
// The flows take the vision client so ANPR rides their entry/exit SNAPSHOT: a button
|
||||||
|
// press / QR / RFID triggers the open + snapshot, and the plate is recognized off that
|
||||||
|
// same image and recorded against the session (advisory; never changes the decision).
|
||||||
|
// No polling — recognition fires only on a real entry/exit. See snapshot.ts +
|
||||||
|
// wiki/entities/opencv-anpr-service.md.
|
||||||
|
const entryFlow = new EntryFlow(db, eventLog, app.log, visionClient);
|
||||||
const unsubscribeEntry = deviceEvents.onInput((e) => {
|
const unsubscribeEntry = deviceEvents.onInput((e) => {
|
||||||
void entryFlow.onInput(e);
|
void entryFlow.onInput(e);
|
||||||
});
|
});
|
||||||
app.addHook("onClose", async () => unsubscribeEntry());
|
app.addHook("onClose", async () => unsubscribeEntry());
|
||||||
|
|
||||||
// Read-driven flows: a credential read (ticket scan / plate / card) routes via the
|
// Read-driven flows: a credential read (ticket scan / plate / card) routes via the
|
||||||
// dispatcher to either the PERMIT flow (if it matches a permit) or the transient
|
// dispatcher to either the SUBSCRIPTION flow (if it matches a subscription) or the
|
||||||
// EXIT flow. See read-dispatch.ts, exit-flow.ts, permit-flow.ts, parking-session.md.
|
// transient EXIT flow. See read-dispatch.ts, exit-flow.ts, subscription-flow.ts,
|
||||||
const exitFlow = new ExitFlow(db, eventLog, app.log);
|
// parking-session.md.
|
||||||
const permitFlow = new PermitFlow(db, eventLog, app.log);
|
const exitFlow = new ExitFlow(db, eventLog, app.log, visionClient);
|
||||||
const readDispatcher = new ReadDispatcher(db, exitFlow, permitFlow, app.log);
|
const subscriptionFlow = new SubscriptionFlow(db, eventLog, app.log, visionClient);
|
||||||
|
const readDispatcher = new ReadDispatcher(db, exitFlow, subscriptionFlow, app.log);
|
||||||
const unsubscribeRead = deviceEvents.onRead((e) => {
|
const unsubscribeRead = deviceEvents.onRead((e) => {
|
||||||
void readDispatcher.dispatch(e);
|
void readDispatcher.dispatch(e);
|
||||||
});
|
});
|
||||||
app.addHook("onClose", async () => unsubscribeRead());
|
app.addHook("onClose", async () => unsubscribeRead());
|
||||||
|
|
||||||
|
// Credential capture ("enroll a card"): lets the operator present an RFID card to a
|
||||||
|
// CHOSEN reader to populate a subscription credential, without blocking the other
|
||||||
|
// reader's live flow. Single-shot + TTL. See credential-capture.ts.
|
||||||
|
const credentialCapture = new CredentialCapture();
|
||||||
|
|
||||||
// GEE/Dingtian QR reader: it HTTP-GETs on each scan and beeps/acts on our JSON
|
// GEE/Dingtian QR reader: it HTTP-GETs on each scan and beeps/acts on our JSON
|
||||||
// verdict (host-in-the-loop, synchronous). Routes the read through the dispatcher
|
// verdict (host-in-the-loop, synchronous). The capture service can intercept a read
|
||||||
// and replies the SDK verdict. See wiki/entities/gee-qr-er80.md, qrcode-sdk.md.
|
// on an armed reader for enrollment; otherwise the read routes through the
|
||||||
await qrReaderRoutes(app, db, readDispatcher);
|
// dispatcher. See wiki/entities/gee-qr-er80.md, qrcode-sdk.md.
|
||||||
|
await qrReaderRoutes(app, db, readDispatcher, credentialCapture);
|
||||||
|
|
||||||
|
// Shifts (manned mode): explicit open/close → signed shift_open / shift_z_report
|
||||||
|
// (sum payments by tender, print the Z-report). Constructed before the pay routes
|
||||||
|
// because the booth money path is GATED on an open shift. See wiki/concepts/shift.md.
|
||||||
|
const shiftService = new ShiftService(db, eventLog, app.log);
|
||||||
|
|
||||||
// Pay station (pay-on-foot): quote an open session against the active tariff +
|
// Pay station (pay-on-foot): quote an open session against the active tariff +
|
||||||
// take payment → signed `payment` event. See wiki/concepts/tariff.md.
|
// take payment → signed `payment` event. The booth pay/exit/voucher/re-open
|
||||||
|
// endpoints require an open shift (passed in). See wiki/concepts/tariff.md.
|
||||||
const payStation = new PayStation(db, eventLog, app.log);
|
const payStation = new PayStation(db, eventLog, app.log);
|
||||||
await payRoutes(app, payStation);
|
await payRoutes(app, db, payStation, exitFlow, shiftService);
|
||||||
|
|
||||||
// Tariff composer: admin publishes effective-dated, immutable rate-card versions
|
// Tariff composer: admin publishes effective-dated, immutable rate-card versions
|
||||||
// the pay station prices against. See wiki/concepts/tariff.md.
|
// the pay station prices against. See wiki/concepts/tariff.md.
|
||||||
await tariffRoutes(app, db);
|
await tariffRoutes(app, db);
|
||||||
|
|
||||||
// Permit (subscription) admin CRUD. See wiki/entities/permit.md.
|
// Subscription admin CRUD + credential capture (arm/poll/cancel). See
|
||||||
await permitRoutes(app, db);
|
// wiki/entities/subscription.md.
|
||||||
|
await subscriptionRoutes(app, db, credentialCapture, eventLog, shiftService);
|
||||||
|
await subscriptionPlanRoutes(app, db);
|
||||||
|
|
||||||
// Shifts (manned mode): explicit open/close → signed shift_open / shift_z_report
|
// Shift open/close + drawer endpoints (shiftService constructed above).
|
||||||
// (sum payments by tender, print the Z-report). See wiki/concepts/shift.md.
|
await shiftRoutes(app, shiftService, db);
|
||||||
const shiftService = new ShiftService(db, eventLog, app.log);
|
|
||||||
await shiftRoutes(app, shiftService);
|
|
||||||
|
|
||||||
// Site config (capacity) + live occupancy. The FULL gate (refuse transient entry
|
// Site config (capacity) + live occupancy. The FULL gate (refuse transient entry
|
||||||
// at capacity) is in the entry flow. See wiki/concepts/capacity-occupancy.md.
|
// at capacity) is in the entry flow. See wiki/concepts/capacity-occupancy.md.
|
||||||
await siteRoutes(app, db);
|
await siteRoutes(app, db);
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
await logRoutes(app, logService);
|
||||||
|
|
||||||
|
// Periodic retention prune (age + row cap) so the log table stays bounded on the
|
||||||
|
// offline appliance. Runs hourly; unref'd so it never holds the process open.
|
||||||
|
const pruneTimer = setInterval(() => {
|
||||||
|
const n = logService.prune();
|
||||||
|
if (n > 0) app.log.debug(`pruned ${n} app_log rows`);
|
||||||
|
}, 60 * 60 * 1000);
|
||||||
|
pruneTimer.unref();
|
||||||
|
logService.prune(); // once at startup
|
||||||
|
app.addHook("onClose", async () => clearInterval(pruneTimer));
|
||||||
|
|
||||||
const unsubscribeInput = deviceEvents.onInput((e) => {
|
const unsubscribeInput = deviceEvents.onInput((e) => {
|
||||||
// Record every input edge as unsigned telemetry, keyed to the device that fired
|
// Record every input edge as unsigned telemetry, keyed to the device that fired
|
||||||
// (provenance). No lane — the pool-of-spaces model has none. The entry flow
|
// (provenance). No lane — the pool-of-spaces model has none. The entry flow
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { eq, devices, ledgerEvents, type Db } from "@parking/db";
|
import { eq, devices, ledgerEvents, type Db } from "@parking/db";
|
||||||
import { registry, type PrinterDevice } from "@parking/devices";
|
import { registry, formatStampSq as zStamp, type PrinterDevice } from "@parking/devices";
|
||||||
import type { LedgerPayload } from "@parking/shared";
|
import type { LedgerPayload } from "@parking/shared";
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
import type { EventLog } from "./event-log.js";
|
import type { EventLog } from "./event-log.js";
|
||||||
@@ -11,9 +11,16 @@ import type { EventLog } from "./event-log.js";
|
|||||||
// See wiki/concepts/shift.md.
|
// See wiki/concepts/shift.md.
|
||||||
|
|
||||||
export class ShiftAlreadyOpenError extends Error {
|
export class ShiftAlreadyOpenError extends Error {
|
||||||
constructor(operator: string) {
|
/** The operator who currently holds the open shift (may be someone else). */
|
||||||
super(`operator ${operator} already has an open shift`);
|
readonly heldBy: string;
|
||||||
|
constructor(operator: string, heldBy: string) {
|
||||||
|
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`,
|
||||||
|
);
|
||||||
this.name = "ShiftAlreadyOpenError";
|
this.name = "ShiftAlreadyOpenError";
|
||||||
|
this.heldBy = heldBy;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export class NoOpenShiftError extends Error {
|
export class NoOpenShiftError extends Error {
|
||||||
@@ -22,6 +29,33 @@ export class NoOpenShiftError extends Error {
|
|||||||
this.name = "NoOpenShiftError";
|
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. */
|
||||||
|
export class NoShiftOpenError extends Error {
|
||||||
|
constructor() {
|
||||||
|
super("no shift is open — open a shift before processing tickets");
|
||||||
|
this.name = "NoShiftOpenError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A COMPLETED shift, reconstructed from its signed `shift_z_report` (which carries
|
||||||
|
* all the figures in its payload). This is the unit of the shift-history feature.
|
||||||
|
* `id` is the z_report's ledger id (stable, for the UI list key / future deep-link). */
|
||||||
|
export interface ShiftSummary {
|
||||||
|
readonly id: string;
|
||||||
|
readonly index: number;
|
||||||
|
readonly operator: string;
|
||||||
|
readonly startedAt: string;
|
||||||
|
readonly endedAt: string;
|
||||||
|
readonly cashTotalMinor: number;
|
||||||
|
readonly cardTotalMinor: number;
|
||||||
|
readonly currency: string | null;
|
||||||
|
readonly paymentCount: number;
|
||||||
|
readonly openingFloatMinor: number;
|
||||||
|
readonly cashAddedMinor: number;
|
||||||
|
readonly cashRemovedMinor: number;
|
||||||
|
readonly expectedDrawerMinor: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ShiftReport {
|
export interface ShiftReport {
|
||||||
readonly operator: string;
|
readonly operator: string;
|
||||||
@@ -31,9 +65,25 @@ export interface ShiftReport {
|
|||||||
readonly cardTotalMinor: number;
|
readonly cardTotalMinor: number;
|
||||||
readonly currency: string | null;
|
readonly currency: string | null;
|
||||||
readonly paymentCount: number;
|
readonly paymentCount: number;
|
||||||
|
// --- Drawer (physical cash till; carries across shifts) ---
|
||||||
|
/** Cash in the drawer at shift start = prior shift's expected closing drawer. */
|
||||||
|
readonly openingFloatMinor: number;
|
||||||
|
/** Admin cash LOADED into the drawer during the shift (sum of + movements). */
|
||||||
|
readonly cashAddedMinor: number;
|
||||||
|
/** Admin cash REMOVED from the drawer during the shift (sum of − movements, as +). */
|
||||||
|
readonly cashRemovedMinor: number;
|
||||||
|
/** Expected drawer at close = opening + cashTaken + added − removed. Carries forward. */
|
||||||
|
readonly expectedDrawerMinor: number;
|
||||||
readonly printed: boolean;
|
readonly printed: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class InvalidCashMovementError extends Error {
|
||||||
|
constructor(msg: string) {
|
||||||
|
super(msg);
|
||||||
|
this.name = "InvalidCashMovementError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class ShiftService {
|
export class ShiftService {
|
||||||
readonly #db: Db;
|
readonly #db: Db;
|
||||||
readonly #log: EventLog;
|
readonly #log: EventLog;
|
||||||
@@ -45,6 +95,12 @@ export class ShiftService {
|
|||||||
this.#logger = logger;
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
/** Is there an open shift for this operator? Returns the open `shift_open` row or null. */
|
/** Is there an open shift for this operator? Returns the open `shift_open` row or null. */
|
||||||
openShiftFor(operator: string) {
|
openShiftFor(operator: string) {
|
||||||
// Scan shift events for this operator; the shift is open if the most recent
|
// Scan shift events for this operator; the shift is open if the most recent
|
||||||
@@ -60,36 +116,235 @@ export class ShiftService {
|
|||||||
return last && last.type === "shift_open" ? last : null;
|
return last && last.type === "shift_open" ? last : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Open a shift for the operator (explicit start). */
|
/**
|
||||||
async open(operator: string): Promise<{ startedAt: string }> {
|
* The SINGLE site-wide open shift, or null. A shift is a site-wide accountability
|
||||||
if (this.openShiftFor(operator)) throw new ShiftAlreadyOpenError(operator);
|
* 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.
|
||||||
|
*/
|
||||||
|
currentOpenShift() {
|
||||||
|
const rows = this.#db
|
||||||
|
.select()
|
||||||
|
.from(ledgerEvents)
|
||||||
|
.orderBy(ledgerEvents.index)
|
||||||
|
.all()
|
||||||
|
.filter((r) => r.type === "shift_open" || r.type === "shift_z_report");
|
||||||
|
const last = rows[rows.length - 1];
|
||||||
|
return last && last.type === "shift_open" ? last : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* COMPLETED shift history, newest first. Each closed shift is one signed
|
||||||
|
* `shift_z_report` whose payload already holds every figure, so this is a simple
|
||||||
|
* read of those rows (no re-summing). Optional filters:
|
||||||
|
* - operator: only this operator's shifts (the `identity` on the z_report).
|
||||||
|
* - from/to: ISO timestamps; keep shifts whose START falls in [from, to].
|
||||||
|
* The open shift (no z_report yet) is intentionally excluded — it's not a
|
||||||
|
* completed accountability period. Use `currentOpenShift()` for the live one.
|
||||||
|
*/
|
||||||
|
listShifts(opts: { operator?: string; from?: string; to?: string } = {}): ShiftSummary[] {
|
||||||
|
const rows = this.#db
|
||||||
|
.select()
|
||||||
|
.from(ledgerEvents)
|
||||||
|
.where(eq(ledgerEvents.type, "shift_z_report"))
|
||||||
|
.orderBy(ledgerEvents.index)
|
||||||
|
.all();
|
||||||
|
|
||||||
|
const out: ShiftSummary[] = [];
|
||||||
|
for (const r of rows) {
|
||||||
|
const pl = (r.payload ?? {}) as LedgerPayload & {
|
||||||
|
operator?: string;
|
||||||
|
startedAt?: string;
|
||||||
|
endedAt?: string;
|
||||||
|
cashTotalMinor?: number;
|
||||||
|
cardTotalMinor?: number;
|
||||||
|
paymentCount?: number;
|
||||||
|
openingFloatMinor?: number;
|
||||||
|
cashAddedMinor?: number;
|
||||||
|
cashRemovedMinor?: number;
|
||||||
|
expectedDrawerMinor?: number;
|
||||||
|
};
|
||||||
|
const operator = pl.operator ?? r.identity ?? "?";
|
||||||
|
const startedAt = pl.startedAt ?? r.occurredAt;
|
||||||
|
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,
|
||||||
|
operator,
|
||||||
|
startedAt,
|
||||||
|
endedAt: pl.endedAt ?? r.occurredAt,
|
||||||
|
cashTotalMinor: pl.cashTotalMinor ?? 0,
|
||||||
|
cardTotalMinor: pl.cardTotalMinor ?? 0,
|
||||||
|
currency: pl.currency ?? null,
|
||||||
|
paymentCount: pl.paymentCount ?? 0,
|
||||||
|
openingFloatMinor: pl.openingFloatMinor ?? 0,
|
||||||
|
cashAddedMinor: pl.cashAddedMinor ?? 0,
|
||||||
|
cashRemovedMinor: pl.cashRemovedMinor ?? 0,
|
||||||
|
expectedDrawerMinor: pl.expectedDrawerMinor ?? 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Newest first for the history list.
|
||||||
|
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();
|
||||||
|
return open;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The physical drawer balance at `at`: a fold over the SIGNED chain BY TIME (not
|
||||||
|
* by operator — a drawer voucher is the admin's, not the shift operator's). Cash
|
||||||
|
* payments add to the drawer; card payments never touch it. Drawer movements adjust
|
||||||
|
* it via three event types kept side-by-side:
|
||||||
|
* - `cash_in` (Mandat Arkëtimi): + amountMinor (positive magnitude)
|
||||||
|
* - `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.
|
||||||
|
*/
|
||||||
|
#drawerBalanceAt(at: string): { balanceMinor: number; currency: string | null } {
|
||||||
|
const rows = this.#db
|
||||||
|
.select()
|
||||||
|
.from(ledgerEvents)
|
||||||
|
.orderBy(ledgerEvents.index)
|
||||||
|
.all()
|
||||||
|
.filter(
|
||||||
|
(r) =>
|
||||||
|
r.occurredAt <= at &&
|
||||||
|
(r.type === "payment" ||
|
||||||
|
r.type === "cash_in" ||
|
||||||
|
r.type === "cash_out" ||
|
||||||
|
r.type === "cash_movement"),
|
||||||
|
);
|
||||||
|
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") {
|
||||||
|
// Only CASH enters the till; card settles to the bank.
|
||||||
|
if (pl.tender !== "card") balanceMinor += amt;
|
||||||
|
} else if (r.type === "cash_in") {
|
||||||
|
balanceMinor += Math.abs(amt); // receipt — direction is the type
|
||||||
|
} else if (r.type === "cash_out") {
|
||||||
|
balanceMinor -= Math.abs(amt); // disbursement — direction is the type
|
||||||
|
} else {
|
||||||
|
// legacy cash_movement amount is signed (+ load, − removal).
|
||||||
|
balanceMinor += amt;
|
||||||
|
}
|
||||||
|
if (pl.currency) currency = pl.currency;
|
||||||
|
}
|
||||||
|
return { balanceMinor, currency };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Next voucher number for a drawer-voucher type, e.g. `AR-0007` (cash_in) /
|
||||||
|
* `PA-0007` (cash_out). Sequential per type = count of existing events + 1. The
|
||||||
|
* number is human-facing (printed on the slip); the signed chain is the real
|
||||||
|
* record, so a small race only risks a duplicate label, never a lost voucher. */
|
||||||
|
#nextVoucherNo(type: "cash_in" | "cash_out"): string {
|
||||||
|
const prefix = type === "cash_in" ? "AR" : "PA";
|
||||||
|
const count = this.#db.select().from(ledgerEvents).where(eq(ledgerEvents.type, type)).all().length;
|
||||||
|
return `${prefix}-${String(count + 1).padStart(4, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Record a drawer cash VOUCHER — the direction is the event TYPE, not the sign of
|
||||||
|
* an amount (a receipt and a disbursement are different financial documents):
|
||||||
|
* - `cash_in` (Mandat Arkëtimi): cash entered the drawer (+).
|
||||||
|
* - `cash_out` (Mandat Pagese): cash left the drawer (−).
|
||||||
|
* `amountMinor` is always a POSITIVE magnitude. The voucher is OPERATOR-RAISED and
|
||||||
|
* ADMIN-AUTHORIZED: `operator` raised it, `authorizedBy` signed off (verified at the
|
||||||
|
* route). Returns the new drawer balance + the assigned voucher number, and prints
|
||||||
|
* a slip best-effort (the signed event is the record). See wiki/concepts/shift.md.
|
||||||
|
*/
|
||||||
|
async recordVoucher(args: {
|
||||||
|
type: "cash_in" | "cash_out";
|
||||||
|
operator: string;
|
||||||
|
authorizedBy: string;
|
||||||
|
amountMinor: number;
|
||||||
|
reason: string;
|
||||||
|
currency?: string;
|
||||||
|
}): Promise<{ type: "cash_in" | "cash_out"; amountMinor: number; voucherNo: string; balanceMinor: number; printed: boolean }> {
|
||||||
|
const { type, operator, authorizedBy, reason } = args;
|
||||||
|
if (!Number.isInteger(args.amountMinor) || args.amountMinor <= 0) {
|
||||||
|
throw new InvalidCashMovementError("amountMinor must be a positive integer (minor units)");
|
||||||
|
}
|
||||||
|
const amountMinor = args.amountMinor;
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const voucherNo = this.#nextVoucherNo(type);
|
||||||
|
await this.#log.append({
|
||||||
|
type,
|
||||||
|
source: "manual",
|
||||||
|
identity: operator, // who RAISED the voucher (the operator at the booth)
|
||||||
|
payload: {
|
||||||
|
amountMinor, // positive magnitude — direction is the type
|
||||||
|
...(reason ? { reason } : {}),
|
||||||
|
...(args.currency ? { currency: args.currency } : {}),
|
||||||
|
operator,
|
||||||
|
authorizedBy,
|
||||||
|
voucherNo,
|
||||||
|
},
|
||||||
|
occurredAt: now,
|
||||||
|
});
|
||||||
|
const { balanceMinor, currency } = this.#drawerBalanceAt(now);
|
||||||
|
const printed = await this.#printVoucher({ type, voucherNo, amountMinor, reason, operator, authorizedBy, currency, at: now });
|
||||||
|
this.#logger.info(
|
||||||
|
`${type} ${voucherNo} ${amountMinor} by ${operator} authz ${authorizedBy} (${reason || "no reason"}) → drawer ${balanceMinor}`,
|
||||||
|
);
|
||||||
|
return { type, amountMinor, voucherNo, balanceMinor, printed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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);
|
||||||
const startedAt = new Date().toISOString();
|
const startedAt = new Date().toISOString();
|
||||||
|
const { balanceMinor: openingFloatMinor } = this.#drawerBalanceAt(startedAt);
|
||||||
await this.#log.append({
|
await this.#log.append({
|
||||||
type: "shift_open",
|
type: "shift_open",
|
||||||
source: "manual",
|
source: "manual",
|
||||||
identity: operator, // the shift's operator; `identity` keys the shift to them
|
identity: operator, // the shift's operator; `identity` keys the shift to them
|
||||||
payload: { operator },
|
// 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 },
|
||||||
occurredAt: startedAt,
|
occurredAt: startedAt,
|
||||||
});
|
});
|
||||||
this.#logger.info(`shift opened for ${operator}`);
|
this.#logger.info(`shift opened for ${operator} (opening float ${openingFloatMinor})`);
|
||||||
return { startedAt };
|
return { startedAt, openingFloatMinor };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Close the operator's open shift: sum payments in the window, sign + print the Z-report. */
|
/**
|
||||||
async close(operator: string): Promise<ShiftReport> {
|
* Project the drawer/takings figures for a shift's window `[startedAt, asOf]`.
|
||||||
const open = this.openShiftFor(operator);
|
* Pure read over the signed chain — appends NOTHING — so it backs BOTH the
|
||||||
if (!open) throw new NoOpenShiftError(operator);
|
* mid-shift X-report (asOf = now, shift still open) and the Z-report at close
|
||||||
|
* (asOf = endedAt). The figures are identical projections; only the persistence
|
||||||
|
* differs (X = read-only, Z = signed + carried forward).
|
||||||
|
*/
|
||||||
|
#summariseWindow(
|
||||||
|
open: typeof ledgerEvents.$inferSelect,
|
||||||
|
asOf: string,
|
||||||
|
): Omit<ShiftReport, "printed"> {
|
||||||
|
const operator = open.identity ?? "?";
|
||||||
const startedAt = open.occurredAt;
|
const startedAt = open.occurredAt;
|
||||||
const endedAt = new Date().toISOString();
|
|
||||||
|
|
||||||
// All payments taken in [startedAt, endedAt], summed by tender. Payment time =
|
// All payments taken in [startedAt, asOf], summed by tender. Payment time =
|
||||||
// the operator who handled the money (decision: sum by payment time).
|
// the operator who handled the money (decision: sum by payment time).
|
||||||
const payments = this.#db
|
const payments = this.#db
|
||||||
.select()
|
.select()
|
||||||
.from(ledgerEvents)
|
.from(ledgerEvents)
|
||||||
.where(eq(ledgerEvents.type, "payment"))
|
.where(eq(ledgerEvents.type, "payment"))
|
||||||
.all()
|
.all()
|
||||||
.filter((r) => r.occurredAt >= startedAt && r.occurredAt <= endedAt);
|
.filter((r) => r.occurredAt >= startedAt && r.occurredAt <= asOf);
|
||||||
|
|
||||||
let cashTotalMinor = 0;
|
let cashTotalMinor = 0;
|
||||||
let cardTotalMinor = 0;
|
let cardTotalMinor = 0;
|
||||||
@@ -102,6 +357,92 @@ export class ShiftService {
|
|||||||
if (pl.currency) currency = pl.currency;
|
if (pl.currency) currency = pl.currency;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Drawer figures ---
|
||||||
|
// Opening float was fixed on shift_open (inherited from the chain at start);
|
||||||
|
// fall back to a fresh fold if an older shift_open lacks it.
|
||||||
|
const openPl = (open.payload ?? {}) as LedgerPayload & { openingFloatMinor?: number };
|
||||||
|
const openingFloatMinor =
|
||||||
|
typeof openPl.openingFloatMinor === "number"
|
||||||
|
? openPl.openingFloatMinor
|
||||||
|
: this.#drawerBalanceAt(startedAt).balanceMinor;
|
||||||
|
|
||||||
|
// Drawer movements within the window, split into added (+) and removed (−).
|
||||||
|
// Three side-by-side types: cash_in (+), cash_out (−), and the legacy signed-±
|
||||||
|
// cash_movement. All carry a POSITIVE magnitude except legacy, which is signed.
|
||||||
|
const movements = this.#db
|
||||||
|
.select()
|
||||||
|
.from(ledgerEvents)
|
||||||
|
.all()
|
||||||
|
.filter(
|
||||||
|
(r) =>
|
||||||
|
(r.type === "cash_in" || r.type === "cash_out" || r.type === "cash_movement") &&
|
||||||
|
r.occurredAt >= startedAt &&
|
||||||
|
r.occurredAt <= asOf,
|
||||||
|
);
|
||||||
|
let cashAddedMinor = 0;
|
||||||
|
let cashRemovedMinor = 0;
|
||||||
|
for (const m of movements) {
|
||||||
|
const pl = (m.payload ?? {}) as LedgerPayload;
|
||||||
|
const amt = typeof pl.amountMinor === "number" ? pl.amountMinor : 0;
|
||||||
|
if (m.type === "cash_in") cashAddedMinor += Math.abs(amt);
|
||||||
|
else if (m.type === "cash_out") cashRemovedMinor += Math.abs(amt);
|
||||||
|
else if (amt >= 0) cashAddedMinor += amt; // legacy + load
|
||||||
|
else cashRemovedMinor += -amt; // legacy − removal, store as positive magnitude
|
||||||
|
if (pl.currency) currency = pl.currency;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expected drawer = opening + cash taken + added − removed. At close this is the
|
||||||
|
// figure the NEXT shift inherits as its opening float.
|
||||||
|
const expectedDrawerMinor = openingFloatMinor + cashTotalMinor + cashAddedMinor - cashRemovedMinor;
|
||||||
|
|
||||||
|
return {
|
||||||
|
operator,
|
||||||
|
startedAt,
|
||||||
|
endedAt: asOf,
|
||||||
|
cashTotalMinor,
|
||||||
|
cardTotalMinor,
|
||||||
|
currency,
|
||||||
|
paymentCount: payments.length,
|
||||||
|
openingFloatMinor,
|
||||||
|
cashAddedMinor,
|
||||||
|
cashRemovedMinor,
|
||||||
|
expectedDrawerMinor,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mid-shift X-report: a READ-ONLY "so far" snapshot of the open shift's takings +
|
||||||
|
* drawer, computed as of now. Appends nothing (it's not an accountability mark —
|
||||||
|
* the Z-report at close is). Returns null when no shift is open. The same
|
||||||
|
* 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();
|
||||||
|
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);
|
||||||
|
const endedAt = new Date().toISOString();
|
||||||
|
|
||||||
|
const report = this.#summariseWindow(open, endedAt);
|
||||||
|
const {
|
||||||
|
startedAt,
|
||||||
|
cashTotalMinor,
|
||||||
|
cardTotalMinor,
|
||||||
|
currency,
|
||||||
|
paymentCount,
|
||||||
|
openingFloatMinor,
|
||||||
|
cashAddedMinor,
|
||||||
|
cashRemovedMinor,
|
||||||
|
expectedDrawerMinor,
|
||||||
|
} = report;
|
||||||
|
|
||||||
await this.#log.append({
|
await this.#log.append({
|
||||||
type: "shift_z_report",
|
type: "shift_z_report",
|
||||||
source: "manual",
|
source: "manual",
|
||||||
@@ -113,24 +454,21 @@ export class ShiftService {
|
|||||||
cashTotalMinor,
|
cashTotalMinor,
|
||||||
cardTotalMinor,
|
cardTotalMinor,
|
||||||
currency: currency ?? undefined,
|
currency: currency ?? undefined,
|
||||||
paymentCount: payments.length,
|
paymentCount,
|
||||||
|
openingFloatMinor,
|
||||||
|
cashAddedMinor,
|
||||||
|
cashRemovedMinor,
|
||||||
|
expectedDrawerMinor,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const printed = await this.#printZReport({
|
const printed = await this.#printZReport(report);
|
||||||
operator,
|
|
||||||
startedAt,
|
|
||||||
endedAt,
|
|
||||||
cashTotalMinor,
|
|
||||||
cardTotalMinor,
|
|
||||||
currency,
|
|
||||||
paymentCount: payments.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
this.#logger.info(
|
this.#logger.info(
|
||||||
`shift closed for ${operator}: cash ${cashTotalMinor} card ${cardTotalMinor} (${payments.length} payments)`,
|
`shift closed for ${operator}: cash ${cashTotalMinor} card ${cardTotalMinor} (${paymentCount} payments); ` +
|
||||||
|
`drawer open ${openingFloatMinor} +${cashAddedMinor} −${cashRemovedMinor} → expected ${expectedDrawerMinor}`,
|
||||||
);
|
);
|
||||||
return { operator, startedAt, endedAt, cashTotalMinor, cardTotalMinor, currency, paymentCount: payments.length, printed };
|
return { ...report, printed };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Print the Z-report on a booth-receipt printer (best-effort; the signed event
|
/** Print the Z-report on a booth-receipt printer (best-effort; the signed event
|
||||||
@@ -143,17 +481,26 @@ export class ShiftService {
|
|||||||
}
|
}
|
||||||
const cur = r.currency ?? "";
|
const cur = r.currency ?? "";
|
||||||
const money = (m: number) => (m / 100).toFixed(2);
|
const money = (m: number) => (m / 100).toFixed(2);
|
||||||
|
// 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 = [
|
const lines = [
|
||||||
`Operator: ${r.operator}`,
|
`Operatori: ${r.operator}`,
|
||||||
`From: ${r.startedAt}`,
|
`Nga: ${zStamp(r.startedAt)}`,
|
||||||
`To: ${r.endedAt}`,
|
`Deri: ${zStamp(r.endedAt)}`,
|
||||||
"",
|
"",
|
||||||
`Payments: ${r.paymentCount}`,
|
`Pagesa: ${r.paymentCount}`,
|
||||||
`Cash: ${money(r.cashTotalMinor)} ${cur}`,
|
`Para në dorë: ${money(r.cashTotalMinor)} ${cur}`,
|
||||||
`Card: ${money(r.cardTotalMinor)} ${cur}`,
|
`Kartë: ${money(r.cardTotalMinor)} ${cur}`,
|
||||||
|
"",
|
||||||
|
"-- Arka --",
|
||||||
|
`Fillimi (kusur): ${money(r.openingFloatMinor)} ${cur}`,
|
||||||
|
`Para të marra: ${money(r.cashTotalMinor)} ${cur}`,
|
||||||
|
`Para të shtuara: ${money(r.cashAddedMinor)} ${cur}`,
|
||||||
|
`Para të hequra: ${money(r.cashRemovedMinor)} ${cur}`,
|
||||||
|
`Arka e pritur: ${money(r.expectedDrawerMinor)} ${cur}`,
|
||||||
];
|
];
|
||||||
try {
|
try {
|
||||||
await printer.printReport({ title: "SHIFT Z-REPORT", lines });
|
await printer.printReport({ title: "RAPORT TURNI", lines });
|
||||||
return true;
|
return true;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.#logger.warn(`Z-report print failed for ${r.operator}: ${(err as Error).message} (event recorded)`);
|
this.#logger.warn(`Z-report print failed for ${r.operator}: ${(err as Error).message} (event recorded)`);
|
||||||
@@ -161,6 +508,46 @@ export class ShiftService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Print a drawer-voucher slip (Mandat Arkëtimi / Mandat Pagese). Best-effort —
|
||||||
|
* the signed event is the record; a failed print doesn't undo the voucher.
|
||||||
|
* Albanian, like every customer/operator-facing slip (see i18n.md). */
|
||||||
|
async #printVoucher(v: {
|
||||||
|
type: "cash_in" | "cash_out";
|
||||||
|
voucherNo: string;
|
||||||
|
amountMinor: number;
|
||||||
|
reason: string;
|
||||||
|
operator: string;
|
||||||
|
authorizedBy: string;
|
||||||
|
currency: string | null;
|
||||||
|
at: string;
|
||||||
|
}): Promise<boolean> {
|
||||||
|
const printer = await this.#boothPrinter();
|
||||||
|
if (!printer) {
|
||||||
|
this.#logger.warn(`no booth-receipt printer — ${v.type} ${v.voucherNo} not printed (event recorded)`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const cur = v.currency ?? "";
|
||||||
|
const money = (m: number) => (m / 100).toFixed(2);
|
||||||
|
const title = v.type === "cash_in" ? "MANDAT ARKËTIMI" : "MANDAT PAGESE";
|
||||||
|
const lines = [
|
||||||
|
`Mandat Nr.: ${v.voucherNo}`,
|
||||||
|
`Data: ${zStamp(v.at)}`,
|
||||||
|
"",
|
||||||
|
`Shuma: ${money(v.amountMinor)} ${cur}`,
|
||||||
|
`Arsyeja: ${v.reason || "-"}`,
|
||||||
|
"",
|
||||||
|
`Hapur nga: ${v.operator}`,
|
||||||
|
`Autorizoi: ${v.authorizedBy}`,
|
||||||
|
];
|
||||||
|
try {
|
||||||
|
await printer.printReport({ title, lines });
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.warn(`${v.type} ${v.voucherNo} print failed: ${(err as Error).message} (event recorded)`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** First enabled booth-receipt printer, or any enabled printer. */
|
/** First enabled booth-receipt printer, or any enabled printer. */
|
||||||
async #boothPrinter(): Promise<PrinterDevice | null> {
|
async #boothPrinter(): Promise<PrinterDevice | null> {
|
||||||
const rows = await this.#db.select().from(devices).where(eq(devices.category, "printer")).all();
|
const rows = await this.#db.select().from(devices).where(eq(devices.category, "printer")).all();
|
||||||
|
|||||||
@@ -58,3 +58,30 @@ export function buildSigner(log?: { warn: (msg: string) => void }): Signer {
|
|||||||
"event signing: no signing key. Set EVENT_SIGNING_KEY (>=16 chars) for the append-only event chain.",
|
"event signing: no signing key. Set EVENT_SIGNING_KEY (>=16 chars) for the append-only event chain.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the signer that can VERIFY an existing event, by its stored `keyId`.
|
||||||
|
* Appends always use the one signer from buildSigner(), but a chain can contain
|
||||||
|
* events signed under different keys across a rotation (e.g. the JWT_SECRET
|
||||||
|
* fallback before a dedicated EVENT_SIGNING_KEY was set, or an ATECC608 swap).
|
||||||
|
* Each event stores its own `keyId`, so verifyChain() must check each row against
|
||||||
|
* the key that produced it — not the current append-signer. Returns undefined for
|
||||||
|
* an unknown keyId (the key is gone / not configured), which verifyChain surfaces
|
||||||
|
* as a distinct failure rather than a false "tampered" alarm.
|
||||||
|
*
|
||||||
|
* TODO(atecc608): add an "atecc608-slotN" case returning a public-key verifier.
|
||||||
|
*/
|
||||||
|
export function buildVerifier(keyId: string): Signer | undefined {
|
||||||
|
switch (keyId) {
|
||||||
|
case "sw-hmac-v2": {
|
||||||
|
const k = process.env.EVENT_SIGNING_KEY;
|
||||||
|
return k && k.length >= 16 ? new SoftwareSigner(k, "sw-hmac-v2") : undefined;
|
||||||
|
}
|
||||||
|
case "sw-hmac-jwtfallback": {
|
||||||
|
const k = process.env.JWT_SECRET;
|
||||||
|
return k && k.length >= 16 ? new SoftwareSigner(k, "sw-hmac-jwtfallback") : undefined;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { deviceEvents as deviceEventsTable, snapshots, type Db } from "@parking/
|
|||||||
import { registry, type CameraDevice } from "@parking/devices";
|
import { registry, type CameraDevice } from "@parking/devices";
|
||||||
import type { FastifyBaseLogger } from "fastify";
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
import { devicesByDirection, type FlowDirection } from "./device-resolve.js";
|
import { devicesByDirection, type FlowDirection } from "./device-resolve.js";
|
||||||
|
import type { VisionClient } from "./vision-client.js";
|
||||||
|
|
||||||
// Camera snapshot capture, fired AFTER the barrier opens and never awaited on the
|
// Camera snapshot capture, fired AFTER the barrier opens and never awaited on the
|
||||||
// open path (decision 2026-06-16): a snapshot is EVIDENCE, not a gate. A camera
|
// open path (decision 2026-06-16): a snapshot is EVIDENCE, not a gate. A camera
|
||||||
@@ -15,13 +16,32 @@ import { devicesByDirection, type FlowDirection } from "./device-resolve.js";
|
|||||||
// → a `snapshots` row + a `kind:"snapshot"` telemetry device_event; a failure → a
|
// → a `snapshots` row + a `kind:"snapshot"` telemetry device_event; a failure → a
|
||||||
// telemetry device_event only. The caller passes the session `identity` so the image
|
// telemetry device_event only. The caller passes the session `identity` so the image
|
||||||
// links to the signed vehicle_entry/exit.
|
// links to the signed vehicle_entry/exit.
|
||||||
|
//
|
||||||
|
// ANPR rides this snapshot (2026-06-19). A transient button-press or a subscriber
|
||||||
|
// QR/RFID read triggers the entry/exit, which fires THIS snapshot — that is exactly the
|
||||||
|
// moment to recognize the plate, off the SAME image, tied to the SAME session identity.
|
||||||
|
// So when a `vision` client is passed AND the camera opts in (config.anpr), each stored
|
||||||
|
// snapshot is sent to the vision service and the extracted plate is RECORDED against the
|
||||||
|
// session (a `kind:"read"` device_event with plate/confidence/snapshotId). ADVISORY +
|
||||||
|
// fire-and-forget: it never blocks the open and never changes the entry/exit decision —
|
||||||
|
// it's a record ("session X entered on plate AA558EE"). No polling; recognition only
|
||||||
|
// happens on a real entry/exit. See wiki/entities/opencv-anpr-service.md.
|
||||||
|
|
||||||
interface SnapshotJob {
|
interface SnapshotJob {
|
||||||
readonly db: Db;
|
readonly db: Db;
|
||||||
readonly direction: FlowDirection;
|
readonly direction: FlowDirection;
|
||||||
/** Session/credential ref (ticket id, plate, permit car key) — links to the ledger. */
|
/** Session/credential ref (ticket id, plate, subscription car key) — links to the ledger. */
|
||||||
readonly identity: string;
|
readonly identity: string;
|
||||||
readonly logger: FastifyBaseLogger;
|
readonly logger: FastifyBaseLogger;
|
||||||
|
/** Optional vision client — when present, ANPR runs on each captured image from an
|
||||||
|
* `anpr`-enabled camera and records the plate against `identity`. Advisory only. */
|
||||||
|
readonly vision?: VisionClient | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Camera config flag opting it into snapshot-triggered ANPR. */
|
||||||
|
interface CameraConfig {
|
||||||
|
readonly anpr?: boolean;
|
||||||
|
readonly [k: string]: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -30,7 +50,7 @@ interface SnapshotJob {
|
|||||||
* The caller must NOT block its open path on this.
|
* The caller must NOT block its open path on this.
|
||||||
*/
|
*/
|
||||||
export function snapshotAsync(job: SnapshotJob): Promise<string[]> {
|
export function snapshotAsync(job: SnapshotJob): Promise<string[]> {
|
||||||
const { db, direction, identity, logger } = job;
|
const { db, direction, identity, logger, vision } = job;
|
||||||
const rows = devicesByDirection(db, "camera", direction);
|
const rows = devicesByDirection(db, "camera", direction);
|
||||||
if (rows.length === 0) return Promise.resolve([]);
|
if (rows.length === 0) return Promise.resolve([]);
|
||||||
|
|
||||||
@@ -57,6 +77,12 @@ export function snapshotAsync(job: SnapshotJob): Promise<string[]> {
|
|||||||
.run();
|
.run();
|
||||||
// Telemetry breadcrumb pointing at the stored image (NOT the bytes).
|
// Telemetry breadcrumb pointing at the stored image (NOT the bytes).
|
||||||
recordEvent(db, direction, row.id, identity, { snapshotId: id, ok: true }, logger);
|
recordEvent(db, direction, row.id, identity, { snapshotId: id, ok: true }, logger);
|
||||||
|
|
||||||
|
// ANPR off the SAME image, tied to the SAME session — when vision is enabled
|
||||||
|
// and this camera opts in. Fire-and-forget: never delays the open path.
|
||||||
|
if (vision?.enabled && (row.config as CameraConfig)?.anpr === true) {
|
||||||
|
void recognizePlate(db, vision, row.id, direction, identity, id, shot, logger);
|
||||||
|
}
|
||||||
return id;
|
return id;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
recordFailure(db, direction, row.id, identity, (err as Error).message, logger);
|
recordFailure(db, direction, row.id, identity, (err as Error).message, logger);
|
||||||
@@ -66,6 +92,55 @@ export function snapshotAsync(job: SnapshotJob): Promise<string[]> {
|
|||||||
).then((ids) => ids.filter((id): id is string => id != null));
|
).then((ids) => ids.filter((id): id is string => id != null));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recognize the plate off a captured entry/exit image and RECORD it against the session
|
||||||
|
* `identity` — an unsigned `kind:"read"` device_event carrying the plate, confidence,
|
||||||
|
* region, and the `snapshotId` it was read from. Advisory: this records the plate
|
||||||
|
* observed for the session; it does NOT feed the access decision (the flow already
|
||||||
|
* decided). A low-confidence/no-plate result records nothing (a shaky read isn't a fact).
|
||||||
|
* Best-effort + fail-soft — a vision error never surfaces on the (already-open) path.
|
||||||
|
*/
|
||||||
|
async function recognizePlate(
|
||||||
|
db: Db,
|
||||||
|
vision: VisionClient,
|
||||||
|
deviceId: string,
|
||||||
|
direction: FlowDirection,
|
||||||
|
identity: string,
|
||||||
|
snapshotId: string,
|
||||||
|
shot: { bytes: Buffer; contentType: string },
|
||||||
|
logger: FastifyBaseLogger,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const result = await vision.analyze(shot.bytes, shot.contentType);
|
||||||
|
if (!result || !result.plate || result.lowConfidence) return; // nothing trustworthy to record
|
||||||
|
const plate = result.plate.text.trim().toUpperCase();
|
||||||
|
if (!plate) return;
|
||||||
|
db.insert(deviceEventsTable)
|
||||||
|
.values({
|
||||||
|
id: randomUUID(),
|
||||||
|
deviceId,
|
||||||
|
category: "camera",
|
||||||
|
kind: "read",
|
||||||
|
// `identity` ties the plate to the session; `snapshotId` to the evidence image.
|
||||||
|
detail: {
|
||||||
|
identity,
|
||||||
|
direction,
|
||||||
|
plate,
|
||||||
|
confidence: result.plate.confidence,
|
||||||
|
region: result.plate.region ?? null,
|
||||||
|
modelVersion: result.modelVersion,
|
||||||
|
snapshotId,
|
||||||
|
source: "entry-exit-snapshot",
|
||||||
|
},
|
||||||
|
occurredAt: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
logger.info(`anpr plate '${plate}' (${result.plate.confidence.toFixed(3)}) for ${identity}`);
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn(`anpr recognize failed (${identity}): ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Build a live camera adapter from a resolved devices row, or null. */
|
/** Build a live camera adapter from a resolved devices row, or null. */
|
||||||
function buildCamera(row: { driverId: string; config: unknown }): CameraDevice | null {
|
function buildCamera(row: { driverId: string; config: unknown }): CameraDevice | null {
|
||||||
const driver = registry.get(row.driverId);
|
const driver = registry.get(row.driverId);
|
||||||
|
|||||||
@@ -0,0 +1,390 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import {
|
||||||
|
eq,
|
||||||
|
ledgerEvents,
|
||||||
|
sessions,
|
||||||
|
subscriptionCredentials,
|
||||||
|
subscriptionPlates,
|
||||||
|
subscriptions,
|
||||||
|
type Db,
|
||||||
|
type DeviceRow,
|
||||||
|
} from "@parking/db";
|
||||||
|
import { registry, type AccessControlDevice } from "@parking/devices";
|
||||||
|
import { reasonPayload, type PlanTimeframes, type ReasonCode } from "@parking/shared";
|
||||||
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
import { printWindowChargeNotice } from "./booth-print.js";
|
||||||
|
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
||||||
|
import type { EventLog } from "./event-log.js";
|
||||||
|
import { type FlowDirection, type ResolvedRelay } from "./device-resolve.js";
|
||||||
|
import { snapshotAsync } from "./snapshot.js";
|
||||||
|
import { planVersionById, windowCharge, windowOwedBetween } from "./subscription-window.js";
|
||||||
|
import type { VisionClient } from "./vision-client.js";
|
||||||
|
|
||||||
|
// SUBSCRIPTION flow: a subscriber identified by card/QR/plate enters/exits without
|
||||||
|
// paying per stay (they're on a recurring plan). Reached from the read dispatcher
|
||||||
|
// when a read matches a subscription (not an open ticket). See
|
||||||
|
// wiki/entities/subscription.md.
|
||||||
|
//
|
||||||
|
// Two optional, independent bindings:
|
||||||
|
// - car-count: `maxConcurrent` (default 1, null = unbound) — how many of the
|
||||||
|
// subscription's cars may be inside at once; enforced over the session projection.
|
||||||
|
// - plate: optional `plates[]` — when set, a matching plate is an accepted identity
|
||||||
|
// too (card/QR OR plate). When unset, any car may use the subscription's card/QR.
|
||||||
|
//
|
||||||
|
// Direction is inferred from the SUBSCRIPTION's open-session state, NOT the specific
|
||||||
|
// credential read — so ANY of a subscription's credentials (QR / RFID / NFC / plate)
|
||||||
|
// may open or close a session. Entry mints a fresh per-occurrence session id (the
|
||||||
|
// ledger `identity`); a read with no open occurrence → ENTRY; with ≥1 open → EXIT the
|
||||||
|
// OLDEST open occurrence (FIFO). A fleet (maxConcurrent > 1) thus has several open
|
||||||
|
// occurrences at once; each read closes one. This decouples exit from the entry
|
||||||
|
// credential (you can enter with QR and leave with the card).
|
||||||
|
//
|
||||||
|
// NB: the SIGNED ledger payload still carries `permitId` (immutable history — see the
|
||||||
|
// schema note); the per-occurrence `identity` is the session key. The mutable master
|
||||||
|
// data / code is "subscription"; the on-chain field name is left as-is so historical
|
||||||
|
// events keep verifying.
|
||||||
|
|
||||||
|
export interface SubscriptionMatch {
|
||||||
|
readonly subscriptionId: string;
|
||||||
|
/** The specific credential/plate value read (for logging/anomalies). NOT the
|
||||||
|
* session key — sessions are keyed by subscription occurrence, so a different
|
||||||
|
* credential of the same subscription can close the session it opened. */
|
||||||
|
readonly carKey: string;
|
||||||
|
readonly via: "card" | "qr" | "plate";
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SubscriptionFlow {
|
||||||
|
readonly #db: Db;
|
||||||
|
readonly #log: EventLog;
|
||||||
|
readonly #logger: FastifyBaseLogger;
|
||||||
|
readonly #inFlight = new Set<string>();
|
||||||
|
/** Optional vision client — passed to snapshotAsync so ANPR runs on the subscriber image. */
|
||||||
|
readonly #vision: VisionClient | null;
|
||||||
|
|
||||||
|
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger, vision: VisionClient | null = null) {
|
||||||
|
this.#db = db;
|
||||||
|
this.#log = log;
|
||||||
|
this.#logger = logger;
|
||||||
|
this.#vision = vision;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve a read to a subscription (by card/QR credential, or a bound plate), or null. */
|
||||||
|
match(e: DeviceReadEvent): SubscriptionMatch | null {
|
||||||
|
// Card / QR / generic credential value.
|
||||||
|
const cred = this.#db
|
||||||
|
.select()
|
||||||
|
.from(subscriptionCredentials)
|
||||||
|
.where(eq(subscriptionCredentials.value, e.value))
|
||||||
|
.get();
|
||||||
|
if (cred) {
|
||||||
|
return { subscriptionId: cred.subscriptionId, carKey: e.value, via: cred.kind === "qr" ? "qr" : "card" };
|
||||||
|
}
|
||||||
|
// Plate binding: a read plate that matches a subscription's bound plate is an identity.
|
||||||
|
if (e.kind === "plate") {
|
||||||
|
const plate = this.#db.select().from(subscriptionPlates).where(eq(subscriptionPlates.plate, e.value)).get();
|
||||||
|
if (plate) return { subscriptionId: plate.subscriptionId, carKey: e.value, via: "plate" };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Run the subscription entry/exit for a matched read at a barrier. `resolved` is the
|
||||||
|
* reader's bound relay; its direction constrains, "both" defers to session state. */
|
||||||
|
async run(resolved: ResolvedRelay, e: DeviceReadEvent, m: SubscriptionMatch): Promise<ReadOutcome> {
|
||||||
|
const key = `${m.subscriptionId}:${m.carKey}`;
|
||||||
|
if (this.#inFlight.has(key)) return { accepted: false, reason: "duplicate read in flight" };
|
||||||
|
this.#inFlight.add(key);
|
||||||
|
try {
|
||||||
|
return await this.#run(resolved, e, m);
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.error(`subscription-flow failed: ${(err as Error).message}`);
|
||||||
|
return { accepted: false, reason: (err as Error).message };
|
||||||
|
} finally {
|
||||||
|
this.#inFlight.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async #run(resolved: ResolvedRelay, e: DeviceReadEvent, m: SubscriptionMatch): Promise<ReadOutcome> {
|
||||||
|
// The physical side the reader sits at — used to fire the right camera on a refusal
|
||||||
|
// that happens BEFORE we infer the entry/exit verb ("both" defers to entry).
|
||||||
|
const lane: FlowDirection = resolved.direction === "exit" ? "exit" : "entry";
|
||||||
|
const sub = this.#db.select().from(subscriptions).where(eq(subscriptions.id, m.subscriptionId)).get();
|
||||||
|
if (!sub) return { accepted: false, reason: await this.#reject(m, lane, "sub.refused.notFound") };
|
||||||
|
|
||||||
|
// Validity: active + within the coverage window.
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const invalid =
|
||||||
|
sub.status !== "active" ||
|
||||||
|
(sub.validFrom != null && now < sub.validFrom) ||
|
||||||
|
(sub.validTo != null && now > sub.validTo);
|
||||||
|
if (invalid) {
|
||||||
|
const reason = await this.#reject(m, lane, "sub.refused.outOfWindow", { status: sub.status });
|
||||||
|
return { accepted: false, reason };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Direction: the BARRIER the reader sits at decides the verb — an entry-lane read
|
||||||
|
// is an ENTRY, an exit-lane read is an EXIT. (The credential is decoupled from the
|
||||||
|
// session, so we can't and needn't infer from "which credential".) A "both" barrier
|
||||||
|
// has no physical side, so there we infer from state: open occurrence → exit, else
|
||||||
|
// entry. This is what lets a FLEET admit several cars (each entry-lane read is an
|
||||||
|
// entry) yet exit any of them with ANY credential (FIFO).
|
||||||
|
const open = this.#openOccurrences(m.subscriptionId);
|
||||||
|
const verb: FlowDirection =
|
||||||
|
resolved.direction === "entry"
|
||||||
|
? "entry"
|
||||||
|
: resolved.direction === "exit"
|
||||||
|
? "exit"
|
||||||
|
: open.length > 0
|
||||||
|
? "exit"
|
||||||
|
: "entry";
|
||||||
|
|
||||||
|
const source = m.via === "plate" ? "lpr" : m.via === "qr" ? "qr" : "wiegand";
|
||||||
|
|
||||||
|
if (verb === "exit") {
|
||||||
|
// EXIT: close the OLDEST open occurrence (FIFO). Its occurrence id is the session
|
||||||
|
// key; the credential just read may differ from the one that opened it. If the
|
||||||
|
// subscription has NOTHING open, an exit read is a no-op anti-passback signal.
|
||||||
|
const oldest = open[0];
|
||||||
|
if (!oldest) {
|
||||||
|
const reason = await this.#reject(m, "exit", "sub.refused.noSession");
|
||||||
|
return { accepted: false, direction: "exit", reason };
|
||||||
|
}
|
||||||
|
const occurrenceId = oldest.identity;
|
||||||
|
|
||||||
|
// TARIFF BRIDGE — exit gate. Total owed = carried early-entry charge (signed on the
|
||||||
|
// entry payload) + a late-exit charge (window-close→now) computed fresh. If the
|
||||||
|
// subscriber owes money and hasn't paid it, REFUSE the exit (like the transient
|
||||||
|
// unpaid/overstay gate) — they settle at the booth (a signed `payment` keyed to the
|
||||||
|
// occurrence), then re-scan. This is a host-ONLINE business gate; the offline path
|
||||||
|
// still fails open. See wiki/entities/subscription.md ("tariff bridge").
|
||||||
|
const owed = this.#windowOwed(occurrenceId, m.subscriptionId, sub.planVersionId);
|
||||||
|
const paid = this.#windowPaidMinor(occurrenceId);
|
||||||
|
if (owed.totalMinor - paid > 0) {
|
||||||
|
const reason = await this.#reject(m, "exit", "sub.refused.unpaidWindow", {
|
||||||
|
amount: ((owed.totalMinor - paid) / 100).toFixed(2),
|
||||||
|
currency: owed.currency ?? "",
|
||||||
|
});
|
||||||
|
return { accepted: false, direction: "exit", reason };
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.#log.append({
|
||||||
|
type: "vehicle_exit",
|
||||||
|
direction: "exit",
|
||||||
|
source,
|
||||||
|
identity: occurrenceId,
|
||||||
|
// `permitId` carries the subscription id; `via` records which credential left.
|
||||||
|
payload: { sessionRef: occurrenceId, permitId: m.subscriptionId, via: m.via },
|
||||||
|
});
|
||||||
|
await this.#open(resolved, "exit", occurrenceId, "subscription exit");
|
||||||
|
this.#closeCache(occurrenceId);
|
||||||
|
return { accepted: true, direction: "exit" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ENTRY: enforce the car-count binding (maxConcurrent), then sign + open. Mint a
|
||||||
|
// fresh per-occurrence id so a fleet can have several open at once.
|
||||||
|
if (sub.maxConcurrent != null && open.length >= sub.maxConcurrent) {
|
||||||
|
const reason = await this.#reject(m, "entry", "sub.refused.atCapacity", {
|
||||||
|
inUse: open.length,
|
||||||
|
max: sub.maxConcurrent,
|
||||||
|
});
|
||||||
|
return { accepted: false, direction: "entry", reason };
|
||||||
|
}
|
||||||
|
|
||||||
|
// TARIFF BRIDGE — early entry. If the plan has time windows and this scan is before
|
||||||
|
// the window opens, the subscriber owes the transient tariff for arrival→window-open.
|
||||||
|
// We DEFER it (open now, collect at exit): stamp the owed amount on the SIGNED entry
|
||||||
|
// payload (the source of truth — `windowOwedMinor`), so the exit gate reads it back
|
||||||
|
// from the chain. Plans without timeframes return null → nothing owed. See
|
||||||
|
// wiki/entities/subscription.md.
|
||||||
|
const entryCharge = windowCharge(this.#db, sub.planVersionId, now, "entry");
|
||||||
|
|
||||||
|
// A short, unique occurrence id. The subscription id is NOT embedded — it rides in
|
||||||
|
// the payload's `permitId` (which every fold matches on), so the key stays compact.
|
||||||
|
const occurrenceId = `SUBSESS-${randomUUID().replace(/-/g, "").slice(0, 12)}`;
|
||||||
|
await this.#log.append({
|
||||||
|
type: "vehicle_entry",
|
||||||
|
direction: "entry",
|
||||||
|
source,
|
||||||
|
identity: occurrenceId,
|
||||||
|
// No ticket, no fee — the subscription IS the authorization. Recorded for audit.
|
||||||
|
// `permitId`/`permit` are the on-chain field names (immutable). A deferred early-
|
||||||
|
// entry charge is signed here (windowOwedMinor + the priced gap) so it's owed at exit.
|
||||||
|
payload: {
|
||||||
|
sessionRef: occurrenceId,
|
||||||
|
permitId: m.subscriptionId,
|
||||||
|
permit: true,
|
||||||
|
via: m.via,
|
||||||
|
...(entryCharge
|
||||||
|
? {
|
||||||
|
windowOwedMinor: entryCharge.amountMinor,
|
||||||
|
windowCurrency: entryCharge.currency,
|
||||||
|
windowTariffVersionId: entryCharge.tariffVersionId,
|
||||||
|
windowGapStart: entryCharge.gapStart,
|
||||||
|
windowGapEnd: entryCharge.gapEnd,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
occurredAt: now,
|
||||||
|
});
|
||||||
|
if (entryCharge) {
|
||||||
|
this.#logger.info(
|
||||||
|
`subscription early-entry charge ${entryCharge.amountMinor} ${entryCharge.currency} (${entryCharge.minutes}min) deferred on ${occurrenceId}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.#open(resolved, "entry", occurrenceId, "subscription entry");
|
||||||
|
try {
|
||||||
|
this.#db
|
||||||
|
.insert(sessions)
|
||||||
|
.values({
|
||||||
|
id: occurrenceId,
|
||||||
|
identity: occurrenceId,
|
||||||
|
source: m.via === "plate" ? "lpr" : "wiegand",
|
||||||
|
subscriptionId: m.subscriptionId,
|
||||||
|
enteredAt: now,
|
||||||
|
state: "open",
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.error(`session-cache insert failed for ${occurrenceId}: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
// BEST-EFFORT: print an advisory "out-of-window" slip so the subscriber has paper
|
||||||
|
// proof a fee is pending (the final amount is computed at the booth on settlement,
|
||||||
|
// combining early-entry + any late-exit time). AFTER the open + cache, and fully
|
||||||
|
// swallowed — a missing/failed printer must NEVER block or delay the barrier.
|
||||||
|
if (entryCharge) {
|
||||||
|
const tf = (planVersionById(this.#db, sub.planVersionId)?.timeframes ?? null) as PlanTimeframes | null;
|
||||||
|
void printWindowChargeNotice(
|
||||||
|
this.#db,
|
||||||
|
{ occurrenceId, holderName: sub.holderName, at: now, windowOpensMin: tf?.fromMin, edge: "entry" },
|
||||||
|
this.#logger,
|
||||||
|
).catch((err) => this.#logger.warn(`out-of-window slip print failed for ${occurrenceId}: ${(err as Error).message}`));
|
||||||
|
}
|
||||||
|
return { accepted: true, direction: "entry" };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Total out-of-window charge owed for an occurrence right now: the transient cost of the
|
||||||
|
* minutes parked OUTSIDE the plan's window over the WHOLE stay `[entry, now]` — ONE
|
||||||
|
* computation covering early entry AND late exit (not entry-gap + exit-gap, which
|
||||||
|
* double-counts and lets the exit gap reach a previous day's close). A plan without
|
||||||
|
* timeframes yields 0. Single source of truth shared with the booth quote.
|
||||||
|
*/
|
||||||
|
#windowOwed(
|
||||||
|
occurrenceId: string,
|
||||||
|
_subscriptionId: string,
|
||||||
|
planVersionId: string | null,
|
||||||
|
): { totalMinor: number; currency: string | null } {
|
||||||
|
const entryRow = this.#db
|
||||||
|
.select()
|
||||||
|
.from(ledgerEvents)
|
||||||
|
.where(eq(ledgerEvents.identity, occurrenceId))
|
||||||
|
.all()
|
||||||
|
.find((r) => r.type === "vehicle_entry");
|
||||||
|
if (!entryRow) return { totalMinor: 0, currency: null };
|
||||||
|
const owed = windowOwedBetween(this.#db, planVersionId, entryRow.occurredAt, new Date().toISOString());
|
||||||
|
return { totalMinor: owed?.amountMinor ?? 0, currency: owed?.currency ?? null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sum of signed `payment` events keyed to this occurrence (what the subscriber has
|
||||||
|
* already paid toward their window charge). Folds the append-only ledger. */
|
||||||
|
#windowPaidMinor(occurrenceId: string): number {
|
||||||
|
const rows = this.#db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, occurrenceId)).all();
|
||||||
|
let paid = 0;
|
||||||
|
for (const r of rows) {
|
||||||
|
if (r.type !== "payment") continue;
|
||||||
|
const pl = (r.payload ?? {}) as { amountMinor?: number };
|
||||||
|
if (typeof pl.amountMinor === "number") paid += pl.amountMinor;
|
||||||
|
}
|
||||||
|
return paid;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The OPEN occurrences of a subscription right now, **oldest first** (FIFO) — a
|
||||||
|
* fold over the signed ledger. An occurrence is a `vehicle_entry` (whose
|
||||||
|
* `payload.permitId` is this subscription) with no later `vehicle_exit` on the same
|
||||||
|
* `identity`. Used to (a) infer entry vs. exit for ANY credential of the
|
||||||
|
* subscription, (b) pick which occurrence a read closes, and (c) enforce
|
||||||
|
* `maxConcurrent`. The on-chain field is `permitId`, so we match against that.
|
||||||
|
*/
|
||||||
|
#openOccurrences(subscriptionId: string): { identity: string; index: number }[] {
|
||||||
|
const rows = this.#db.select().from(ledgerEvents).orderBy(ledgerEvents.index).all();
|
||||||
|
// Net entries−exits per occurrence identity, keeping the entry order (oldest first).
|
||||||
|
const net = new Map<string, number>();
|
||||||
|
const firstIndex = new Map<string, number>();
|
||||||
|
for (const r of rows) {
|
||||||
|
const id = r.identity;
|
||||||
|
if (!id) continue;
|
||||||
|
const pl = (r.payload ?? {}) as { permitId?: string };
|
||||||
|
if (r.type === "vehicle_entry") {
|
||||||
|
if (pl.permitId !== subscriptionId) continue;
|
||||||
|
net.set(id, (net.get(id) ?? 0) + 1);
|
||||||
|
if (!firstIndex.has(id)) firstIndex.set(id, r.index);
|
||||||
|
} else if (r.type === "vehicle_exit") {
|
||||||
|
if (!net.has(id)) continue; // not one of this subscription's occurrences
|
||||||
|
net.set(id, (net.get(id) ?? 0) - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const open: { identity: string; index: number }[] = [];
|
||||||
|
for (const [id, n] of net) if (n > 0) open.push({ identity: id, index: firstIndex.get(id) ?? 0 });
|
||||||
|
open.sort((a, b) => a.index - b.index); // oldest first → FIFO
|
||||||
|
return open;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sign a refused-subscription anomaly with a localizable reason code, fire the
|
||||||
|
* directional evidence camera, and return the rendered English reason for the
|
||||||
|
* caller's ReadOutcome. `dir` is the lane the refusal happened at (entry/exit) so
|
||||||
|
* the right camera captures the turned-away subscriber. `via` records which
|
||||||
|
* credential was presented. */
|
||||||
|
async #reject(
|
||||||
|
m: SubscriptionMatch,
|
||||||
|
dir: FlowDirection,
|
||||||
|
code: ReasonCode,
|
||||||
|
params?: Record<string, string | number>,
|
||||||
|
): Promise<string> {
|
||||||
|
const rp = reasonPayload(code, params);
|
||||||
|
await this.#log.append({
|
||||||
|
type: "anomaly",
|
||||||
|
identity: m.carKey,
|
||||||
|
// `permitId`/`permitRefused` are the on-chain field names (immutable).
|
||||||
|
payload: { ...rp, permitId: m.subscriptionId, permitRefused: true, via: m.via },
|
||||||
|
});
|
||||||
|
this.#fireSnapshot(dir, m.carKey);
|
||||||
|
this.#logger.warn(`subscription refused (${m.carKey}): ${rp.reason}`);
|
||||||
|
return rp.reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fire the directional camera(s) for a refused-subscription event; never awaited
|
||||||
|
* (evidence, not a gate). The accepted entry/exit paths snapshot inside #open. */
|
||||||
|
#fireSnapshot(dir: FlowDirection, identity: string): void {
|
||||||
|
void snapshotAsync({ db: this.#db, direction: dir, identity, logger: this.#logger, vision: this.#vision }).catch(
|
||||||
|
(err) => this.#logger.error(`subscription snapshot error: ${(err as Error).message}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async #open(resolved: ResolvedRelay, dir: FlowDirection, carKey: string, what: string): Promise<void> {
|
||||||
|
const access = this.#buildAccess(resolved.controller);
|
||||||
|
if (access) await access.pulseOpen(resolved.relay);
|
||||||
|
else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`);
|
||||||
|
|
||||||
|
// SNAPSHOT — fire the directional camera(s), never awaited (evidence, not a gate).
|
||||||
|
this.#fireSnapshot(dir, carKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
#closeCache(carKey: string): void {
|
||||||
|
try {
|
||||||
|
this.#db.update(sessions).set({ exitedAt: new Date().toISOString(), state: "closed" }).where(eq(sessions.id, carKey)).run();
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.error(`session-cache close failed for ${carKey}: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build a live access adapter from a resolved controller row, or null. */
|
||||||
|
#buildAccess(row: DeviceRow): AccessControlDevice | null {
|
||||||
|
const driver = registry.get(row.driverId);
|
||||||
|
if (!driver) return null;
|
||||||
|
try {
|
||||||
|
return driver.create(row.config as never) as AccessControlDevice;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { and, eq, lte, desc, subscriptionPlans, type Db } from "@parking/db";
|
||||||
|
import type { SubscriptionPlan } from "@parking/shared";
|
||||||
|
|
||||||
|
// Subscription-plan pricing. The PURE span math (periodsBetween / priceSubscriptionSpan
|
||||||
|
// / addMonths) lives in @parking/shared so it's unit-tested alongside the tariff fee
|
||||||
|
// function; here we add the DB-backed plan-version resolver. A plan is admin-composed,
|
||||||
|
// versioned config (like a tariff) — the operator SELLS from it and never types a
|
||||||
|
// price. See wiki/entities/subscription.md.
|
||||||
|
export { periodsBetween, priceSubscriptionSpan, addMonths } from "@parking/shared";
|
||||||
|
|
||||||
|
/** Resolve the plan VERSION in force for `planId` at `asOf`: the latest active row
|
||||||
|
* with effectiveFrom ≤ asOf (the tariff-resolve pattern). null when none applies. */
|
||||||
|
export function resolvePlanVersion(db: Db, planId: string, asOf: string): SubscriptionPlan | null {
|
||||||
|
const row = db
|
||||||
|
.select()
|
||||||
|
.from(subscriptionPlans)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(subscriptionPlans.planId, planId),
|
||||||
|
eq(subscriptionPlans.active, true),
|
||||||
|
lte(subscriptionPlans.effectiveFrom, asOf),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.orderBy(desc(subscriptionPlans.effectiveFrom))
|
||||||
|
.limit(1)
|
||||||
|
.get();
|
||||||
|
return row ? (row as SubscriptionPlan) : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import { desc, eq, siteConfig, subscriptionPlans, tariffVersions, tariffs, type Db } from "@parking/db";
|
||||||
|
import {
|
||||||
|
computeFee,
|
||||||
|
minutesOutsideWindow,
|
||||||
|
outOfWindowGap,
|
||||||
|
type PlanTimeframes,
|
||||||
|
type SubscriptionPlan,
|
||||||
|
type TariffStructure,
|
||||||
|
} from "@parking/shared";
|
||||||
|
|
||||||
|
// Subscription TIME-WINDOW → TARIFF BRIDGE. A plan may restrict WHEN a subscriber may be
|
||||||
|
// parked (e.g. weekday 20:00→08:00, weekend all-day). A scan OUTSIDE the window is NOT
|
||||||
|
// refused — the out-of-window minutes are charged at the normal TRANSIENT tariff:
|
||||||
|
// - early ENTRY: arrival → window-open is owed (deferred; collected at exit).
|
||||||
|
// - late EXIT: window-close → departure is owed (exit is GATED until paid).
|
||||||
|
// Only plans WITH timeframes trigger any charge; a 24/7 plan never does. The gap math is
|
||||||
|
// pure + tz-aware (outOfWindowGap in @parking/shared); pricing reuses computeFee (the same
|
||||||
|
// engine transient stays use). See wiki/entities/subscription.md ("tariff bridge").
|
||||||
|
|
||||||
|
const DEFAULT_TZ = "Europe/Tirane";
|
||||||
|
|
||||||
|
/** A computed out-of-window charge: the gap, what it costs, and the tariff version used
|
||||||
|
* (recorded so it reprices identically — like every transient payment). */
|
||||||
|
export interface WindowCharge {
|
||||||
|
readonly amountMinor: number;
|
||||||
|
readonly gapStart: string;
|
||||||
|
readonly gapEnd: string;
|
||||||
|
readonly minutes: number;
|
||||||
|
readonly currency: string;
|
||||||
|
readonly tariffVersionId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The plan VERSION that priced a subscription's sale (by planVersionId), or null. The
|
||||||
|
* timeframes are read from THIS version so a later plan edit can't retroactively change
|
||||||
|
* an existing subscriber's window rules. */
|
||||||
|
export function planVersionById(db: Db, planVersionId: string | null): SubscriptionPlan | null {
|
||||||
|
if (!planVersionId) return null;
|
||||||
|
const row = db.select().from(subscriptionPlans).where(eq(subscriptionPlans.id, planVersionId)).get();
|
||||||
|
return row ? (row as unknown as SubscriptionPlan) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The site IANA timezone (falls back to the project default). */
|
||||||
|
export function siteTz(db: Db): string {
|
||||||
|
const cfg = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||||
|
return cfg?.timezone && cfg.timezone.length > 0 ? cfg.timezone : DEFAULT_TZ;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The active site tariff version in force at `at` (latest effectiveFrom ≤ at), or null. */
|
||||||
|
function tariffVersionAt(db: Db, at: string) {
|
||||||
|
const tariff = db.select().from(tariffs).where(eq(tariffs.scope, "site")).get();
|
||||||
|
if (!tariff) return null;
|
||||||
|
const versions = db
|
||||||
|
.select()
|
||||||
|
.from(tariffVersions)
|
||||||
|
.where(eq(tariffVersions.tariffId, tariff.id))
|
||||||
|
.orderBy(desc(tariffVersions.effectiveFrom))
|
||||||
|
.all();
|
||||||
|
return versions.find((v) => v.effectiveFrom <= at) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute the out-of-window charge for a subscriber scan at `atISO`, or null when there
|
||||||
|
* is nothing to charge (no plan timeframes, in-window, weekend all-day, within grace, or
|
||||||
|
* no tariff configured). `edge` = "entry" (early) or "exit" (late). The gap is priced as
|
||||||
|
* a fresh transient stay of that duration (computeFee over [gapStart, gapEnd]).
|
||||||
|
*/
|
||||||
|
export function windowCharge(
|
||||||
|
db: Db,
|
||||||
|
planVersionId: string | null,
|
||||||
|
atISO: string,
|
||||||
|
edge: "entry" | "exit",
|
||||||
|
): WindowCharge | null {
|
||||||
|
const plan = planVersionById(db, planVersionId);
|
||||||
|
const timeframes = (plan?.timeframes ?? null) as PlanTimeframes | null;
|
||||||
|
if (!timeframes) return null; // 24/7 plan (or comp sub) — never a time charge.
|
||||||
|
|
||||||
|
const tz = timeframes.tz || siteTz(db);
|
||||||
|
const gap = outOfWindowGap(timeframes, tz, atISO, edge);
|
||||||
|
if (!gap) return null; // in-window / all-day / within grace.
|
||||||
|
|
||||||
|
const tv = tariffVersionAt(db, gap.start);
|
||||||
|
if (!tv) return null; // no tariff to price against — can't charge (don't trap).
|
||||||
|
const structure = tv.structure as unknown as TariffStructure;
|
||||||
|
const amountMinor = computeFee(gap.start, gap.end, structure);
|
||||||
|
if (amountMinor <= 0) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
amountMinor,
|
||||||
|
gapStart: gap.start,
|
||||||
|
gapEnd: gap.end,
|
||||||
|
minutes: gap.minutes,
|
||||||
|
currency: tv.currency,
|
||||||
|
tariffVersionId: tv.id,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The TOTAL out-of-window charge a subscriber owes for an OPEN occurrence, computed over
|
||||||
|
* the whole stay `[enteredAt, nowISO)` in ONE shot (not entry-gap + exit-gap, which
|
||||||
|
* double-counts and lets the exit gap reach back to a previous day's close). Sums the
|
||||||
|
* minutes parked outside the plan's allowed window and prices them as a single transient
|
||||||
|
* stay of that duration — so the tariff's increments + daily cap apply correctly. Returns
|
||||||
|
* null when the plan has no timeframes / nothing is owed / no tariff to price against.
|
||||||
|
*/
|
||||||
|
export function windowOwedBetween(
|
||||||
|
db: Db,
|
||||||
|
planVersionId: string | null,
|
||||||
|
enteredAtISO: string,
|
||||||
|
nowISO: string,
|
||||||
|
): { amountMinor: number; minutes: number; currency: string; tariffVersionId: string } | null {
|
||||||
|
const plan = planVersionById(db, planVersionId);
|
||||||
|
const timeframes = (plan?.timeframes ?? null) as PlanTimeframes | null;
|
||||||
|
if (!timeframes) return null;
|
||||||
|
|
||||||
|
const tz = timeframes.tz || siteTz(db);
|
||||||
|
const minutes = minutesOutsideWindow(timeframes, tz, enteredAtISO, nowISO);
|
||||||
|
if (minutes <= 0) return null;
|
||||||
|
|
||||||
|
// Price the out-of-window duration as a transient stay (entry→entry+minutes), against
|
||||||
|
// the tariff in force at entry — reproducible, and the daily cap applies.
|
||||||
|
const tv = tariffVersionAt(db, enteredAtISO);
|
||||||
|
if (!tv) return null;
|
||||||
|
const structure = tv.structure as unknown as TariffStructure;
|
||||||
|
const end = new Date(Date.parse(enteredAtISO) + minutes * 60_000).toISOString();
|
||||||
|
const amountMinor = computeFee(enteredAtISO, end, structure);
|
||||||
|
if (amountMinor <= 0) return null;
|
||||||
|
|
||||||
|
return { amountMinor, minutes, currency: tv.currency, tariffVersionId: tv.id };
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import type { FastifyBaseLogger } from "fastify";
|
||||||
|
|
||||||
|
// Node-side client for the host vision service (apps/vision — the ANPR microservice).
|
||||||
|
// Calls it over LOCALHOST HTTP with a camera snapshot and gets back a plate read. The
|
||||||
|
// Python service is a separate process/failure domain; this client is the adapter the
|
||||||
|
// rest of the server talks to, so the recognizer is swappable without business-logic
|
||||||
|
// changes. See wiki/entities/opencv-anpr-service.md, decisions/vision-service*.md.
|
||||||
|
//
|
||||||
|
// ADVISORY, NEVER SOLE AUTHORITY. Per the vision decision + the fitness assessment, a
|
||||||
|
// plate read is an *identity hint + evidence*, never the lone reason a paid/access
|
||||||
|
// barrier opens. This client enforces two things at the boundary so callers can't
|
||||||
|
// misuse it:
|
||||||
|
// 1. It is FAIL-SOFT — any error (service down, timeout, decode fail) resolves to
|
||||||
|
// `null`, never throws into the entry/exit path. A missing vision result must
|
||||||
|
// degrade to the ticket/manual path, never strand or wrongly admit a car
|
||||||
|
// (fail-state-safety).
|
||||||
|
// 2. It applies the CONFIDENCE FLOOR — a read below the threshold is returned with
|
||||||
|
// `lowConfidence: true` (mirroring the service's own flag) so the caller treats it
|
||||||
|
// as advisory-only and falls back.
|
||||||
|
//
|
||||||
|
// NOT yet wired into the read bus — that (snapshot-before-decision on an opt-in camera →
|
||||||
|
// emit DeviceReadEvent{kind:"plate"}) is a separate, deliberate step. This is the
|
||||||
|
// transport + contract adapter only.
|
||||||
|
|
||||||
|
/** Plate bounding box (pixels, top-left origin) — mirrors the service schema. */
|
||||||
|
export interface PlateBBox {
|
||||||
|
readonly x1: number;
|
||||||
|
readonly y1: number;
|
||||||
|
readonly x2: number;
|
||||||
|
readonly y2: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One plate read from the vision service. `confidence` is the MIN of the model's
|
||||||
|
* per-character confidences (a plate is only as trustworthy as its weakest char). */
|
||||||
|
export interface VisionPlate {
|
||||||
|
readonly text: string;
|
||||||
|
readonly confidence: number;
|
||||||
|
readonly bbox?: PlateBBox | null;
|
||||||
|
/** Predicted issuing region/country (advisory; the global model emits this). */
|
||||||
|
readonly region?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The raw /analyze response shape (the Python contract). `vehicle` is reserved for
|
||||||
|
* Job 2 (vehicle verification) — not yet produced. */
|
||||||
|
interface AnalyzeResponse {
|
||||||
|
readonly plate: VisionPlate | null;
|
||||||
|
readonly plates: VisionPlate[];
|
||||||
|
readonly vehicle: unknown | null;
|
||||||
|
readonly low_confidence: boolean;
|
||||||
|
readonly model_version: string;
|
||||||
|
readonly took_ms: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the rest of the server gets back from `analyze()`. Normalised + camelCased,
|
||||||
|
* with the advisory gate already applied. Never thrown — `null` on any failure. */
|
||||||
|
export interface VisionResult {
|
||||||
|
/** The best plate, or null if none read. */
|
||||||
|
readonly plate: VisionPlate | null;
|
||||||
|
/** All plates found in the frame (a frame may hold several vehicles). */
|
||||||
|
readonly plates: VisionPlate[];
|
||||||
|
/** True when the best plate is below the confidence floor — treat as advisory only
|
||||||
|
* and fall back to the ticket/manual path. */
|
||||||
|
readonly lowConfidence: boolean;
|
||||||
|
readonly modelVersion: string;
|
||||||
|
readonly tookMs: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VisionHealth {
|
||||||
|
readonly ok: boolean;
|
||||||
|
readonly recognizer: string;
|
||||||
|
readonly ready: boolean;
|
||||||
|
readonly modelVersion: string;
|
||||||
|
readonly detail?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VisionClientOptions {
|
||||||
|
/** Base URL of the vision service (localhost). */
|
||||||
|
readonly baseUrl?: string;
|
||||||
|
/** Per-request timeout (ms) — a slow vision call must never hang the lane. */
|
||||||
|
readonly timeoutMs?: number;
|
||||||
|
/** Confidence floor: a best-plate below this is flagged lowConfidence. Mirrors the
|
||||||
|
* service's own VISION_MIN_CONFIDENCE; kept here too so the gate holds even if the
|
||||||
|
* service is misconfigured. */
|
||||||
|
readonly minConfidence?: number;
|
||||||
|
/** Master switch — when false, `analyze()` short-circuits to null (no call). Lets the
|
||||||
|
* appliance run with no vision service configured. */
|
||||||
|
readonly enabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class VisionClient {
|
||||||
|
readonly #baseUrl: string;
|
||||||
|
readonly #timeoutMs: number;
|
||||||
|
readonly #minConfidence: number;
|
||||||
|
readonly #enabled: boolean;
|
||||||
|
readonly #logger: FastifyBaseLogger;
|
||||||
|
|
||||||
|
constructor(logger: FastifyBaseLogger, opts: VisionClientOptions = {}) {
|
||||||
|
this.#logger = logger;
|
||||||
|
this.#baseUrl = (opts.baseUrl ?? process.env.VISION_URL ?? "http://127.0.0.1:8089").replace(/\/$/, "");
|
||||||
|
this.#timeoutMs = opts.timeoutMs ?? Number(process.env.VISION_TIMEOUT_MS ?? 1500);
|
||||||
|
this.#minConfidence = opts.minConfidence ?? Number(process.env.VISION_MIN_CONFIDENCE ?? 0.5);
|
||||||
|
// Default OFF: vision is opt-in. Enable with VISION_ENABLED=1 (or pass enabled:true).
|
||||||
|
this.#enabled =
|
||||||
|
opts.enabled ?? ["1", "true", "yes"].includes((process.env.VISION_ENABLED ?? "").toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
get enabled(): boolean {
|
||||||
|
return this.#enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Analyse snapshot bytes → a plate read, or `null`. NEVER throws and NEVER blocks the
|
||||||
|
* caller's open path beyond `timeoutMs`: any failure (disabled, unreachable, timeout,
|
||||||
|
* non-2xx, bad body) logs and resolves to null, so the caller falls back to the
|
||||||
|
* ticket/manual path. The returned `lowConfidence` re-applies the floor on top of the
|
||||||
|
* service's own flag.
|
||||||
|
*/
|
||||||
|
async analyze(imageBytes: Buffer, contentType = "application/octet-stream"): Promise<VisionResult | null> {
|
||||||
|
if (!this.#enabled) return null;
|
||||||
|
try {
|
||||||
|
const body = await this.#post("/analyze", imageBytes, contentType);
|
||||||
|
if (!body) return null;
|
||||||
|
const res = body as AnalyzeResponse;
|
||||||
|
const best = res.plate ?? null;
|
||||||
|
const lowConfidence =
|
||||||
|
res.low_confidence || (best != null && best.confidence < this.#minConfidence);
|
||||||
|
return {
|
||||||
|
plate: best,
|
||||||
|
plates: Array.isArray(res.plates) ? res.plates : [],
|
||||||
|
lowConfidence,
|
||||||
|
modelVersion: res.model_version ?? "unknown",
|
||||||
|
tookMs: typeof res.took_ms === "number" ? res.took_ms : 0,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
this.#logger.warn(`vision analyze failed (fallback to ticket path): ${(err as Error).message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Liveness/readiness of the vision service. Returns ok:false (never throws) when
|
||||||
|
* disabled or unreachable, so the device-status footer can show it. */
|
||||||
|
async health(): Promise<VisionHealth> {
|
||||||
|
if (!this.#enabled) {
|
||||||
|
return { ok: false, recognizer: "disabled", ready: false, modelVersion: "-", detail: "vision disabled" };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(() => controller.abort(), this.#timeoutMs);
|
||||||
|
try {
|
||||||
|
const r = await fetch(`${this.#baseUrl}/health`, { signal: controller.signal });
|
||||||
|
if (!r.ok) return { ok: false, recognizer: "?", ready: false, modelVersion: "-", detail: `HTTP ${r.status}` };
|
||||||
|
const h = (await r.json()) as {
|
||||||
|
status?: string;
|
||||||
|
recognizer?: string;
|
||||||
|
ready?: boolean;
|
||||||
|
model_version?: string;
|
||||||
|
detail?: string | null;
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
ok: h.status === "ok",
|
||||||
|
recognizer: h.recognizer ?? "?",
|
||||||
|
ready: Boolean(h.ready),
|
||||||
|
modelVersion: h.model_version ?? "-",
|
||||||
|
detail: h.detail ?? null,
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
return { ok: false, recognizer: "?", ready: false, modelVersion: "-", detail: (err as Error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST raw bytes to a path, with timeout. Returns parsed JSON or throws (caught by
|
||||||
|
* the caller, which fails soft). */
|
||||||
|
async #post(path: string, bytes: Buffer, contentType: string): Promise<unknown> {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(() => controller.abort(), this.#timeoutMs);
|
||||||
|
try {
|
||||||
|
const r = await fetch(`${this.#baseUrl}${path}`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "content-type": contentType },
|
||||||
|
// Buffer is a valid BodyInit in Node's undici fetch.
|
||||||
|
body: bytes,
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
if (!r.ok) throw new Error(`vision ${path} → HTTP ${r.status}`);
|
||||||
|
return await r.json();
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# apps/vision — the ANPR microservice's own env (copy to apps/vision/.env).
|
||||||
|
# This is the PYTHON SERVICE's config only. The Node server has its OWN VISION_* vars
|
||||||
|
# (in apps/server/.env) — keep the two .env files SEPARATE (they share the VISION_
|
||||||
|
# prefix but are different processes). See wiki/entities/opencv-anpr-service.md "Configuration".
|
||||||
|
|
||||||
|
# Recognizer: "stub" (no models, recognizes nothing — boots anywhere, for dev/CI) or
|
||||||
|
# "fast_alpr" (the real MIT YOLOv9+CCT/ONNX stack — needs `uv sync --extra alpr`).
|
||||||
|
VISION_RECOGNIZER=fast_alpr
|
||||||
|
|
||||||
|
# Bind. On the appliance prefer 127.0.0.1 — the Node backend is the only caller, so the
|
||||||
|
# /analyze endpoint should NOT be reachable off-host. (0.0.0.0 only if you must.)
|
||||||
|
VISION_HOST=127.0.0.1
|
||||||
|
VISION_PORT=8089
|
||||||
|
|
||||||
|
# fast-alpr models (only used when recognizer=fast_alpr). The defaults won the Albanian
|
||||||
|
# benchmark; change the OCR to european-plates-mobile-vit-v2-model only to re-test.
|
||||||
|
VISION_DETECTOR_MODEL=yolo-v9-t-384-license-plate-end2end
|
||||||
|
VISION_OCR_MODEL=cct-xs-v2-global-model
|
||||||
|
|
||||||
|
# Confidence floor — a best plate below this is flagged low_confidence so the Node side
|
||||||
|
# treats it as advisory and falls back to the ticket path. Keep in sync with the server.
|
||||||
|
VISION_MIN_CONFIDENCE=0.5
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.venv/
|
||||||
|
.mypy_cache/
|
||||||
|
.pytest_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
|
||||||
|
# Model weights (fetched at deploy / first run, never committed — can be large + license-scoped)
|
||||||
|
models/
|
||||||
|
*.onnx
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
3.12
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# @parking/vision — host-side ANPR / vehicle-verification service
|
||||||
|
|
||||||
|
A **separate process** (Python + FastAPI) the Node backend calls over **localhost HTTP** with a
|
||||||
|
camera snapshot, returning a licence-plate read (and, later, vehicle-attribute verification — the
|
||||||
|
anti-plate-spoofing witness). Recognition is **advisory, never the sole authority** to open a
|
||||||
|
barrier: if this service is down or unsure, the host falls back to the ticket path.
|
||||||
|
|
||||||
|
Lives inside the Turborepo at `apps/vision/` but is **not a JS package** — Python deps are managed by
|
||||||
|
`uv`/`pyproject.toml`; the `package.json` is a thin shim so `turbo run lint/test` includes it. See
|
||||||
|
`wiki/decisions/vision-service-packaging.md` and `wiki/entities/opencv-anpr-service.md`.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# from apps/vision/ — install the light core (boots in stub mode, no model downloads)
|
||||||
|
uv sync
|
||||||
|
|
||||||
|
# dev server with reload (or: pnpm --filter @parking/vision dev)
|
||||||
|
uv run uvicorn vision_service.app:app --reload --port 8089
|
||||||
|
|
||||||
|
# checks
|
||||||
|
uv run ruff check .
|
||||||
|
uv run pytest -q
|
||||||
|
```
|
||||||
|
|
||||||
|
### Enable the real recognizer (fast-alpr)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv sync --extra alpr # installs fast-alpr + onnxruntime (downloads model weights)
|
||||||
|
VISION_RECOGNIZER=fast_alpr uv run uvicorn vision_service.app:app --port 8089
|
||||||
|
```
|
||||||
|
|
||||||
|
Model weights (~11 MB: a YOLOv9 detector + CCT OCR) download on first use and cache under
|
||||||
|
`~/.cache/open-image-models` + `~/.cache/fast-plate-ocr` — offline after that.
|
||||||
|
|
||||||
|
### Quick test against an image (CLI, no HTTP)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv run python -m vision_service.cli path/to/car.jpg # or: pnpm --filter @parking/vision recognize -- car.jpg
|
||||||
|
uv run python -m vision_service.cli car.jpg --ocr cct-s-v2-global-model # try another OCR model
|
||||||
|
```
|
||||||
|
|
||||||
|
Prints the parsed plate(s) + confidence + region as JSON. Confidence is the **min** of fast-alpr's
|
||||||
|
per-character confidences (a plate is only as trustworthy as its weakest character). Example output on
|
||||||
|
the fast-alpr test image: `5AU5341 (1.000) region "Czech Republic"` in ~40 ms on CPU.
|
||||||
|
|
||||||
|
`fast-alpr` is MIT (YOLOv9 detector + CCT OCR on ONNX Runtime). Swap `VISION_OCR_MODEL` to the 40+
|
||||||
|
country European model to benchmark Albanian plates. For GPU/NPU, install `onnxruntime-gpu` /
|
||||||
|
`-openvino` / `-directml` instead of `onnxruntime`.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- `GET /health` → `{ status, recognizer, ready, model_version, detail? }`
|
||||||
|
- `POST /analyze` (body = raw image bytes, `Content-Type: application/octet-stream`) →
|
||||||
|
`{ plate: {text, confidence, bbox}|null, plates[], vehicle: null, low_confidence, model_version, took_ms }`
|
||||||
|
|
||||||
|
The Node side POSTs `Snapshot.bytes` directly (no multipart). `vehicle` is scaffolded but not yet
|
||||||
|
populated — fast-alpr is plate-only; the vehicle stage (Job 2) is built later on the same runtime.
|
||||||
|
|
||||||
|
## Config (env, prefix `VISION_`) — see `.env.example`
|
||||||
|
|
||||||
|
This service's env only. The **Node server has its own `VISION_*`** (`apps/server/.env`:
|
||||||
|
`VISION_ENABLED`, `VISION_URL`, `VISION_POLL_MS`, …) — same prefix, **separate process, separate
|
||||||
|
`.env`**. Don't merge them.
|
||||||
|
|
||||||
|
| Var | Default | Meaning |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `VISION_RECOGNIZER` | `stub` | `stub` (no models) or `fast_alpr` (real) |
|
||||||
|
| `VISION_HOST` | `0.0.0.0` | bind address — prefer `127.0.0.1` on the appliance (Node is the only caller) |
|
||||||
|
| `VISION_PORT` | `8089` | listen port (must match the server's `VISION_URL`) |
|
||||||
|
| `VISION_DETECTOR_MODEL` | `yolo-v9-t-384-license-plate-end2end` | fast-alpr detector |
|
||||||
|
| `VISION_OCR_MODEL` | `cct-xs-v2-global-model` | fast-alpr OCR (won the AL benchmark) |
|
||||||
|
| `VISION_MIN_CONFIDENCE` | `0.5` | below this → `low_confidence=true` |
|
||||||
|
|
||||||
|
To use it from the booth: set `VISION_ENABLED=1` on the **server**, run this service, then tick
|
||||||
|
**ANPR** on a camera in the SetupWizard (the camera must also be bound to a barrier). The booth footer
|
||||||
|
shows a **Vision** chip when enabled. Full config guide: `wiki/entities/opencv-anpr-service.md`.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"name": "@parking/vision",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"//": "Thin shim so this Python service is a first-class node in the Turbo task graph (it is NOT a JS package — deps are managed by uv/pyproject.toml). Each script shells to Python tooling. See wiki/decisions/vision-service-packaging.md.",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "uv run uvicorn vision_service.app:app --reload --host 0.0.0.0 --port 8089",
|
||||||
|
"start": "uv run uvicorn vision_service.app:app --host 0.0.0.0 --port 8089",
|
||||||
|
"lint": "uv run ruff check .",
|
||||||
|
"format": "uv run ruff format .",
|
||||||
|
"typecheck": "uv run mypy vision_service",
|
||||||
|
"test": "uv run pytest -q",
|
||||||
|
"recognize": "uv run python -m vision_service.cli",
|
||||||
|
"build": "echo 'no build step (Python service; models fetched at deploy)'"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
[project]
|
||||||
|
name = "parking-vision"
|
||||||
|
version = "0.0.0"
|
||||||
|
description = "Host-side ANPR / vehicle-verification microservice for the parking system (separate process; localhost HTTP)."
|
||||||
|
requires-python = ">=3.10,<4.0"
|
||||||
|
# Core deps are LIGHT on purpose: the service boots, serves /health, and answers
|
||||||
|
# /analyze in stub mode with ONLY these. The heavy recognizer stack (fast-alpr +
|
||||||
|
# onnxruntime + model weights) is the optional `alpr` extra, so `uv sync` and the test
|
||||||
|
# suite work offline without downloading models. See
|
||||||
|
# wiki/decisions/vision-service-packaging.md + wiki/entities/opencv-anpr-service.md.
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.115",
|
||||||
|
"uvicorn[standard]>=0.32",
|
||||||
|
"pydantic>=2.9",
|
||||||
|
"pydantic-settings>=2.6",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
vision-recognize = "vision_service.cli:main"
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
# The real recognizer. Install with: uv sync --extra alpr
|
||||||
|
# fast-alpr is MIT (YOLOv9 detector + CCT OCR, both MIT) on ONNX Runtime — see the
|
||||||
|
# recognizer evaluation in wiki/entities/opencv-anpr-service.md. onnxruntime is the
|
||||||
|
# CPU backend; swap for onnxruntime-gpu / -openvino / -directml on capable hardware.
|
||||||
|
alpr = [
|
||||||
|
"fast-alpr>=0.4.0",
|
||||||
|
"onnxruntime>=1.19",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dependency-groups]
|
||||||
|
# Dev tooling (uv installs these by default for local work; excluded from the runtime image).
|
||||||
|
dev = [
|
||||||
|
"ruff>=0.8",
|
||||||
|
"pytest>=8.3",
|
||||||
|
"httpx>=0.27", # FastAPI TestClient transport
|
||||||
|
"mypy>=1.13",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
line-length = 110
|
||||||
|
target-version = "py310"
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
# A pragmatic default set: pyflakes, pycodestyle, isort, bugbear, pyupgrade.
|
||||||
|
select = ["E", "F", "I", "B", "UP"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
|
||||||
|
[tool.mypy]
|
||||||
|
python_version = "3.10"
|
||||||
|
strict = true
|
||||||
|
# fast-alpr / onnxruntime ship without type stubs; don't fail typecheck on the optional stack.
|
||||||
|
ignore_missing_imports = true
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["hatchling"]
|
||||||
|
build-backend = "hatchling.build"
|
||||||
|
|
||||||
|
[tool.hatch.build.targets.wheel]
|
||||||
|
packages = ["vision_service"]
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Smoke tests for the vision service in STUB mode (no model weights needed)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from vision_service.app import app
|
||||||
|
|
||||||
|
|
||||||
|
def make_client() -> TestClient:
|
||||||
|
# TestClient runs the lifespan, building the (stub) recognizer.
|
||||||
|
return TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_health_ok_in_stub_mode() -> None:
|
||||||
|
with make_client() as client:
|
||||||
|
res = client.get("/health")
|
||||||
|
assert res.status_code == 200
|
||||||
|
body = res.json()
|
||||||
|
assert body["status"] == "ok"
|
||||||
|
assert body["ready"] is True
|
||||||
|
assert body["recognizer"] == "stub"
|
||||||
|
assert body["model_version"] == "stub-0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_analyze_returns_contract_shape() -> None:
|
||||||
|
with make_client() as client:
|
||||||
|
# The stub recognizes nothing, but the response must match the contract.
|
||||||
|
res = client.post(
|
||||||
|
"/analyze",
|
||||||
|
content=b"\xff\xd8\xff\xe0not-a-real-jpeg",
|
||||||
|
headers={"content-type": "application/octet-stream"},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
body = res.json()
|
||||||
|
assert body["plate"] is None
|
||||||
|
assert body["plates"] == []
|
||||||
|
assert body["vehicle"] is None
|
||||||
|
assert body["low_confidence"] is False
|
||||||
|
assert body["model_version"] == "stub-0"
|
||||||
|
assert "took_ms" in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_analyze_rejects_empty_body() -> None:
|
||||||
|
with make_client() as client:
|
||||||
|
res = client.post(
|
||||||
|
"/analyze",
|
||||||
|
content=b"",
|
||||||
|
headers={"content-type": "application/octet-stream"},
|
||||||
|
)
|
||||||
|
assert res.status_code == 400
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""Unit tests for fast-alpr result parsing — no model weights required (the objects
|
||||||
|
are duck-typed stand-ins shaped like fast-alpr's ALPRResult)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from vision_service.recognizer import _reduce_confidence, plate_from_alpr_result
|
||||||
|
|
||||||
|
|
||||||
|
def test_reduce_confidence_takes_min_of_list() -> None:
|
||||||
|
# The weakest character governs trust in the whole plate.
|
||||||
|
assert _reduce_confidence([0.99, 0.80, 0.95]) == 0.80
|
||||||
|
|
||||||
|
|
||||||
|
def test_reduce_confidence_handles_scalar_and_junk() -> None:
|
||||||
|
assert _reduce_confidence(0.7) == 0.7
|
||||||
|
assert _reduce_confidence(None) == 0.0
|
||||||
|
assert _reduce_confidence([]) == 0.0
|
||||||
|
assert _reduce_confidence("nope") == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_result(text: str, conf: list[float], region: str | None = None) -> SimpleNamespace:
|
||||||
|
box = SimpleNamespace(x1=10, y1=20, x2=110, y2=60)
|
||||||
|
return SimpleNamespace(
|
||||||
|
ocr=SimpleNamespace(text=text, confidence=conf, region=region),
|
||||||
|
detection=SimpleNamespace(bounding_box=box),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_plate_from_result_maps_fields() -> None:
|
||||||
|
plate = plate_from_alpr_result(_fake_result("5AU5341", [0.999, 0.9995, 0.97], "Czech Republic"))
|
||||||
|
assert plate is not None
|
||||||
|
assert plate.text == "5AU5341"
|
||||||
|
assert plate.confidence == 0.97 # min of the per-character list
|
||||||
|
assert plate.region == "Czech Republic"
|
||||||
|
assert plate.bbox is not None
|
||||||
|
assert (plate.bbox.x1, plate.bbox.y1, plate.bbox.x2, plate.bbox.y2) == (10, 20, 110, 60)
|
||||||
|
|
||||||
|
|
||||||
|
def test_plate_from_result_skips_empty_text() -> None:
|
||||||
|
assert plate_from_alpr_result(_fake_result("", [0.9])) is None
|
||||||
|
assert plate_from_alpr_result(SimpleNamespace(ocr=None, detection=None)) is None
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://turbo.build/schema.json",
|
||||||
|
"extends": ["//"],
|
||||||
|
"tasks": {
|
||||||
|
"build": {
|
||||||
|
"outputs": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
"""Host-side ANPR / vehicle-verification microservice.
|
||||||
|
|
||||||
|
A separate process (FastAPI over localhost HTTP) that the Node backend calls with a
|
||||||
|
camera snapshot and gets back a plate read (Job 1) — and, later, vehicle-attribute
|
||||||
|
verification (Job 2, the anti-spoofing witness). Recognition is ADVISORY, never the
|
||||||
|
sole authority to open a barrier. See wiki/entities/opencv-anpr-service.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__version__ = "0.0.0"
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""FastAPI app: POST /analyze (snapshot → plate) + GET /health.
|
||||||
|
|
||||||
|
Called by the Node backend over localhost HTTP (the camera driver already holds the
|
||||||
|
JPEG bytes — Snapshot.bytes). This service is a SEPARATE PROCESS with its own failure
|
||||||
|
domain: if it's down or unsure, the host falls back to the ticket path — recognition is
|
||||||
|
advisory, never the sole authority. See wiki/entities/opencv-anpr-service.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI, HTTPException, Request
|
||||||
|
|
||||||
|
from .recognizer import Recognizer, build_recognizer
|
||||||
|
from .schemas import AnalyzeResponse, HealthResponse
|
||||||
|
from .settings import Settings, get_settings
|
||||||
|
|
||||||
|
# Cap an upload so a malformed/huge POST can't exhaust memory (a camera JPEG is well
|
||||||
|
# under this). 413 beyond it.
|
||||||
|
MAX_IMAGE_BYTES = 12 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||||
|
settings = get_settings()
|
||||||
|
app.state.settings = settings
|
||||||
|
# Build the recognizer once at startup (models load here, not per-request).
|
||||||
|
app.state.recognizer = build_recognizer(settings)
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(title="parking-vision", version="0.0.0", lifespan=lifespan)
|
||||||
|
|
||||||
|
|
||||||
|
# Typed accessors over the untyped `app.state` (so mypy --strict sees the real types).
|
||||||
|
def _recognizer(request: Request) -> Recognizer:
|
||||||
|
rec: Recognizer = request.app.state.recognizer
|
||||||
|
return rec
|
||||||
|
|
||||||
|
|
||||||
|
def _settings(request: Request) -> Settings:
|
||||||
|
settings: Settings = request.app.state.settings
|
||||||
|
return settings
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health", response_model=HealthResponse)
|
||||||
|
async def health(request: Request) -> HealthResponse:
|
||||||
|
rec = _recognizer(request)
|
||||||
|
settings = _settings(request)
|
||||||
|
ready = bool(rec.ready)
|
||||||
|
return HealthResponse(
|
||||||
|
status="ok" if ready else "degraded",
|
||||||
|
recognizer=settings.recognizer,
|
||||||
|
ready=ready,
|
||||||
|
model_version=rec.model_version,
|
||||||
|
detail=getattr(rec, "error", None),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/analyze", response_model=AnalyzeResponse)
|
||||||
|
async def analyze(request: Request) -> AnalyzeResponse:
|
||||||
|
"""Analyze raw image bytes (the camera JPEG). Body is the octet-stream itself, so
|
||||||
|
the Node side POSTs Snapshot.bytes directly with Content-Type:
|
||||||
|
application/octet-stream — no multipart wrapping. We read the raw body ourselves
|
||||||
|
(rather than a required Body param) so an empty/oversize body returns our own clean
|
||||||
|
400/413 instead of FastAPI's generic 422."""
|
||||||
|
image = await request.body()
|
||||||
|
if not image:
|
||||||
|
raise HTTPException(status_code=400, detail="empty image body")
|
||||||
|
if len(image) > MAX_IMAGE_BYTES:
|
||||||
|
raise HTTPException(status_code=413, detail="image too large")
|
||||||
|
|
||||||
|
rec = _recognizer(request)
|
||||||
|
if not rec.ready:
|
||||||
|
# The real recognizer failed to load — be explicit so Node falls back rather
|
||||||
|
# than treating a silent empty result as "no plate present".
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=503,
|
||||||
|
detail=f"recognizer not ready: {getattr(rec, 'error', 'unavailable')}",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return rec.analyze(image)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||||
|
except Exception as exc: # noqa: BLE001 - never leak a stack to the caller
|
||||||
|
raise HTTPException(status_code=500, detail=f"analysis failed: {exc}") from exc
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""Dev CLI to test a recognizer against an image file — no HTTP, fast feedback.
|
||||||
|
|
||||||
|
uv run python -m vision_service.cli path/to/car.jpg
|
||||||
|
uv run python -m vision_service.cli car.jpg --recognizer stub # contract only
|
||||||
|
uv run python -m vision_service.cli car.jpg --ocr cct-s-v2-global-model
|
||||||
|
|
||||||
|
Defaults to the `fast_alpr` recognizer (the point of this tool). Prints the parsed
|
||||||
|
plate result as JSON. If the `alpr` extra isn't installed it says so and exits non-zero
|
||||||
|
rather than silently using the stub. See wiki/entities/opencv-anpr-service.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .recognizer import build_recognizer
|
||||||
|
from .settings import Settings
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
parser = argparse.ArgumentParser(prog="vision-recognize", description="Run a recognizer on an image.")
|
||||||
|
parser.add_argument("image", type=Path, help="path to an image file (JPEG/PNG) with a plate")
|
||||||
|
parser.add_argument(
|
||||||
|
"--recognizer",
|
||||||
|
choices=["fast_alpr", "stub"],
|
||||||
|
default="fast_alpr",
|
||||||
|
help="which recognizer to use (default: fast_alpr)",
|
||||||
|
)
|
||||||
|
parser.add_argument("--detector", default=None, help="override the fast-alpr detector model name")
|
||||||
|
parser.add_argument("--ocr", default=None, help="override the fast-alpr OCR model name")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
if not args.image.is_file():
|
||||||
|
print(f"error: no such file: {args.image}", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
|
||||||
|
settings = Settings(recognizer=args.recognizer)
|
||||||
|
if args.detector:
|
||||||
|
settings.detector_model = args.detector
|
||||||
|
if args.ocr:
|
||||||
|
settings.ocr_model = args.ocr
|
||||||
|
|
||||||
|
rec = build_recognizer(settings)
|
||||||
|
if not rec.ready:
|
||||||
|
err = getattr(rec, "error", "unavailable")
|
||||||
|
print(
|
||||||
|
f"error: recognizer '{args.recognizer}' not ready: {err}\n"
|
||||||
|
"hint: install the models with uv sync --extra alpr",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
image_bytes = args.image.read_bytes()
|
||||||
|
result = rec.analyze(image_bytes)
|
||||||
|
# Pydantic v2: model_dump_json gives a clean, stable rendering.
|
||||||
|
print(result.model_dump_json(indent=2))
|
||||||
|
|
||||||
|
if result.plate is None:
|
||||||
|
print("\n(no plate detected)", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
flag = " [LOW CONFIDENCE]" if result.low_confidence else ""
|
||||||
|
print(
|
||||||
|
f"\n→ {result.plate.text} ({result.plate.confidence:.3f}){flag} in {result.took_ms:.1f} ms",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
"""The recognizer port + implementations.
|
||||||
|
|
||||||
|
The service depends on the `Recognizer` PROTOCOL, never a concrete model library — the
|
||||||
|
same swappable-behind-an-interface principle as the Node device adapters
|
||||||
|
(wiki/concepts/device-adapter-pattern.md). Two impls today:
|
||||||
|
|
||||||
|
- StubRecognizer: no model weights, deterministic placeholder. Lets the service boot
|
||||||
|
and the tests run offline with nothing downloaded (dev/CI default).
|
||||||
|
- FastAlprRecognizer: the real MIT YOLOv9-detector + CCT-OCR stack on ONNX Runtime
|
||||||
|
(the `alpr` extra). See wiki/entities/opencv-anpr-service.md "Recognizer evaluation".
|
||||||
|
|
||||||
|
Adding a recognizer (e.g. a fine-tuned YOLO + PaddleOCR) = a new class here, no app change.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
from .schemas import AnalyzeResponse, BBox, PlateResult
|
||||||
|
from .settings import Settings
|
||||||
|
|
||||||
|
|
||||||
|
class Recognizer(Protocol):
|
||||||
|
"""Reads plates from a JPEG/PNG image. Implementations must be process-local and offline."""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def model_version(self) -> str: ...
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ready(self) -> bool: ...
|
||||||
|
|
||||||
|
def analyze(self, image_bytes: bytes) -> AnalyzeResponse: ...
|
||||||
|
|
||||||
|
|
||||||
|
def _reduce_confidence(raw: object) -> float:
|
||||||
|
"""fast-alpr's OCR confidence is a LIST of per-character confidences. Reduce to one
|
||||||
|
plate confidence via the MIN — a plate is only as trustworthy as its weakest
|
||||||
|
character (one misread digit changes the identity). Tolerates a scalar (future
|
||||||
|
models) or junk (→ 0.0). Pure + model-free so it's unit-testable without weights."""
|
||||||
|
if isinstance(raw, (list, tuple)) and raw:
|
||||||
|
try:
|
||||||
|
return float(min(raw))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0.0
|
||||||
|
if isinstance(raw, (int, float)):
|
||||||
|
return float(raw)
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def plate_from_alpr_result(r: object) -> PlateResult | None:
|
||||||
|
"""Map ONE fast-alpr ALPRResult to our PlateResult, or None if it carries no text.
|
||||||
|
Uses getattr throughout so it's decoupled from the exact fast-alpr classes (and
|
||||||
|
testable with a duck-typed stand-in). See wiki/entities/opencv-anpr-service.md."""
|
||||||
|
ocr = getattr(r, "ocr", None)
|
||||||
|
det = getattr(r, "detection", None)
|
||||||
|
text = getattr(ocr, "text", None)
|
||||||
|
if ocr is None or not text:
|
||||||
|
return None
|
||||||
|
bbox = None
|
||||||
|
box = getattr(det, "bounding_box", None)
|
||||||
|
if box is not None:
|
||||||
|
bbox = BBox(x1=int(box.x1), y1=int(box.y1), x2=int(box.x2), y2=int(box.y2))
|
||||||
|
return PlateResult(
|
||||||
|
text=text,
|
||||||
|
confidence=_reduce_confidence(getattr(ocr, "confidence", None)),
|
||||||
|
bbox=bbox,
|
||||||
|
region=getattr(ocr, "region", None),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class StubRecognizer:
|
||||||
|
"""A no-model placeholder. Returns an empty (no-plate) result quickly so the whole
|
||||||
|
HTTP path — Node adapter, contract, error handling — can be exercised without the
|
||||||
|
heavy recognizer stack or any model download."""
|
||||||
|
|
||||||
|
model_version = "stub-0"
|
||||||
|
ready = True
|
||||||
|
|
||||||
|
def __init__(self, settings: Settings) -> None:
|
||||||
|
self._settings = settings
|
||||||
|
|
||||||
|
def analyze(self, image_bytes: bytes) -> AnalyzeResponse:
|
||||||
|
started = time.perf_counter()
|
||||||
|
# Deliberately recognizes nothing — it is a stub, not a fake "always finds a plate"
|
||||||
|
# (which would be dangerous: recognition must never invent an identity).
|
||||||
|
took_ms = (time.perf_counter() - started) * 1000.0
|
||||||
|
return AnalyzeResponse(
|
||||||
|
plate=None,
|
||||||
|
plates=[],
|
||||||
|
vehicle=None,
|
||||||
|
low_confidence=False,
|
||||||
|
model_version=self.model_version,
|
||||||
|
took_ms=took_ms,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FastAlprRecognizer:
|
||||||
|
"""The real recognizer: fast-alpr (YOLOv9 plate detector + CCT OCR, ONNX Runtime).
|
||||||
|
|
||||||
|
Imported lazily so the service still imports/boots in stub mode when the `alpr`
|
||||||
|
extra (and its model weights) are not installed — a missing recognizer must not
|
||||||
|
crash the process; it degrades to a clear `ready=False`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, settings: Settings) -> None:
|
||||||
|
self._settings = settings
|
||||||
|
self._alpr = None
|
||||||
|
self._error: str | None = None
|
||||||
|
try:
|
||||||
|
from fast_alpr import ALPR
|
||||||
|
|
||||||
|
self._alpr = ALPR(
|
||||||
|
detector_model=settings.detector_model,
|
||||||
|
ocr_model=settings.ocr_model,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001 - any failure ⇒ not-ready, surfaced via /health
|
||||||
|
self._error = f"{type(exc).__name__}: {exc}"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def model_version(self) -> str:
|
||||||
|
return f"fast-alpr:{self._settings.detector_model}+{self._settings.ocr_model}"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ready(self) -> bool:
|
||||||
|
return self._alpr is not None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def error(self) -> str | None:
|
||||||
|
return self._error
|
||||||
|
|
||||||
|
def analyze(self, image_bytes: bytes) -> AnalyzeResponse:
|
||||||
|
if self._alpr is None:
|
||||||
|
raise RuntimeError(f"fast-alpr not available: {self._error}")
|
||||||
|
|
||||||
|
# fast-alpr's predict() takes a BGR ndarray; decode the JPEG with cv2 (pulled in
|
||||||
|
# transitively by the alpr extra). Import locally so stub mode needs neither.
|
||||||
|
import cv2
|
||||||
|
import numpy as np # local import: only needed on the real path
|
||||||
|
|
||||||
|
started = time.perf_counter()
|
||||||
|
buf = np.frombuffer(image_bytes, dtype=np.uint8)
|
||||||
|
frame = cv2.imdecode(buf, cv2.IMREAD_COLOR)
|
||||||
|
if frame is None:
|
||||||
|
raise ValueError("could not decode image bytes")
|
||||||
|
|
||||||
|
results = self._alpr.predict(frame)
|
||||||
|
plates: list[PlateResult] = []
|
||||||
|
for r in results:
|
||||||
|
plate = plate_from_alpr_result(r)
|
||||||
|
if plate is not None:
|
||||||
|
plates.append(plate)
|
||||||
|
|
||||||
|
plates.sort(key=lambda p: p.confidence, reverse=True)
|
||||||
|
best = plates[0] if plates else None
|
||||||
|
low = best is not None and best.confidence < self._settings.min_confidence
|
||||||
|
took_ms = (time.perf_counter() - started) * 1000.0
|
||||||
|
return AnalyzeResponse(
|
||||||
|
plate=best,
|
||||||
|
plates=plates,
|
||||||
|
vehicle=None, # Job 2 not built yet
|
||||||
|
low_confidence=low,
|
||||||
|
model_version=self.model_version,
|
||||||
|
took_ms=took_ms,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_recognizer(settings: Settings) -> Recognizer:
|
||||||
|
"""Factory: pick the recognizer from settings. Falls back to the stub if the real
|
||||||
|
one can't load, so the service always comes up (with ready=False surfaced)."""
|
||||||
|
if settings.recognizer == "fast_alpr":
|
||||||
|
rec = FastAlprRecognizer(settings)
|
||||||
|
return rec
|
||||||
|
return StubRecognizer(settings)
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""The /analyze response contract — the shape the Node VisionClient adapter consumes.
|
||||||
|
|
||||||
|
Mirrors the first-cut API in wiki/entities/opencv-anpr-service.md:
|
||||||
|
{ plate: {text, confidence, bbox}|null, vehicle: {...}|null, modelVersion, tookMs }
|
||||||
|
Job 2 (vehicle attributes) is scaffolded as an optional field, not yet populated —
|
||||||
|
fast-alpr is plate-only; the vehicle stage is built later on the same ONNX runtime.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class BBox(BaseModel):
|
||||||
|
"""Plate bounding box in pixels (top-left origin)."""
|
||||||
|
|
||||||
|
x1: int
|
||||||
|
y1: int
|
||||||
|
x2: int
|
||||||
|
y2: int
|
||||||
|
|
||||||
|
|
||||||
|
class PlateResult(BaseModel):
|
||||||
|
text: str
|
||||||
|
# The plate's confidence = the MIN of fast-alpr's per-character confidences (a plate
|
||||||
|
# is only as trustworthy as its weakest character). See recognizer.py.
|
||||||
|
confidence: float = Field(ge=0.0, le=1.0)
|
||||||
|
bbox: BBox | None = None
|
||||||
|
# Predicted issuing region/country (advisory; fast-alpr's global model emits this).
|
||||||
|
region: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class VehicleResult(BaseModel):
|
||||||
|
"""Job 2 — vehicle attributes / fingerprint (anti-spoofing). Not yet produced."""
|
||||||
|
|
||||||
|
colour: str | None = None
|
||||||
|
body_type: str | None = None
|
||||||
|
make: str | None = None
|
||||||
|
model: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class AnalyzeResponse(BaseModel):
|
||||||
|
# The single best plate, or null when none was found.
|
||||||
|
plate: PlateResult | None = None
|
||||||
|
# All plates found (a frame may contain several vehicles).
|
||||||
|
plates: list[PlateResult] = Field(default_factory=list)
|
||||||
|
vehicle: VehicleResult | None = None
|
||||||
|
# True when the best plate is below the confidence floor — Node should treat the
|
||||||
|
# read as advisory only and prefer the ticket path. See fail-state-safety.
|
||||||
|
low_confidence: bool = False
|
||||||
|
model_version: str
|
||||||
|
took_ms: float
|
||||||
|
|
||||||
|
|
||||||
|
class HealthResponse(BaseModel):
|
||||||
|
status: str
|
||||||
|
recognizer: str
|
||||||
|
ready: bool
|
||||||
|
model_version: str
|
||||||
|
detail: str | None = None
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Runtime configuration, from environment (prefix VISION_).
|
||||||
|
|
||||||
|
Offline-first: every default is local and works with no network. The recognizer is
|
||||||
|
chosen by `recognizer` — "stub" (no models, deterministic placeholder) or "fast_alpr"
|
||||||
|
(the real MIT YOLOv9+CCT/ONNX stack, installed via the `alpr` extra).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
model_config = SettingsConfigDict(env_prefix="VISION_", env_file=".env", extra="ignore")
|
||||||
|
|
||||||
|
host: str = "0.0.0.0"
|
||||||
|
port: int = 8089
|
||||||
|
|
||||||
|
# Which recognizer to load. "stub" needs no model weights (boots anywhere, for
|
||||||
|
# dev/CI); "fast_alpr" loads the real models (requires the `alpr` extra installed).
|
||||||
|
recognizer: Literal["stub", "fast_alpr"] = "stub"
|
||||||
|
|
||||||
|
# fast-alpr model names (only used when recognizer="fast_alpr"). Defaults match the
|
||||||
|
# library defaults; swap the OCR for the 40+country EU model to benchmark Albanian
|
||||||
|
# plates. See wiki/entities/opencv-anpr-service.md "Recognizer evaluation".
|
||||||
|
detector_model: str = "yolo-v9-t-384-license-plate-end2end"
|
||||||
|
ocr_model: str = "cct-xs-v2-global-model"
|
||||||
|
|
||||||
|
# Below this OCR confidence the read is returned but flagged low_confidence, so the
|
||||||
|
# Node side can fall back to the ticket path rather than trust it.
|
||||||
|
min_confidence: float = 0.5
|
||||||
|
|
||||||
|
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return Settings()
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Production build env for the SPA (auto-loaded by `vite build`, which the Tauri
|
||||||
|
# desktop bundle runs via beforeBuildCommand). NOT loaded by `vite` dev.
|
||||||
|
#
|
||||||
|
# The desktop shell serves the bundled SPA from tauri://localhost (no proxy, not
|
||||||
|
# same-origin), so the SPA must reach Fastify by absolute origin. This is the
|
||||||
|
# appliance's local Fastify address. Not a secret — committed for reproducible
|
||||||
|
# desktop builds. Override per-deployment if Fastify binds elsewhere.
|
||||||
|
#
|
||||||
|
# NOTE: a plain browser prod build (Fastify serving dist/ same-origin) does NOT
|
||||||
|
# want this set. If you build the SPA for that, override VITE_API_BASE="" .
|
||||||
|
VITE_API_BASE=http://127.0.0.1:3000
|
||||||
@@ -12,13 +12,26 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@parking/shared": "workspace:*",
|
"@parking/shared": "workspace:*",
|
||||||
|
"@radix-ui/react-dialog": "^1.1.17",
|
||||||
|
"@radix-ui/react-dropdown-menu": "^2.1.18",
|
||||||
|
"@radix-ui/react-tabs": "^1.1.15",
|
||||||
|
"@tanstack/react-query": "^5.101.0",
|
||||||
|
"@tanstack/react-router": "^1.170.16",
|
||||||
|
"@tauri-apps/plugin-process": "^2.3.1",
|
||||||
|
"@tauri-apps/plugin-updater": "^2.10.1",
|
||||||
|
"i18next": "^26.3.1",
|
||||||
"react": "19.2.7",
|
"react": "19.2.7",
|
||||||
"react-dom": "19.2.7"
|
"react-dom": "19.2.7",
|
||||||
|
"react-i18next": "^17.0.8",
|
||||||
|
"zustand": "^5.0.14"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@tailwindcss/vite": "^4.3.1",
|
||||||
|
"@tanstack/react-router-devtools": "^1.167.0",
|
||||||
"@types/react": "19.2.17",
|
"@types/react": "19.2.17",
|
||||||
"@types/react-dom": "19.2.3",
|
"@types/react-dom": "19.2.3",
|
||||||
"@vitejs/plugin-react": "6.0.2",
|
"@vitejs/plugin-react": "6.0.2",
|
||||||
|
"tailwindcss": "^4.3.1",
|
||||||
"typescript": "6.0.3",
|
"typescript": "6.0.3",
|
||||||
"vite": "8.0.16"
|
"vite": "8.0.16"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { fetchActiveSessions, reopenBarrier, type ActiveSession } from "./api.js";
|
||||||
|
import { qk } from "./lib/query.js";
|
||||||
|
import { useShift } from "./lib/use-shift.js";
|
||||||
|
import { formatDuration, formatRelativeDateTime } from "./lib/format.js";
|
||||||
|
import { Panel } from "./ui/Panel.js";
|
||||||
|
import { FilterBar, SegGroup, type SegOption } from "./ui/FilterBar.js";
|
||||||
|
|
||||||
|
// Active Sessions panel. A session is "active" while still inside OR exited-but-
|
||||||
|
// within-grace (the barrier is UNCONFIRMED, so a paid/exited car is presumed
|
||||||
|
// possibly-present until grace runs out). Lets the operator find a stuck car —
|
||||||
|
// damaged ticket, dead scanner, or a phantom barrier re-close — without a scan:
|
||||||
|
// - click a row → the pay/exit modal (pay an unpaid car, or review),
|
||||||
|
// - "Open barrier" (PAID sessions only) → an audited human-intervention re-pulse.
|
||||||
|
// No payment → no Open barrier button (the no-unpaid-bypass rule).
|
||||||
|
//
|
||||||
|
// OVERSTAY sessions (paid, grace expired, no signed exit) are no longer aged out — they
|
||||||
|
// stay listed with a distinct badge. A new period has begun (the car re-parked or is
|
||||||
|
// faulty/abandoned); occupancy lingers and the car owes a fresh top-up. The operator
|
||||||
|
// reconciles via the pay/exit modal — never a free barrier open.
|
||||||
|
// See wiki/concepts/booth-exit-flow.md.
|
||||||
|
|
||||||
|
type StatusFilter = "unpaid" | "paid" | "exiting" | "overstay";
|
||||||
|
type KindFilter = "transient" | "subscription";
|
||||||
|
|
||||||
|
function statusOf(s: ActiveSession): StatusFilter | "subscription" {
|
||||||
|
if (s.subscription) return "subscription";
|
||||||
|
if (s.overstay) return "overstay";
|
||||||
|
if (!s.open && s.withinGrace) return "exiting";
|
||||||
|
if (s.paidAt) return "paid";
|
||||||
|
return "unpaid";
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusBadge(s: ActiveSession): { key: string; titleKey?: string; cls: string } {
|
||||||
|
if (s.subscription) return { key: "booth.badgeSubscription", cls: "text-term-cyan" };
|
||||||
|
if (s.overstay)
|
||||||
|
return { key: "booth.badgeOverstay", titleKey: "booth.badgeOverstayTitle", cls: "text-term-red" };
|
||||||
|
if (!s.open && s.withinGrace) return { key: "booth.badgeExiting", cls: "text-term-cyan" };
|
||||||
|
if (s.paidAt) return { key: "booth.badgePaid", cls: "text-term-green" };
|
||||||
|
return { key: "booth.badgeUnpaid", cls: "text-term-amber" };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ActiveSessions({ onPick }: { onPick: (identity: string) => void }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const qc = useQueryClient();
|
||||||
|
// The audited barrier re-open is a money-path action (server-gated on an open
|
||||||
|
// shift); disable it unless this operator's shift is open.
|
||||||
|
const { isOpen: shiftOpen, isMine: shiftMine } = useShift();
|
||||||
|
const shiftReady = shiftOpen && shiftMine;
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey: qk.activeSessions,
|
||||||
|
queryFn: fetchActiveSessions,
|
||||||
|
// Belt-and-braces refresh in case a grace window expires with no ledger event
|
||||||
|
// to invalidate the cache (the WS only pushes on appends).
|
||||||
|
refetchInterval: 15_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const reopen = useMutation({
|
||||||
|
mutationFn: (identity: string) => reopenBarrier(identity),
|
||||||
|
onSettled: () => {
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.activeSessions });
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.events });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const [reopenMsg, setReopenMsg] = useState<{ id: string; text: string; ok: boolean } | null>(null);
|
||||||
|
|
||||||
|
// Filters: free-text search, status, and transient-vs-subscriber.
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [status, setStatus] = useState<StatusFilter | "">("");
|
||||||
|
const [kind, setKind] = useState<KindFilter | "">("");
|
||||||
|
|
||||||
|
const sessions = useMemo(() => data?.sessions ?? [], [data]);
|
||||||
|
const filtered = useMemo(() => {
|
||||||
|
const q = search.trim().toLowerCase();
|
||||||
|
return sessions.filter((s) => {
|
||||||
|
if (kind === "transient" && s.subscription) return false;
|
||||||
|
if (kind === "subscription" && !s.subscription) return false;
|
||||||
|
if (status && statusOf(s) !== status) return false;
|
||||||
|
if (q) {
|
||||||
|
const hay = `${s.identity} ${s.subscriptionHolder ?? ""}`.toLowerCase();
|
||||||
|
if (!hay.includes(q)) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}, [sessions, search, status, kind]);
|
||||||
|
|
||||||
|
const statusOpts: SegOption<StatusFilter>[] = [
|
||||||
|
{ value: "unpaid", label: t("booth.fStatusUnpaid") },
|
||||||
|
{ value: "paid", label: t("booth.fStatusPaid") },
|
||||||
|
{ value: "exiting", label: t("booth.fStatusExiting") },
|
||||||
|
{ value: "overstay", label: t("booth.fStatusOverstay") },
|
||||||
|
];
|
||||||
|
const kindOpts: SegOption<KindFilter>[] = [
|
||||||
|
{ value: "transient", label: t("booth.fKindTransient") },
|
||||||
|
{ value: "subscription", label: t("booth.fKindSubscription") },
|
||||||
|
];
|
||||||
|
|
||||||
|
async function handleReopen(s: ActiveSession) {
|
||||||
|
setReopenMsg(null);
|
||||||
|
try {
|
||||||
|
const r = await reopen.mutateAsync(s.identity);
|
||||||
|
setReopenMsg({
|
||||||
|
id: s.identity,
|
||||||
|
ok: r.opened,
|
||||||
|
text: r.opened ? t("booth.barrierOpened") : r.reason ?? t("booth.openManually"),
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
setReopenMsg({ id: s.identity, ok: false, text: (e as Error).message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Panel
|
||||||
|
title={t("booth.activeSessions")}
|
||||||
|
right={
|
||||||
|
<span className="text-[10px] uppercase tracking-wider text-term-muted">
|
||||||
|
{filtered.length}
|
||||||
|
{filtered.length !== sessions.length ? `/${sessions.length}` : ""} {t("booth.insideCount")}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
className="min-h-0 flex-1"
|
||||||
|
>
|
||||||
|
<div className="flex h-full flex-col">
|
||||||
|
<FilterBar search={search} onSearch={setSearch} searchPlaceholder={t("booth.filterSearchSessions")}>
|
||||||
|
<SegGroup value={status} options={statusOpts} onChange={setStatus} allLabel={t("booth.filterAll")} />
|
||||||
|
<SegGroup value={kind} options={kindOpts} onChange={setKind} allLabel={t("booth.filterAll")} />
|
||||||
|
</FilterBar>
|
||||||
|
|
||||||
|
<div className="min-h-0 flex-1 overflow-y-auto pr-1">
|
||||||
|
{filtered.length === 0 ? (
|
||||||
|
<div className="text-term-muted">
|
||||||
|
{isLoading
|
||||||
|
? t("common.loading")
|
||||||
|
: sessions.length === 0
|
||||||
|
? t("booth.noActiveSessions")
|
||||||
|
: t("booth.noMatch")}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
filtered.map((s) => {
|
||||||
|
const badge = statusBadge(s);
|
||||||
|
const msg = reopenMsg?.id === s.identity ? reopenMsg : null;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={s.identity}
|
||||||
|
className="flex items-center gap-3 border-b border-term-border/50 py-1.5 text-[12px] tabular-nums"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onPick(s.identity)}
|
||||||
|
className="flex flex-1 items-center gap-3 text-left hover:text-term-amber"
|
||||||
|
title={t("booth.openPayExit")}
|
||||||
|
>
|
||||||
|
<span className="text-term-text">
|
||||||
|
{s.subscription ? `★ ${s.subscriptionHolder ?? t("subs.unnamed")}` : s.identity}
|
||||||
|
</span>
|
||||||
|
{s.plate && (
|
||||||
|
<span
|
||||||
|
className="rounded border border-term-border px-1 font-semibold tracking-wide text-term-amber"
|
||||||
|
title={t("booth.plateTitle")}
|
||||||
|
>
|
||||||
|
{s.plate}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span className="text-term-muted">{formatRelativeDateTime(s.enteredAt, t)}</span>
|
||||||
|
<span className="text-term-muted">{formatDuration(s.enteredAt, new Date().toISOString())}</span>
|
||||||
|
<span
|
||||||
|
className={`ml-auto w-16 text-right font-semibold uppercase ${badge.cls}`}
|
||||||
|
title={badge.titleKey ? t(badge.titleKey) : undefined}
|
||||||
|
>
|
||||||
|
{t(badge.key)}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Open barrier — PAID-and-still-in-grace transient OR a SUBSCRIPTION
|
||||||
|
(prepaid). NOT an OVERSTAY session: its grace has expired, so the car
|
||||||
|
owes a top-up — the row routes to the pay/exit modal instead (no
|
||||||
|
free overstay exit). An unpaid transient also has no button
|
||||||
|
(no-unpaid-bypass). Mirrors reopenBarrier's server-side guard. */}
|
||||||
|
{(s.paidAt && !s.overstay) || s.subscription ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={reopen.isPending || !shiftReady}
|
||||||
|
onClick={() => handleReopen(s)}
|
||||||
|
className="btn btn-pay btn-sm shrink-0"
|
||||||
|
title={shiftReady ? t("booth.openBarrierTitle") : t("shift.gateTitle")}
|
||||||
|
>
|
||||||
|
{t("booth.openBarrier")}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<span className="w-[88px] shrink-0" />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{msg && (
|
||||||
|
<span className={`shrink-0 text-[10px] ${msg.ok ? "text-term-green" : "text-term-red"}`}>
|
||||||
|
{msg.text}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,15 +1,17 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { fetchMe, logout, type SessionUser } from "./api.js";
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { RouterProvider } from "@tanstack/react-router";
|
||||||
|
import { fetchMe, type SessionUser } from "./api.js";
|
||||||
import { Login } from "./Login.js";
|
import { Login } from "./Login.js";
|
||||||
import { PermitManager } from "./PermitManager.js";
|
import { queryClient } from "./lib/query.js";
|
||||||
import { SetupWizard } from "./SetupWizard.js";
|
import { setLanguage } from "./lib/i18n/index.js";
|
||||||
import { ShiftControl } from "./ShiftControl.js";
|
import { applyTheme } from "./lib/theme.js";
|
||||||
import { SiteSettings } from "./SiteSettings.js";
|
import { router } from "./router.js";
|
||||||
import { TariffComposer } from "./TariffComposer.js";
|
|
||||||
|
|
||||||
// Operator UI shell. Plain React (no admin framework) — the operator UI is
|
// App root: bootstraps the session (cookie-based, from /api/auth/me), then hands
|
||||||
// simple enough that a framework's abstractions cost more than they save.
|
// off to TanStack Router inside the QueryClient provider. The router renders the
|
||||||
// Auth is cookie-based; the SPA bootstraps the session from /api/auth/me.
|
// terminal chrome + screens; auth gating stays here (Login until signed in), and
|
||||||
|
// the signed-in user flows into the router context for role-based route guards.
|
||||||
// See wiki/entities/react-vite-spa.md and local-jwt-auth.md.
|
// See wiki/entities/react-vite-spa.md and local-jwt-auth.md.
|
||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
@@ -22,37 +24,32 @@ export function App() {
|
|||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
if (loading) return <p style={{ fontFamily: "system-ui", padding: "2rem" }}>Loading…</p>;
|
// Apply the signed-in user's preferred language + theme whenever they resolve/
|
||||||
if (!user) return <Login onLoggedIn={setUser} />;
|
// change (login, bootstrap, or a toggle). Albanian + dark are the defaults before
|
||||||
|
// auth resolves; on logout, fall back to dark so the Login screen is consistent.
|
||||||
|
useEffect(() => {
|
||||||
|
if (user) {
|
||||||
|
setLanguage(user.language);
|
||||||
|
applyTheme(user.theme);
|
||||||
|
} else {
|
||||||
|
applyTheme("dark");
|
||||||
|
}
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <div className="flex h-screen items-center justify-center text-term-muted">loading…</div>;
|
||||||
|
}
|
||||||
|
if (!user) {
|
||||||
|
return (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<Login onLoggedIn={setUser} />
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main style={{ fontFamily: "system-ui", padding: "2rem", maxWidth: 720 }}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<header style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
|
<RouterProvider router={router} context={{ user, setUser }} />
|
||||||
<h1 style={{ margin: 0 }}>Parking System</h1>
|
</QueryClientProvider>
|
||||||
<span style={{ color: "#555" }}>
|
|
||||||
{user.username} ({user.role}){" "}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={async () => {
|
|
||||||
await logout();
|
|
||||||
setUser(null);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Log out
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
</header>
|
|
||||||
<SiteSettings canEdit={user.role === "admin"} />
|
|
||||||
{user.role !== "readonly" && <ShiftControl />}
|
|
||||||
{user.role === "admin" ? (
|
|
||||||
<>
|
|
||||||
<SetupWizard />
|
|
||||||
<TariffComposer />
|
|
||||||
<PermitManager />
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<p style={{ marginTop: "1rem" }}>Signed in. (Operator console coming soon.)</p>
|
|
||||||
)}
|
|
||||||
</main>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,428 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import * as Dialog from "@radix-ui/react-dialog";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
boothExit,
|
||||||
|
fetchSiteConfig,
|
||||||
|
lookupSession,
|
||||||
|
openShift,
|
||||||
|
paySession,
|
||||||
|
printReceipt,
|
||||||
|
printVoucher,
|
||||||
|
reopenBarrier,
|
||||||
|
type SessionLookup,
|
||||||
|
} from "./api.js";
|
||||||
|
import { qk } from "./lib/query.js";
|
||||||
|
import { useShift } from "./lib/use-shift.js";
|
||||||
|
import { formatDuration, formatMoney, formatTime, formatRelativeDateTime } from "./lib/format.js";
|
||||||
|
import { SnapshotStrip } from "./ui/SnapshotStrip.js";
|
||||||
|
|
||||||
|
// The booth pay/exit modal. Opened when the operator submits a ticket id. Shows the
|
||||||
|
// session (entry, exit=now, duration, total owed) + entry/exit snapshots, takes
|
||||||
|
// payment, then EITHER prints an exit voucher (customer self-exits at a distant
|
||||||
|
// exit) OR fires the exit immediately (booth at/near the exit) — controlled by a
|
||||||
|
// checkbox defaulting from site_config.exitVoucherDefault. See booth-exit-flow.md.
|
||||||
|
|
||||||
|
type Phase = "review" | "paying" | "finishing" | "done" | "error";
|
||||||
|
|
||||||
|
export function BoothPayModal({ identity, onClose }: { identity: string; onClose: () => void }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const session = useQuery({ queryKey: ["session", identity], queryFn: () => lookupSession(identity) });
|
||||||
|
const config = useQuery({ queryKey: qk.siteConfig, queryFn: fetchSiteConfig });
|
||||||
|
|
||||||
|
// A shift must be open (and mine) before any pay/exit/voucher action — the booth
|
||||||
|
// money path is gated. The server enforces this too (409 no_shift); the modal
|
||||||
|
// surfaces it up front and offers a one-click open. See wiki/concepts/shift.md.
|
||||||
|
const { isOpen: shiftOpen, isMine: shiftMine, blockedByOther, heldBy } = useShift();
|
||||||
|
const shiftReady = shiftOpen && shiftMine;
|
||||||
|
|
||||||
|
const [tender, setTender] = useState<"cash" | "card">("cash");
|
||||||
|
const [printVoucherChecked, setPrintVoucherChecked] = useState<boolean | null>(null);
|
||||||
|
const [phase, setPhase] = useState<Phase>("review");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [result, setResult] = useState<string | null>(null);
|
||||||
|
const [openingShift, setOpeningShift] = useState(false);
|
||||||
|
const [reprinting, setReprinting] = useState(false);
|
||||||
|
|
||||||
|
const s: SessionLookup | undefined = session.data;
|
||||||
|
// Checkbox default comes from config the first time it loads; operator can toggle.
|
||||||
|
const voucher = printVoucherChecked ?? config.data?.exitVoucherDefault ?? false;
|
||||||
|
|
||||||
|
const alreadyPaid = s?.paidAt != null;
|
||||||
|
const isSubscription = s?.subscription === true;
|
||||||
|
// OVERSTAY = paid but walk-back grace expired with no exit → a NEW period began; owes
|
||||||
|
// a fresh TOP-UP. Treat it as payable even though it's "already paid": the car must
|
||||||
|
// settle the new period's fee (s.amountMinor, priced from grace-expiry) before any
|
||||||
|
// exit. A normal within-grace paid session is NOT payable (it's settled). See
|
||||||
|
// booth-exit-flow.md / reopenBarrier server guard.
|
||||||
|
const isOverstay = s?.overstay === true;
|
||||||
|
// A subscription is normally prepaid (never charged). EXCEPTION: a time-window plan can
|
||||||
|
// owe an out-of-window TARIFF-BRIDGE charge (early entry / late exit) — lookup() returns
|
||||||
|
// it as s.amountMinor, and exit is GATED until it's paid. So a subscription IS payable
|
||||||
|
// when it has an amount due. Otherwise the only action is an audited assist-open.
|
||||||
|
const subWindowDue = !!(isSubscription && (s?.amountMinor ?? 0) > 0);
|
||||||
|
// Allow pay for an unpaid transient, an overstay top-up, or a subscriber window charge.
|
||||||
|
const canPay = !!(
|
||||||
|
shiftReady &&
|
||||||
|
s?.found &&
|
||||||
|
s.open &&
|
||||||
|
((!alreadyPaid && !isSubscription) || isOverstay || subWindowDue)
|
||||||
|
);
|
||||||
|
|
||||||
|
async function handleOpenBarrier() {
|
||||||
|
if (!s) return;
|
||||||
|
setError(null);
|
||||||
|
setPhase("finishing");
|
||||||
|
try {
|
||||||
|
const r = await reopenBarrier(identity);
|
||||||
|
setResult(r.opened ? t("pay.subBarrierOpened") : t("pay.paidExitRecorded", { reason: r.reason ?? t("booth.openManually") }));
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.events });
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.activeSessions });
|
||||||
|
setPhase("done");
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
setPhase("error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleOpenShift() {
|
||||||
|
setOpeningShift(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await openShift();
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.shift });
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.events });
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setOpeningShift(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleReprintReceipt() {
|
||||||
|
setReprinting(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const r = await printReceipt(identity);
|
||||||
|
setResult(t("pay.receiptReprinted", { printer: r.printedBy }));
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setReprinting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handlePayAndExit() {
|
||||||
|
if (!s) return;
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
// 1. Take payment. For a first stay this is the only charge; for an OVERSTAY the
|
||||||
|
// session is "already paid" but a new period accrued — we still charge (canPay
|
||||||
|
// is true). A settled within-grace session is not payable (canPay false) and is
|
||||||
|
// skipped. The server re-quotes authoritatively (overstay → from grace-expiry).
|
||||||
|
if (canPay) {
|
||||||
|
setPhase("paying");
|
||||||
|
await paySession(identity, tender);
|
||||||
|
}
|
||||||
|
// 2. Voucher OR immediate exit.
|
||||||
|
setPhase("finishing");
|
||||||
|
if (voucher) {
|
||||||
|
// The voucher slip carries the payment detail + barcode + grace.
|
||||||
|
const r = await printVoucher(identity);
|
||||||
|
setResult(t("pay.voucherPrinted", { printer: r.printedBy }));
|
||||||
|
} else {
|
||||||
|
const r = await boothExit(identity);
|
||||||
|
// No voucher → auto-print a standalone payment receipt for transparency.
|
||||||
|
// Best-effort: a printer fault must NOT block the exit that already happened;
|
||||||
|
// the operator can reprint from the done screen.
|
||||||
|
let receiptNote = "";
|
||||||
|
try {
|
||||||
|
await printReceipt(identity);
|
||||||
|
} catch {
|
||||||
|
receiptNote = ` ${t("pay.receiptPrintFailed")}`;
|
||||||
|
}
|
||||||
|
setResult(
|
||||||
|
(r.opened
|
||||||
|
? t("pay.paidBarrierOpened")
|
||||||
|
: t("pay.paidExitRecorded", { reason: r.reason ?? t("booth.openManually") })) +
|
||||||
|
receiptNote,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Refresh the live views.
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.events });
|
||||||
|
void qc.invalidateQueries({ queryKey: qk.occupancy });
|
||||||
|
setPhase("done");
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
setPhase("error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog.Root open onOpenChange={(o) => !o && onClose()}>
|
||||||
|
<Dialog.Portal>
|
||||||
|
<Dialog.Overlay className="fixed inset-0 z-40 bg-black/70" />
|
||||||
|
<Dialog.Content
|
||||||
|
className="fixed left-1/2 top-1/2 z-50 w-[560px] max-w-[95vw] -translate-x-1/2 -translate-y-1/2 rounded-term border border-term-border bg-term-panel font-mono text-term-text shadow-2xl"
|
||||||
|
aria-describedby={undefined}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between border-b border-term-border bg-term-panel-2 px-4 py-2">
|
||||||
|
<Dialog.Title className="m-0 text-[12px] font-semibold uppercase tracking-wider text-term-amber">
|
||||||
|
{isSubscription
|
||||||
|
? `${t("pay.subscription")} · ${s?.subscriptionHolder ?? t("subs.unnamed")}`
|
||||||
|
: `${t("pay.ticket")} ${identity}`}
|
||||||
|
</Dialog.Title>
|
||||||
|
<Dialog.Close className="text-term-muted hover:text-term-text" aria-label={t("common.close")}>
|
||||||
|
✕
|
||||||
|
</Dialog.Close>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-3 p-4">
|
||||||
|
{/* Shift gate — block all actions until THIS operator has a shift open.
|
||||||
|
Another operator's open shift can't be operated under (no shared
|
||||||
|
till); only an "open mine" path when no shift is open at all. */}
|
||||||
|
{!shiftReady && (
|
||||||
|
<div className="rounded-term border border-term-amber bg-term-amber/5 px-3 py-2">
|
||||||
|
{blockedByOther ? (
|
||||||
|
<>
|
||||||
|
<div className="text-[12px] font-semibold uppercase tracking-wider text-term-amber">
|
||||||
|
{t("shift.gateOtherTitle")}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-[12px] text-term-text">
|
||||||
|
{t("shift.gateOtherBody", { operator: heldBy ?? "?" })}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="text-[12px] font-semibold uppercase tracking-wider text-term-amber">
|
||||||
|
{t("shift.gateTitle")}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-[12px] text-term-text">{t("shift.gateBody")}</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleOpenShift}
|
||||||
|
disabled={openingShift}
|
||||||
|
className="btn btn-go btn-sm mt-2"
|
||||||
|
>
|
||||||
|
{openingShift ? t("shift.opening") : t("shift.openNow")}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{session.isLoading && <div className="text-term-muted">{t("pay.lookingUp")}</div>}
|
||||||
|
|
||||||
|
{s && !s.found && (
|
||||||
|
<div className="rounded-term border border-term-red px-3 py-2 text-term-red">
|
||||||
|
{t("pay.noSessionFound")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{s && s.found && !s.open && (
|
||||||
|
<div className="rounded-term border border-term-amber px-3 py-2 text-term-amber">
|
||||||
|
{t("pay.alreadyClosed", { time: formatTime(s.exitedAt) })}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{s && s.found && s.open && (
|
||||||
|
<>
|
||||||
|
{/* Session figures */}
|
||||||
|
<div className="grid grid-cols-2 gap-x-6 gap-y-1 tabular-nums">
|
||||||
|
<Row label={t("pay.entry")} value={formatRelativeDateTime(s.enteredAt, t)} />
|
||||||
|
<Row label={t("pay.now")} value={formatTime(new Date().toISOString())} />
|
||||||
|
<Row
|
||||||
|
label={t("pay.duration")}
|
||||||
|
value={s.enteredAt ? formatDuration(s.enteredAt, new Date().toISOString()) : "—"}
|
||||||
|
/>
|
||||||
|
<Row
|
||||||
|
label={t("pay.statusLabel")}
|
||||||
|
value={
|
||||||
|
isSubscription
|
||||||
|
? t("pay.subscription")
|
||||||
|
: isOverstay
|
||||||
|
? t("pay.overstay")
|
||||||
|
: alreadyPaid
|
||||||
|
? t("pay.paid")
|
||||||
|
: t("pay.unpaid")
|
||||||
|
}
|
||||||
|
valueClass={
|
||||||
|
isSubscription
|
||||||
|
? "text-term-cyan"
|
||||||
|
: isOverstay
|
||||||
|
? "text-term-red"
|
||||||
|
: alreadyPaid
|
||||||
|
? "text-term-green"
|
||||||
|
: "text-term-amber"
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Total — a subscription is prepaid (no amount) UNLESS it owes an
|
||||||
|
out-of-window window charge; then show that amount. For an overstay the
|
||||||
|
amount is the TOP-UP delta, not the whole stay. */}
|
||||||
|
<div className="flex items-end justify-between rounded-term bg-term-panel-2 px-3 py-2">
|
||||||
|
<span className="text-[11px] uppercase tracking-wider text-term-muted">
|
||||||
|
{subWindowDue ? t("pay.windowCharge") : isSubscription ? t("pay.plan") : isOverstay ? t("pay.topUp") : t("pay.total")}
|
||||||
|
</span>
|
||||||
|
<span className="text-3xl font-bold text-term-cyan">
|
||||||
|
{subWindowDue && s.amountMinor != null && s.currency
|
||||||
|
? formatMoney(s.amountMinor, s.currency)
|
||||||
|
: isSubscription
|
||||||
|
? t("pay.prepaid")
|
||||||
|
: s.amountMinor != null && s.currency
|
||||||
|
? formatMoney(s.amountMinor, s.currency)
|
||||||
|
: alreadyPaid
|
||||||
|
? t("booth.badgePaid")
|
||||||
|
: t("pay.noTariff")}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* For a subscription with a window charge, explain why it's payable. For a
|
||||||
|
plain prepaid subscription, explain the assist-open is the only action. */}
|
||||||
|
{subWindowDue ? (
|
||||||
|
<div className="rounded-term border border-term-amber/40 bg-term-amber/5 px-3 py-2 text-[12px] text-term-text">
|
||||||
|
{t("pay.windowChargeHint")}
|
||||||
|
</div>
|
||||||
|
) : isSubscription && (
|
||||||
|
<div className="rounded-term border border-term-cyan/40 bg-term-cyan/5 px-3 py-2 text-[12px] text-term-text">
|
||||||
|
{t("pay.subAssistHint")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* For an overstay, explain why a top-up is required (no free exit). */}
|
||||||
|
{isOverstay && (
|
||||||
|
<div className="rounded-term border border-term-red/40 bg-term-red/5 px-3 py-2 text-[12px] text-term-text">
|
||||||
|
{t("pay.overstayHint")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Snapshots */}
|
||||||
|
<SnapshotStrip identity={identity} />
|
||||||
|
|
||||||
|
{phase !== "done" && !isSubscription && (
|
||||||
|
<>
|
||||||
|
{/* Tender */}
|
||||||
|
{canPay && (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-[11px] uppercase tracking-wider text-term-muted">{t("pay.tender")}</span>
|
||||||
|
{(["cash", "card"] as const).map((tn) => (
|
||||||
|
<button
|
||||||
|
key={tn}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setTender(tn)}
|
||||||
|
className={tender === tn ? "btn btn-primary btn-sm" : "btn btn-sm"}
|
||||||
|
>
|
||||||
|
{t(`pay.${tn}`)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Voucher checkbox (default from site config) */}
|
||||||
|
<label className="flex items-center gap-2 text-[12px]">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="accent-term-amber"
|
||||||
|
checked={voucher}
|
||||||
|
onChange={(e) => setPrintVoucherChecked(e.target.checked)}
|
||||||
|
/>
|
||||||
|
{t("pay.printExitVoucher")}
|
||||||
|
<span className="text-term-muted">{t("pay.selfExitHint")}</span>
|
||||||
|
</label>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && <div className="rounded-term border border-term-red px-3 py-2 text-term-red">{error}</div>}
|
||||||
|
{result && (
|
||||||
|
<div className="rounded-term border border-term-green px-3 py-2 text-term-green">{result}</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
<div className="flex justify-end gap-2 pt-1">
|
||||||
|
{phase === "done" ? (
|
||||||
|
<>
|
||||||
|
{/* Reprint the payment receipt (slip jammed / customer asks).
|
||||||
|
Only for a charged session — a subscription has no payment. */}
|
||||||
|
{!isSubscription && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleReprintReceipt}
|
||||||
|
disabled={reprinting}
|
||||||
|
className="btn btn-sm"
|
||||||
|
>
|
||||||
|
{reprinting ? t("pay.reprinting") : t("pay.reprintReceipt")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="btn btn-primary btn-sm"
|
||||||
|
>
|
||||||
|
{t("common.close")}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="btn btn-ghost btn-sm"
|
||||||
|
>
|
||||||
|
{t("common.cancel")}
|
||||||
|
</button>
|
||||||
|
{isSubscription ? (
|
||||||
|
// Prepaid — the only action is the audited barrier open (assist
|
||||||
|
// a faulty exit reader / missing card). Gated on an open shift.
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleOpenBarrier}
|
||||||
|
disabled={!shiftReady || phase === "finishing"}
|
||||||
|
className="btn btn-pay btn-lg"
|
||||||
|
>
|
||||||
|
{phase === "finishing" ? t("pay.opening") : t("booth.openBarrier")}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handlePayAndExit}
|
||||||
|
disabled={!shiftReady || phase === "paying" || phase === "finishing"}
|
||||||
|
className="btn btn-go btn-lg"
|
||||||
|
>
|
||||||
|
{phase === "paying"
|
||||||
|
? t("pay.takingPayment")
|
||||||
|
: phase === "finishing"
|
||||||
|
? voucher
|
||||||
|
? t("pay.printingVoucher")
|
||||||
|
: t("pay.opening")
|
||||||
|
: alreadyPaid
|
||||||
|
? voucher
|
||||||
|
? t("pay.printVoucher")
|
||||||
|
: t("pay.openBarrier")
|
||||||
|
: voucher
|
||||||
|
? t("pay.payAndVoucher")
|
||||||
|
: t("pay.payAndOpen")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Dialog.Content>
|
||||||
|
</Dialog.Portal>
|
||||||
|
</Dialog.Root>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Row({ label, value, valueClass = "" }: { label: string; value: string; valueClass?: string }) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-baseline justify-between">
|
||||||
|
<span className="text-[11px] uppercase tracking-wider text-term-muted">{label}</span>
|
||||||
|
<span className={`text-sm ${valueClass}`}>{value}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,539 @@
|
|||||||
|
import { useRef, useState, type ReactNode } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { fetchEvents, fetchOccupancy, type LedgerEvent, type Occupancy } from "./api.js";
|
||||||
|
import { formatMoney } from "./lib/format.js";
|
||||||
|
import { qk } from "./lib/query.js";
|
||||||
|
import { useLiveStore } from "./lib/live-store.js";
|
||||||
|
import { useShift } from "./lib/use-shift.js";
|
||||||
|
import { Panel } from "./ui/Panel.js";
|
||||||
|
import { StatusDot } from "./ui/StatusDot.js";
|
||||||
|
import { BoothPayModal } from "./BoothPayModal.js";
|
||||||
|
import { ActiveSessions } from "./ActiveSessions.js";
|
||||||
|
import { Modal } from "./ui/Modal.js";
|
||||||
|
import { SnapshotStrip } from "./ui/SnapshotStrip.js";
|
||||||
|
import { FilterBar, SegGroup, type SegOption } from "./ui/FilterBar.js";
|
||||||
|
import { renderReason } from "./lib/reason.js";
|
||||||
|
|
||||||
|
// The live operator booth view — the real-time heart of the console. Occupancy
|
||||||
|
// gauge + a streaming entry/exit/payment ticker. Query owns the initial load and
|
||||||
|
// the authoritative numbers; the WS-fed live store overlays real-time updates so
|
||||||
|
// the screen reacts the instant a car enters or exits. Dense, dark, glanceable.
|
||||||
|
|
||||||
|
/** Per-event-type display: i18n label key + accent colour for the ticker. */
|
||||||
|
const EVENT_STYLE: Record<string, { labelKey: string; color: string }> = {
|
||||||
|
vehicle_entry: { labelKey: "booth.evtEntry", color: "text-term-green" },
|
||||||
|
vehicle_exit: { labelKey: "booth.evtExit", color: "text-term-red" },
|
||||||
|
payment: { labelKey: "booth.evtPay", color: "text-term-cyan" },
|
||||||
|
void: { labelKey: "booth.evtVoid", color: "text-term-amber" },
|
||||||
|
barrier_open_command: { labelKey: "booth.evtOpenCmd", color: "text-term-muted" },
|
||||||
|
barrier_open_observed: { labelKey: "booth.evtOpenObserved", color: "text-term-muted" },
|
||||||
|
shift_open: { labelKey: "booth.evtShiftOpen", color: "text-term-amber" },
|
||||||
|
shift_z_report: { labelKey: "booth.evtShiftZ", color: "text-term-amber" },
|
||||||
|
cash_movement: { labelKey: "booth.evtCashMovement", color: "text-term-cyan" },
|
||||||
|
cash_in: { labelKey: "booth.evtCashIn", color: "text-term-green" },
|
||||||
|
cash_out: { labelKey: "booth.evtCashOut", color: "text-term-amber" },
|
||||||
|
anomaly: { labelKey: "booth.evtAnomaly", color: "text-term-red" },
|
||||||
|
};
|
||||||
|
|
||||||
|
// Live-feed filter category for an event type. Several ledger types collapse into a
|
||||||
|
// few operator-meaningful buckets; the rest (barrier/shift/cash) fall outside the
|
||||||
|
// filter and only show under "all".
|
||||||
|
type FeedCat = "entry" | "exit" | "pay" | "void" | "anomaly";
|
||||||
|
function feedCat(type: string): FeedCat | null {
|
||||||
|
switch (type) {
|
||||||
|
case "vehicle_entry":
|
||||||
|
return "entry";
|
||||||
|
case "vehicle_exit":
|
||||||
|
return "exit";
|
||||||
|
case "payment":
|
||||||
|
return "pay";
|
||||||
|
case "void":
|
||||||
|
return "void";
|
||||||
|
case "anomaly":
|
||||||
|
return "anomaly";
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function hhmmss(iso: string): string {
|
||||||
|
// Local time-of-day, terminal style. Defensive against a bad timestamp.
|
||||||
|
const d = new Date(iso);
|
||||||
|
return Number.isNaN(d.getTime()) ? "--:--:--" : d.toTimeString().slice(0, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
function OccupancyGauge({ occ }: { occ: Occupancy }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const pct = occ.capacity ? Math.min(100, Math.round((occ.count / occ.capacity) * 100)) : null;
|
||||||
|
const barColor = occ.full ? "bg-term-red" : pct != null && pct >= 85 ? "bg-term-amber" : "bg-term-green";
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<div className="flex items-end gap-4">
|
||||||
|
<div className="text-6xl font-bold leading-none tabular-nums text-term-text">{occ.count}</div>
|
||||||
|
<div className="pb-1 text-term-muted">
|
||||||
|
<div className="text-[11px] uppercase tracking-wider">{t("booth.inside")}</div>
|
||||||
|
<div className="text-sm tabular-nums">
|
||||||
|
{occ.capacity == null ? t("booth.uncapped") : `${t("booth.of")} ${occ.capacity}`}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="ml-auto text-right">
|
||||||
|
<div className="text-[11px] uppercase tracking-wider text-term-muted">{t("booth.free")}</div>
|
||||||
|
<div className={`text-3xl font-bold tabular-nums ${occ.full ? "text-term-red" : "text-term-green"}`}>
|
||||||
|
{occ.free == null ? "∞" : occ.free}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{pct != null && (
|
||||||
|
<div className="h-2 w-full overflow-hidden rounded-term bg-term-panel-2">
|
||||||
|
<div className={`h-full ${barColor} transition-[width] duration-300`} style={{ width: `${pct}%` }} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{occ.full && (
|
||||||
|
<div className="rounded-term border border-term-red px-2 py-1 text-center text-[11px] font-bold uppercase tracking-widest text-term-red">
|
||||||
|
{t("booth.lotFull")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Translated classification badges derived from a payload's boolean flags. Unlike
|
||||||
|
* `reason` (an immutable English sentence baked into the signed ledger, shown
|
||||||
|
* verbatim), these are computed client-side so they CAN be localized. They give a
|
||||||
|
* glanceable "what kind of anomaly" tag without parsing the free-text reason. */
|
||||||
|
function eventBadges(p: LedgerEvent["payload"]): string[] {
|
||||||
|
if (!p) return [];
|
||||||
|
const keys: string[] = [];
|
||||||
|
if (p.entryRefused) keys.push("booth.badgeEntryRefused");
|
||||||
|
if (p.exitRefused) keys.push("booth.badgeExitRefused");
|
||||||
|
if (p.full) keys.push("booth.badgeLotFull");
|
||||||
|
if (p.exitOpenFailed) keys.push("booth.badgeBarrierFailed");
|
||||||
|
if (p.permitRefused) keys.push("booth.badgeSubRefused");
|
||||||
|
if (p.ticketPrinted === false) keys.push("booth.badgeNoTicket");
|
||||||
|
if (p.subscriptionSale) keys.push("booth.badgeSubSale");
|
||||||
|
// Subscriber entered/exited outside their plan's allowed window → owes a deferred
|
||||||
|
// transient charge, collected (gated) at exit. Flag it so the operator KNOWS now.
|
||||||
|
if (typeof p.windowOwedMinor === "number" && p.windowOwedMinor > 0) keys.push("booth.badgeWindowCharge");
|
||||||
|
if (p.source === "manual" && !p.subscriptionSale) keys.push("booth.badgeManualOpen");
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The i18n key for a subscriber's access medium (`via`), or null. Lets the activity
|
||||||
|
* log show HOW a subscriber entered/left — QR code, RFID card/chip, or plate. */
|
||||||
|
function viaKey(p: LedgerEvent["payload"]): string | null {
|
||||||
|
if (!p) return null;
|
||||||
|
if (p.via === "qr") return "booth.viaQr";
|
||||||
|
if (p.via === "card") return "booth.viaCard";
|
||||||
|
if (p.via === "plate") return "booth.viaPlate";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A short money summary for payment events (e.g. "350.00 ALL"). */
|
||||||
|
function paymentSummary(p: LedgerEvent["payload"]): string | null {
|
||||||
|
if (!p || typeof p.amountMinor !== "number" || !p.currency) return null;
|
||||||
|
return formatMoney(p.amountMinor, p.currency);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What to SHOW for an event's actor. A subscription occurrence has an opaque
|
||||||
|
* `SUBSESS-…` identity; the server resolves the holder's name into `subscriberLabel`,
|
||||||
|
* so we show that (e.g. "Aqif Kopertoni") instead. Otherwise the identity itself. */
|
||||||
|
function displayIdentity(e: LedgerEvent): string {
|
||||||
|
return e.subscriberLabel ?? e.identity ?? "—";
|
||||||
|
}
|
||||||
|
|
||||||
|
function EventRow({ e, onOpen }: { e: LedgerEvent; onOpen: (e: LedgerEvent) => void }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const style = EVENT_STYLE[e.type];
|
||||||
|
const label = style ? t(style.labelKey) : e.type.toUpperCase();
|
||||||
|
const isAnomaly = e.type === "anomaly";
|
||||||
|
const p = e.payload;
|
||||||
|
// Localize the reason from the signed reasonCode (falls back to the English text on
|
||||||
|
// legacy events). Anomalies ALWAYS get a detail line so a red flag is never silent.
|
||||||
|
const reason = renderReason(p, t);
|
||||||
|
const amount = paymentSummary(p);
|
||||||
|
const badges = eventBadges(p);
|
||||||
|
const via = viaKey(p);
|
||||||
|
const detail = reason ?? amount ?? (isAnomaly ? t("booth.evtNoReason") : null);
|
||||||
|
const showDetail = detail != null || badges.length > 0 || via != null;
|
||||||
|
|
||||||
|
// The whole row is a button → opens the event-detail modal (full payload + the
|
||||||
|
// session's entry/exit snapshots). A grid keeps the time/label/identity/index
|
||||||
|
// columns aligned across rows; the detail line lives in its own row, indented to
|
||||||
|
// start under the identity column so it never collides with the ticket code.
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onOpen(e)}
|
||||||
|
className={`grid w-full grid-cols-[auto_5rem_1fr_auto] items-center gap-x-3 gap-y-0.5 border-b border-term-border/50 px-1 py-1 text-left text-[12px] tabular-nums hover:bg-term-panel-2 ${
|
||||||
|
isAnomaly ? "bg-term-red/5" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="text-term-muted">{hhmmss(e.occurredAt)}</span>
|
||||||
|
<span className={`shrink-0 font-semibold ${style?.color ?? "text-term-text"}`}>{label}</span>
|
||||||
|
<span className="flex min-w-0 items-center gap-2">
|
||||||
|
<span className="truncate text-term-text">{displayIdentity(e)}</span>
|
||||||
|
{e.plate && (
|
||||||
|
<span
|
||||||
|
className="shrink-0 rounded border border-term-border px-1 text-[11px] font-semibold tracking-wide text-term-amber"
|
||||||
|
title={t("booth.plateTitle")}
|
||||||
|
>
|
||||||
|
{e.plate}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<span className="text-term-muted">#{e.index}</span>
|
||||||
|
{showDetail && (
|
||||||
|
<div className="col-start-3 col-end-5 flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||||
|
{badges.map((k) => (
|
||||||
|
<span
|
||||||
|
key={k}
|
||||||
|
className="rounded-sm bg-term-red/15 px-1.5 py-px text-[10px] font-semibold uppercase tracking-wide text-term-red"
|
||||||
|
>
|
||||||
|
{t(k)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
{via && (
|
||||||
|
<span className="rounded-sm bg-term-cyan/15 px-1.5 py-px text-[10px] font-semibold uppercase tracking-wide text-term-cyan">
|
||||||
|
{t(via)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{detail && (
|
||||||
|
<span className={`text-[11px] ${isAnomaly ? "text-term-red/90" : "text-term-muted"}`}>{detail}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One label/value line in the event-detail modal. */
|
||||||
|
function DetailRow({ label, children }: { label: string; children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="grid grid-cols-[8rem_1fr] gap-3 border-b border-term-border/40 py-1.5 text-[12px]">
|
||||||
|
<span className="text-[11px] uppercase tracking-wider text-term-muted">{label}</span>
|
||||||
|
<span className="min-w-0 break-words text-term-text">{children}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Full read-only detail for one ledger event: business fields + the human-readable
|
||||||
|
* reason + the session's entry/exit snapshots, then the signed-chain provenance
|
||||||
|
* (signature/prev-hash/key) for an audit trail. Read-only — the ledger is immutable;
|
||||||
|
* this only DISPLAYS the signed record. */
|
||||||
|
function EventDetailModal({ e, onClose }: { e: LedgerEvent; onClose: () => void }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const style = EVENT_STYLE[e.type];
|
||||||
|
const label = style ? t(style.labelKey) : e.type.toUpperCase();
|
||||||
|
const p = e.payload;
|
||||||
|
const reason = renderReason(p, t);
|
||||||
|
const amount = paymentSummary(p);
|
||||||
|
const badges = eventBadges(p);
|
||||||
|
const isAnomaly = e.type === "anomaly";
|
||||||
|
|
||||||
|
// Pretty money for any minor-unit amount in the payload.
|
||||||
|
const money =
|
||||||
|
p && typeof p.amountMinor === "number" && typeof p.currency === "string"
|
||||||
|
? formatMoney(p.amountMinor, p.currency)
|
||||||
|
: null;
|
||||||
|
// Pull out the business fields worth a labelled row. Everything else (and the raw
|
||||||
|
// bytes) lives behind the audit disclosure — the operator sees a clean summary.
|
||||||
|
const sessionRef = typeof p?.sessionRef === "string" ? p.sessionRef : null;
|
||||||
|
const plate = typeof p?.plate === "string" ? p.plate : null;
|
||||||
|
const category = typeof p?.category === "string" ? p.category : null;
|
||||||
|
const operator = typeof p?.operator === "string" ? p.operator : null;
|
||||||
|
const tariffVersionId = typeof p?.tariffVersionId === "string" ? p.tariffVersionId : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal open onClose={onClose} title={t("booth.eventDetail")} width="max-w-2xl">
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
{/* Headline: the type + localized reason, prominent for anomalies. */}
|
||||||
|
<div className={`rounded-term border p-3 ${isAnomaly ? "border-term-red/50 bg-term-red/5" : "border-term-border bg-term-panel-2"}`}>
|
||||||
|
<div className={`text-sm font-bold uppercase tracking-widest ${style?.color ?? "text-term-text"}`}>{label}</div>
|
||||||
|
{(reason || money) && (
|
||||||
|
<div className={`mt-1 text-[13px] ${isAnomaly ? "text-term-red/90" : "text-term-text"}`}>
|
||||||
|
{reason ?? money}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{!reason && !money && isAnomaly && (
|
||||||
|
<div className="mt-1 text-[13px] text-term-red/90">{t("booth.evtNoReason")}</div>
|
||||||
|
)}
|
||||||
|
{badges.length > 0 && (
|
||||||
|
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||||
|
{badges.map((k) => (
|
||||||
|
<span
|
||||||
|
key={k}
|
||||||
|
className="rounded-sm bg-term-red/15 px-1.5 py-px text-[10px] font-semibold uppercase tracking-wide text-term-red"
|
||||||
|
>
|
||||||
|
{t(k)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Humanized fields — labelled rows, not raw JSON. Only what applies renders. */}
|
||||||
|
<div>
|
||||||
|
<DetailRow label={t("booth.edTime")}>{new Date(e.occurredAt).toLocaleString()}</DetailRow>
|
||||||
|
<DetailRow label={t("booth.edIndex")}>#{e.index}</DetailRow>
|
||||||
|
{e.direction && <DetailRow label={t("booth.edDirection")}>{e.direction}</DetailRow>}
|
||||||
|
{e.source && <DetailRow label={t("booth.edSource")}>{e.source}</DetailRow>}
|
||||||
|
<DetailRow label={t("booth.edIdentity")}>{displayIdentity(e)}</DetailRow>
|
||||||
|
{/* When we showed a subscriber NAME above, also expose the raw occurrence id
|
||||||
|
(the SUBSESS-… session key) for traceability against the ledger. */}
|
||||||
|
{e.subscriberLabel && e.identity && (
|
||||||
|
<DetailRow label={t("booth.edOccurrence")}>
|
||||||
|
<code className="text-[11px] text-term-muted">{e.identity}</code>
|
||||||
|
</DetailRow>
|
||||||
|
)}
|
||||||
|
{money && (
|
||||||
|
<DetailRow label={t("booth.edAmount")}>
|
||||||
|
<span className="text-term-cyan">{money}</span>
|
||||||
|
</DetailRow>
|
||||||
|
)}
|
||||||
|
{typeof p?.tender === "string" && <DetailRow label={t("booth.edTender")}>{p.tender}</DetailRow>}
|
||||||
|
{viaKey(p) && (
|
||||||
|
<DetailRow label={t("booth.edVia")}>
|
||||||
|
<span className="text-term-cyan">{t(viaKey(p)!)}</span>
|
||||||
|
</DetailRow>
|
||||||
|
)}
|
||||||
|
{category && <DetailRow label={t("booth.edCategory")}>{category}</DetailRow>}
|
||||||
|
{plate && <DetailRow label={t("booth.edPlate")}>{plate}</DetailRow>}
|
||||||
|
{operator && <DetailRow label={t("booth.edOperator")}>{operator}</DetailRow>}
|
||||||
|
{sessionRef && sessionRef !== e.identity && (
|
||||||
|
<DetailRow label={t("booth.edSession")}>{sessionRef}</DetailRow>
|
||||||
|
)}
|
||||||
|
{tariffVersionId && (
|
||||||
|
<DetailRow label={t("booth.edTariffVersion")}>
|
||||||
|
<code className="text-[11px] text-term-muted">{tariffVersionId}</code>
|
||||||
|
</DetailRow>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* The entry/exit evidence images for this session's identity. */}
|
||||||
|
{e.identity && (
|
||||||
|
<div>
|
||||||
|
<div className="mb-1.5 text-[11px] uppercase tracking-wider text-term-muted">{t("booth.edSnapshots")}</div>
|
||||||
|
<SnapshotStrip identity={e.identity} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Audit data — collapsed by default. The signed-chain provenance (signature,
|
||||||
|
key, prev-hash) and the raw payload are an auditor's concern, not the
|
||||||
|
operator's; tucking them behind a disclosure keeps the common view clean
|
||||||
|
while preserving the tamper-evidence trail on demand. */}
|
||||||
|
<details className="rounded-term border border-term-border bg-term-panel-2">
|
||||||
|
<summary className="cursor-pointer select-none px-3 py-2 text-[11px] uppercase tracking-wider text-term-muted hover:text-term-text">
|
||||||
|
{t("booth.edAuditData")}
|
||||||
|
</summary>
|
||||||
|
<div className="border-t border-term-border px-3 pb-3 pt-1">
|
||||||
|
<DetailRow label={t("booth.edSignature")}>
|
||||||
|
<code className="break-all text-[11px] text-term-muted">{e.signature}</code>
|
||||||
|
</DetailRow>
|
||||||
|
<DetailRow label={t("booth.edKeyId")}>
|
||||||
|
<code className="text-[11px] text-term-muted">{e.keyId}</code>
|
||||||
|
</DetailRow>
|
||||||
|
<DetailRow label={t("booth.edPrevHash")}>
|
||||||
|
<code className="break-all text-[11px] text-term-muted">{e.prevHash ?? "—"}</code>
|
||||||
|
</DetailRow>
|
||||||
|
<div className="mb-1.5 mt-3 text-[11px] uppercase tracking-wider text-term-muted">
|
||||||
|
{t("booth.edRawPayload")}
|
||||||
|
</div>
|
||||||
|
{p && Object.keys(p).length > 0 ? (
|
||||||
|
<pre className="overflow-x-auto rounded-term border border-term-border bg-term-bg p-2 text-[11px] text-term-text">
|
||||||
|
{JSON.stringify(p, null, 2)}
|
||||||
|
</pre>
|
||||||
|
) : (
|
||||||
|
<div className="text-[12px] text-term-muted">{t("booth.edNoPayload")}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ticket entry: an HID barcode scanner types the id and presses Enter; a manual
|
||||||
|
* operator types it. Either way, submit opens the pay/exit modal for that id. The
|
||||||
|
* input auto-focuses and re-focuses after a scan so the scanner always lands here. */
|
||||||
|
function TicketInput({ onSubmit }: { onSubmit: (identity: string) => void }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [value, setValue] = useState("");
|
||||||
|
const ref = useRef<HTMLInputElement>(null);
|
||||||
|
return (
|
||||||
|
<form
|
||||||
|
className="flex items-center gap-2"
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const id = value.trim();
|
||||||
|
if (id) {
|
||||||
|
onSubmit(id);
|
||||||
|
setValue("");
|
||||||
|
ref.current?.focus();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
ref={ref}
|
||||||
|
autoFocus
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => setValue(e.target.value)}
|
||||||
|
placeholder={t("booth.scanPlaceholder")}
|
||||||
|
inputMode="numeric"
|
||||||
|
className="input h-11 flex-1 px-3 text-lg tabular-nums"
|
||||||
|
/>
|
||||||
|
<button type="submit" className="btn btn-primary btn-lg">
|
||||||
|
{t("booth.open")}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BoothScreen() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
// The site-wide shift drives the log scope: the feed shows ONLY the open shift's
|
||||||
|
// window (per-shift logs, not all history). When no shift is open, the feed is
|
||||||
|
// empty and the operator is prompted to open one.
|
||||||
|
const { isOpen: shiftOpen, startedAt: shiftStart } = useShift();
|
||||||
|
|
||||||
|
// Initial load via Query (also the fallback if the WS is briefly down). The events
|
||||||
|
// query is scoped to the current shift's start so it never shows prior shifts.
|
||||||
|
const occQuery = useQuery({ queryKey: qk.occupancy, queryFn: fetchOccupancy });
|
||||||
|
const eventsQuery = useQuery({
|
||||||
|
queryKey: [...qk.events, shiftStart ?? "none"],
|
||||||
|
queryFn: () => fetchEvents(100, shiftStart ?? undefined),
|
||||||
|
enabled: shiftOpen,
|
||||||
|
});
|
||||||
|
|
||||||
|
// The ticket currently open in the pay/exit modal (null = no modal).
|
||||||
|
const [activeTicket, setActiveTicket] = useState<string | null>(null);
|
||||||
|
// The ledger event open in the read-only detail modal (null = closed).
|
||||||
|
const [detailEvent, setDetailEvent] = useState<LedgerEvent | null>(null);
|
||||||
|
|
||||||
|
// Live-feed filters: free-text search, event category, and direction/source.
|
||||||
|
const [feedSearch, setFeedSearch] = useState("");
|
||||||
|
const [feedType, setFeedType] = useState<FeedCat | "">("");
|
||||||
|
const [feedDir, setFeedDir] = useState<"entry" | "exit" | "">("");
|
||||||
|
const [feedSrc, setFeedSrc] = useState<"booth" | "reader" | "">("");
|
||||||
|
|
||||||
|
// Live overlays from the WS store.
|
||||||
|
const liveOcc = useLiveStore((s) => s.occupancy);
|
||||||
|
const liveFeed = useLiveStore((s) => s.feed);
|
||||||
|
|
||||||
|
// Prefer the live-pushed occupancy; fall back to the query.
|
||||||
|
const occ = liveOcc ?? occQuery.data ?? null;
|
||||||
|
|
||||||
|
// Merge: live events first (newest), then the queried history, de-duped by id —
|
||||||
|
// then clip to the current shift window (the live store spans shifts; the feed
|
||||||
|
// must not show events from before this shift's start). No shift → no feed.
|
||||||
|
const seen = new Set(liveFeed.map((e) => e.id));
|
||||||
|
const history = (eventsQuery.data?.events ?? []).filter((e) => !seen.has(e.id));
|
||||||
|
const merged = [...liveFeed, ...history].slice(0, 200);
|
||||||
|
const scoped =
|
||||||
|
shiftOpen && shiftStart
|
||||||
|
? merged.filter((e) => e.occurredAt >= shiftStart)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
// Apply the live-feed filters. Source maps to booth (operator-initiated `manual`)
|
||||||
|
// vs reader (device-initiated: wiegand/lpr/qr/ticket). Search spans identity,
|
||||||
|
// subscriber label, and any advisory plate on the payload.
|
||||||
|
const fq = feedSearch.trim().toLowerCase();
|
||||||
|
const events = scoped.filter((e) => {
|
||||||
|
if (feedType && feedCat(e.type) !== feedType) return false;
|
||||||
|
if (feedDir && e.direction !== feedDir) return false;
|
||||||
|
if (feedSrc) {
|
||||||
|
const isBooth = e.source === "manual";
|
||||||
|
if (feedSrc === "booth" ? !isBooth : isBooth) return false;
|
||||||
|
}
|
||||||
|
if (fq) {
|
||||||
|
const hay = `${e.identity ?? ""} ${e.subscriberLabel ?? ""} ${e.payload?.plate ?? ""}`.toLowerCase();
|
||||||
|
if (!hay.includes(fq)) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const feedTypeOpts: SegOption<FeedCat>[] = [
|
||||||
|
{ value: "entry", label: t("booth.fEvtEntry") },
|
||||||
|
{ value: "exit", label: t("booth.fEvtExit") },
|
||||||
|
{ value: "pay", label: t("booth.fEvtPay") },
|
||||||
|
{ value: "void", label: t("booth.fEvtVoid") },
|
||||||
|
{ value: "anomaly", label: t("booth.fEvtAnomaly") },
|
||||||
|
];
|
||||||
|
const feedDirOpts: SegOption<"entry" | "exit">[] = [
|
||||||
|
{ value: "entry", label: t("booth.fDirEntry") },
|
||||||
|
{ value: "exit", label: t("booth.fDirExit") },
|
||||||
|
];
|
||||||
|
const feedSrcOpts: SegOption<"booth" | "reader">[] = [
|
||||||
|
{ value: "booth", label: t("booth.fSrcBooth") },
|
||||||
|
{ value: "reader", label: t("booth.fSrcReader") },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="grid h-full grid-cols-1 gap-3 lg:grid-cols-[minmax(320px,1fr)_2fr] lg:grid-rows-[auto_1fr]">
|
||||||
|
{/* Ticket input spans both columns at the top — the operator's primary action. */}
|
||||||
|
<div className="lg:col-span-2">
|
||||||
|
<Panel title={t("booth.processTicket")}>
|
||||||
|
<TicketInput onSubmit={setActiveTicket} />
|
||||||
|
</Panel>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Left column: occupancy gauge above the active-sessions list. */}
|
||||||
|
<div className="flex min-h-0 flex-col gap-3">
|
||||||
|
<Panel title={t("booth.occupancy")} right={<StatusDot />}>
|
||||||
|
{occ ? (
|
||||||
|
<OccupancyGauge occ={occ} />
|
||||||
|
) : (
|
||||||
|
<div className="text-term-muted">{occQuery.isError ? t("booth.occUnavailable") : t("common.loading")}</div>
|
||||||
|
)}
|
||||||
|
</Panel>
|
||||||
|
<div className="flex min-h-0 flex-1 flex-col">
|
||||||
|
<ActiveSessions onPick={setActiveTicket} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Panel
|
||||||
|
title={t("booth.liveFeed")}
|
||||||
|
right={
|
||||||
|
<span className="text-[10px] uppercase tracking-wider text-term-muted">
|
||||||
|
{events.length}
|
||||||
|
{events.length !== scoped.length ? `/${scoped.length}` : ""} {t("booth.events")}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
className="min-h-0"
|
||||||
|
>
|
||||||
|
<div className="flex h-full flex-col">
|
||||||
|
{shiftOpen && (
|
||||||
|
<FilterBar search={feedSearch} onSearch={setFeedSearch} searchPlaceholder={t("booth.filterSearchFeed")}>
|
||||||
|
<SegGroup
|
||||||
|
value={feedType}
|
||||||
|
options={feedTypeOpts}
|
||||||
|
onChange={setFeedType}
|
||||||
|
allLabel={t("booth.filterAll")}
|
||||||
|
/>
|
||||||
|
<SegGroup value={feedDir} options={feedDirOpts} onChange={setFeedDir} allLabel={t("booth.filterAll")} />
|
||||||
|
<SegGroup value={feedSrc} options={feedSrcOpts} onChange={setFeedSrc} allLabel={t("booth.filterAll")} />
|
||||||
|
</FilterBar>
|
||||||
|
)}
|
||||||
|
<div className="min-h-0 flex-1 overflow-y-auto pr-1">
|
||||||
|
{!shiftOpen ? (
|
||||||
|
<div className="text-term-amber">{t("shift.gateTitle")}</div>
|
||||||
|
) : events.length === 0 ? (
|
||||||
|
<div className="text-term-muted">
|
||||||
|
{eventsQuery.isLoading
|
||||||
|
? t("common.loading")
|
||||||
|
: scoped.length === 0
|
||||||
|
? t("booth.noEventsYet")
|
||||||
|
: t("booth.noMatch")}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
events.map((e) => <EventRow key={e.id} e={e} onOpen={setDetailEvent} />)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
|
||||||
|
{activeTicket && <BoothPayModal identity={activeTicket} onClose={() => setActiveTicket(null)} />}
|
||||||
|
{detailEvent && <EventDetailModal e={detailEvent} onClose={() => setDetailEvent(null)} />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||