feat(modules): venue-module registry — entitled ∩ activated, requireModule, Setup panel

Groundwork for the Car Wash pilot (wiki/decisions/venue-modules.md, build-order
steps 1 + 3). No Car Wash code yet; validation is the first module behind the
seam, unchanged in behaviour.

- @parking/shared: MODULE_IDS, ModuleManifest, MODULES (parking required;
  validation dependsOn parking), parseEntitledModules / resolveModuleActivation
  / effectiveModules as pure functions.
- DB: site_config.modules_json (migration 0026, hand-written + journal;
  additive, nullable = everything entitled).
- Server: modules.ts (entitledModules from MODULES_ENTITLED env, activated
  from site_config, effective set, requireModule preHandler → 403
  module_disabled); modules/index.ts registers folder-based modules by
  iterating the registry (modules/validation); site-config GET exposes
  modules/modulesEntitled/modulesActivated, PUT takes the full desired set,
  enforces entitlement + dependency rules (400 with reason) and signs one
  config_change per module that actually flips; /api/auth/me carries the
  effective set; validation routes guarded requireModule → requirePermission.
- Web: lib/modules.ts + modules/{index,validation}; router.tsx spreads
  WEB_MODULES into nav + route tree (validate route no longer named there);
  Setup → Site "Modules" panel (required shown disabled, dependencies as
  hints, server refusal shown verbatim); validation sections + programs fetch
  gated on the module; App invalidates the router whenever the session
  changes (route-context consumers only re-read on navigation — the nav was
  stale after a flip, and after every other setUser too).
- Lavazh validation station retired (STATIONS = ["bar"]; rows untouched).
- Deploy: MODULES_ENTITLED=parking,validation explicit in both booth stacks;
  documented in .env.example.
- Tests: modules.test.ts (7); suite 329/329; web build clean; Playwright
  round-trip on /setup/site verified live.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
This commit is contained in:
2026-09-05 11:04:39 +02:00
parent db9c3e0e31
commit 23d6379be8
27 changed files with 848 additions and 57 deletions
+8
View File
@@ -41,6 +41,14 @@ export function App() {
});
}, []);
// Route-context consumers (RootLayout's nav, route beforeLoad guards) only re-read
// the router context on navigation — NOT when this `user` state changes. So after
// any session refresh (login, profile edit, a venue-module flip in Setup → Site)
// re-validate the current matches once React has committed the new context.
useEffect(() => {
if (user) void router.invalidate();
}, [user]);
// Apply the signed-in user's preferred language + theme + font scale whenever they
// resolve/change (login, bootstrap, or a toggle). Albanian + dark + 100% are the defaults
// before auth resolves; on logout, fall back so the Login screen is consistent.
+89 -17
View File
@@ -1,6 +1,8 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useRouteContext } from "@tanstack/react-router";
import {
fetchMe,
fetchOccupancy,
fetchSiteConfig,
fetchValidationPrograms,
@@ -10,7 +12,9 @@ import {
type SiteConfig,
type ValidationProgramView,
} from "./api.js";
import { STATIONS, ValidationStationsPanel, defaultProgram, type StationId } from "./ValidationSetup.js";
import { STATIONS, ValidationStationsPanel, defaultProgram, stationLabelKey, type StationId } from "./ValidationSetup.js";
import { MODULES, type ModuleId } from "@parking/shared";
import type { RouterContext } from "./router.js";
// Live occupancy + capacity + park metadata. Occupancy is shown to everyone (it's a
// fold over the signed ledger); capacity and the metadata fields are admin-editable.
@@ -42,23 +46,43 @@ export function SiteSettings({ canEdit }: { canEdit: boolean }) {
// station's `active` (persisted at once — each flip signs a config_change); the
// right-column panel edits the enabled stations. See validation-discounts.md.
const [programs, setPrograms] = useState<ValidationProgramView[]>([]);
// Venue modules: what this site is entitled to (vendor-set), what the admin has
// activated, and the effective set. Toggling persists at once (the server signs a
// config_change per module that flips and validates dependencies). See
// wiki/decisions/venue-modules.md.
const [mods, setMods] = useState<{ entitled: ModuleId[]; activated: ModuleId[]; effective: ModuleId[] } | null>(null);
const [modMsg, setModMsg] = useState<string | null>(null);
const moduleOn = (id: ModuleId) => mods?.effective.includes(id) ?? false;
// The header nav gates module entries on the SESSION's module set (/api/auth/me),
// so a flip here must refresh the session too or the nav stays stale until reload
// (App re-validates the router whenever `user` changes).
const { setUser } = useRouteContext({ strict: false }) as RouterContext;
function reload() {
fetchOccupancy().then(setOcc).catch(() => {});
}
/** The validation programs are a module route — only ask for them while the
* module is effective (the server 403s otherwise, which would land in app_logs
* as a failed request every time an admin opens this page). */
function loadPrograms(effective: ModuleId[]) {
if (!canEdit || !effective.includes("validation")) {
setPrograms([]);
return;
}
fetchValidationPrograms()
.then((r) => setPrograms(r.programs))
.catch(() => {});
}
useEffect(() => {
reload();
if (canEdit) {
fetchValidationPrograms()
.then((r) => setPrograms(r.programs))
.catch(() => {});
}
fetchSiteConfig()
.then((c) => {
setCapInput(c.capacity == null ? "" : String(c.capacity));
setExitVoucherDefault(c.exitVoucherDefault);
setReserveSubs(c.reserveSubscriberSpots);
setAnprEntry(c.anprEntryEnabled);
setMods({ entitled: c.modulesEntitled, activated: c.modulesActivated, effective: c.modules });
loadPrograms(c.modules);
const m: Record<string, string> = {};
for (const { key } of META_FIELDS) m[key] = c[key] == null ? "" : String(c[key]);
setMeta(m);
@@ -73,7 +97,7 @@ export function SiteSettings({ canEdit }: { canEdit: boolean }) {
const existing = programs.find((p) => p.id === id);
const body = existing
? { ...existing, active }
: { ...defaultProgram(id, t(id === "bar" ? "val.enableBar" : "val.enableLavazh")), active };
: { ...defaultProgram(id, t(stationLabelKey(id))), active };
try {
const saved = await saveValidationProgram(id, body);
setPrograms((ps) => [...ps.filter((p) => p.id !== id), saved]);
@@ -82,6 +106,23 @@ export function SiteSettings({ canEdit }: { canEdit: boolean }) {
}
}
/** Flip a module: send the full desired activation set; the server decides
* (required always on, must be entitled, dependencies) and echoes the result. */
async function toggleModule(id: ModuleId, on: boolean) {
if (!mods) return;
setModMsg(null);
const next = on ? [...new Set([...mods.activated, id])] : mods.activated.filter((m) => m !== id);
try {
const c = await saveSiteConfig({ modules: next });
setMods({ entitled: c.modulesEntitled, activated: c.modulesActivated, effective: c.modules });
loadPrograms(c.modules);
const me = await fetchMe();
if (me) setUser(me);
} catch (e) {
setModMsg((e as Error).message);
}
}
async function save() {
setMsg(null);
const raw = capInput.trim();
@@ -164,22 +205,53 @@ export function SiteSettings({ canEdit }: { canEdit: boolean }) {
</span>
</label>
<div className="border-t border-term-border pt-3 text-[0.6875rem] uppercase tracking-wider text-term-muted">
{t("val.sectionTitle")}
{t("modules.sectionTitle")}
</div>
<span className="hint -mt-2">{t("val.sectionHint")}</span>
<div className="flex gap-6">
{STATIONS.map((id) => (
<label key={id} className="flex items-center gap-2 text-[0.75rem] text-term-text">
<span className="hint -mt-2">{t("modules.sectionHint")}</span>
<div className="grid gap-1.5">
{MODULES.filter((m) => mods?.entitled.includes(m.id)).map((m) => (
<label key={m.id} className="flex items-start gap-2 text-[0.75rem] text-term-text">
<input
type="checkbox"
className="accent-term-amber"
checked={programs.find((p) => p.id === id)?.active ?? false}
onChange={(e) => toggleStation(id, e.target.checked)}
className="mt-0.5 accent-term-amber"
checked={moduleOn(m.id)}
disabled={m.required || !mods}
onChange={(e) => toggleModule(m.id, e.target.checked)}
/>
{t(id === "bar" ? "val.enableBar" : "val.enableLavazh")}
<span>
{t(`modules.name.${m.id}`)}
{m.required && <span className="hint block">{t("modules.required")}</span>}
{m.dependsOn.length > 0 && (
<span className="hint block">
{t("modules.requires", { deps: m.dependsOn.map((d) => t(`modules.name.${d}`)).join(", ") })}
</span>
)}
</span>
</label>
))}
{modMsg && <span className="text-[0.75rem] text-term-red">{modMsg}</span>}
</div>
{moduleOn("validation") && (
<>
<div className="border-t border-term-border pt-3 text-[0.6875rem] uppercase tracking-wider text-term-muted">
{t("val.sectionTitle")}
</div>
<span className="hint -mt-2">{t("val.sectionHint")}</span>
<div className="flex gap-6">
{STATIONS.map((id) => (
<label key={id} className="flex items-center gap-2 text-[0.75rem] text-term-text">
<input
type="checkbox"
className="accent-term-amber"
checked={programs.find((p) => p.id === id)?.active ?? false}
onChange={(e) => toggleStation(id, e.target.checked)}
/>
{t(stationLabelKey(id))}
</label>
))}
</div>
</>
)}
<div className="border-t border-term-border pt-3 text-[0.6875rem] uppercase tracking-wider text-term-muted">
{t("site.parkDetails")}
</div>
@@ -211,7 +283,7 @@ export function SiteSettings({ canEdit }: { canEdit: boolean }) {
</div>
)}
</section>
{canEdit && (
{canEdit && moduleOn("validation") && (
<ValidationStationsPanel
programs={programs}
onSaved={(p) => setPrograms((ps) => [...ps.filter((x) => x.id !== p.id), p])}
+13 -3
View File
@@ -15,10 +15,20 @@ import {
// fixed stations. Amounts are entered in MAJOR units and stored in integer minor
// units (the tariff-composer convention). See wiki/concepts/validation-discounts.md.
/** The two well-known stations the checkboxes toggle. */
export const STATIONS = ["bar", "lavazh"] as const;
/** The well-known merchant stations the checkboxes toggle. Was `["bar", "lavazh"]`;
* the Lavazh (car-wash) station was retired 2026-09-05 — the Car Wash module
* sponsors parking through its own order flow instead (wiki/decisions/
* venue-modules.md). Existing `lavazh` program rows are untouched data; the server
* accepts any kebab slug, so they simply no longer have a checkbox. */
export const STATIONS = ["bar"] as const;
export type StationId = (typeof STATIONS)[number];
/** i18n label for a station's checkbox / tab. */
const STATION_LABEL_KEY: Record<StationId, string> = { bar: "val.enableBar" };
export function stationLabelKey(id: StationId): string {
return STATION_LABEL_KEY[id];
}
/** A blank program draft for a station enabled for the first time. */
export function defaultProgram(id: StationId, label: string): Omit<ValidationProgramView, "id"> {
return {
@@ -220,7 +230,7 @@ export function ValidationStationsPanel({
className={`btn btn-sm ${p.id === current.id ? "btn-primary" : "btn-ghost"}`}
onClick={() => setTab(p.id)}
>
{t(p.id === "bar" ? "val.enableBar" : "val.enableLavazh")}
{t(stationLabelKey(p.id as StationId))}
</button>
))}
</div>
+10 -1
View File
@@ -16,7 +16,7 @@ import { getDesktopCsrfToken, setDesktopCsrfToken } from "./lib/desktop-csrf.js"
import { logFailedRequest } from "./lib/logger.js";
import { apiUrl, platformFetch } from "./lib/origin.js";
import { inTauri } from "./lib/tauri-env.js";
import type { AppLogRecord, ValidationLine, ValidationMode } from "@parking/shared";
import type { AppLogRecord, ModuleId, ValidationLine, ValidationMode } from "@parking/shared";
const CSRF_COOKIE = "parking_csrf";
const CSRF_HEADER = "X-CSRF-Token";
@@ -98,6 +98,9 @@ export interface SessionUser {
fullName: string | null;
/** Optional contact email (profile metadata); null if unset. */
email: string | null;
/** Effective venue modules at this site (entitled ∩ activated) — what the SPA may
* SHOW; the server enforces. See lib/modules.ts. */
modules: ModuleId[];
/** Desktop-only: the CSRF token also echoed via the (JS-unreadable, on
* desktop) parking_csrf cookie — see the file header. Absent/unused in the
* browser build, which reads the cookie directly instead. */
@@ -1257,6 +1260,12 @@ export interface SiteConfig {
bypassPresenceRadar: boolean;
/** Entry presence-gate bypass: drop camera detection as an entry-button requirement. */
bypassPresenceCamera: boolean;
/** Effective venue modules (entitled ∩ activated). */
modules: ModuleId[];
/** What this deployment is entitled to (vendor-set) — the toggles offered in Setup. */
modulesEntitled: ModuleId[];
/** What the site admin has activated. Send the full desired set via saveSiteConfig. */
modulesActivated: ModuleId[];
parkName: string | null;
operatorName: string | null;
/** NIUS — Albanian tax/identification number. */
+11 -2
View File
@@ -56,6 +56,16 @@ export const en: Catalog = {
changeServer: "Change server",
changeServerConfirm: "This signs you out and asks for a new server address on next launch. Continue?",
},
modules: {
sectionTitle: "Modules",
sectionHint: "Optional parts of the system this site uses. What can be switched on here is decided at deployment; switching one off hides it and refuses its actions — nothing is deleted.",
required: "Always on.",
requires: "Requires: {{deps}}",
name: {
parking: "Parking",
validation: "Merchant validations (Bar)",
},
},
update: {
available: "Update available",
prompt: "Version {{version}} is available. Install now and restart? (Installing requires the administrator password.)",
@@ -756,9 +766,8 @@ export const en: Catalog = {
val: {
// /setup/site
sectionTitle: "Merchant validations",
sectionHint: "An in-park merchant (bar / car-wash) scans the customer's ticket and grants a parking discount — payment and the receipt always stay at the booth.",
sectionHint: "An in-park merchant (the bar) scans the customer's ticket and grants a parking discount — payment and the receipt always stay at the booth.",
enableBar: "Bar",
enableLavazh: "Car wash",
labelName: "Receipt label",
labelNamePh: "e.g. Car wash — first hour free",
mode: "Discount type",
+11 -2
View File
@@ -59,6 +59,16 @@ export const sq = {
changeServer: "Ndrysho serverin",
changeServerConfirm: "Kjo do t'ju dalë nga sesioni dhe do kërkojë adresë të re serveri në hapjen tjetër. Vazhdo?",
},
modules: {
sectionTitle: "Modulet",
sectionHint: "Pjesët opsionale të sistemit që përdor ky park. Çfarë mund të aktivizohet këtu vendoset gjatë instalimit; çaktivizimi e fsheh modulin dhe refuzon veprimet e tij — asgjë nuk fshihet.",
required: "Gjithmonë aktiv.",
requires: "Kërkon: {{deps}}",
name: {
parking: "Parkimi",
validation: "Validime tregtare (Bar)",
},
},
update: {
available: "Përditësim i disponueshëm",
prompt: "Versioni {{version}} është i disponueshëm. Ta instaloj tani dhe ta rinis? (Instalimi kërkon fjalëkalimin e administratorit.)",
@@ -769,9 +779,8 @@ export const sq = {
val: {
// /setup/site
sectionTitle: "Validime tregtare",
sectionHint: "Shërbime të tjera brenda parkut (bar / lavazh) skanojnë biletën e hyrjes dhe bëjnë zbritje — pagesa dhe fatura bëhen në kabinë.",
sectionHint: "Bari brenda parkut skanon biletën e hyrjes dhe bën zbritje — pagesa dhe fatura bëhen në kabinë.",
enableBar: "Bar",
enableLavazh: "Lavazh",
labelName: "Etiketa në faturë",
labelNamePh: "p.sh. Lavazh — 1 orë falas",
mode: "Lloji i zbritjes",
+37
View File
@@ -0,0 +1,37 @@
import type { AnyRoute } from "@tanstack/react-router";
import type { ModuleId } from "@parking/shared";
import type { Permission, SessionUser } from "../api.js";
import type { rootRoute } from "../router.js";
/** The app's root route (type only — a runtime import here would be a cycle). */
export type RootRoute = typeof rootRoute;
// Venue modules — the web side. The server ENFORCES the effective set
// (requireModule); this file only decides what to SHOW. A module's nav entries and
// routes live in its own folder (apps/web/src/modules/<id>/index.tsx) and are
// discovered through WEB_MODULES below, so router.tsx never names a module's screens.
// See wiki/decisions/venue-modules.md.
/** Is the module effective for this session? `modules` comes from /api/auth/me
* (entitled ∩ activated); a server too old to send it hides every module rather
* than showing something it would 403 — fail closed on the display side too. */
export function moduleOn(user: SessionUser | null, id: ModuleId): boolean {
return !!user && Array.isArray(user.modules) && user.modules.includes(id);
}
export interface WebModuleNav {
to: string;
/** i18n key for the header label. */
labelKey: string;
/** Shown only if the role holds this permission (and the module is on). */
perm: Permission;
}
export interface WebModule {
id: ModuleId;
/** Header nav entries, in display order. */
nav: readonly WebModuleNav[];
/** Build this module's routes under the given root. Called once at router
* assembly; each route's own beforeLoad must gate on moduleOn + permission. */
routes(root: RootRoute): AnyRoute[];
}
+9
View File
@@ -0,0 +1,9 @@
import type { WebModule } from "../lib/modules.js";
import { validationModule } from "./validation/index.js";
// The web-side module registry, in display order. Adding a module = its folder here
// + one entry below (+ the manifest in @parking/shared). router.tsx spreads these
// into the nav and the route tree and never names a module's screens itself.
// `parking` has no folder yet — its screens are still declared directly in
// router.tsx; they move behind this seam subsystem by subsystem.
export const WEB_MODULES: readonly WebModule[] = [validationModule];
+34
View File
@@ -0,0 +1,34 @@
import { createRoute, redirect, useRouteContext } from "@tanstack/react-router";
import { can } from "../../api.js";
import { moduleOn, type RootRoute, type WebModule } from "../../lib/modules.js";
import type { RouterContext } from "../../router.js";
import { ValidateScreen } from "../../ValidateScreen.js";
// Merchant-scan ticket validation as a venue module (kept for the Bar —
// wiki/decisions/venue-modules.md, decision 1). The merchant (bar) scan-and-validate
// screen is usually the ONLY page a merchant user's role can reach. The server
// enforces module-on + the program↔user binding on apply; the gates here are
// defence in depth / display. See wiki/concepts/validation-discounts.md.
export const validationModule: WebModule = {
id: "validation",
nav: [{ to: "/validate", labelKey: "nav.validate", perm: "validation:create" }],
routes(root: RootRoute) {
const validateRoute = createRoute({
getParentRoute: () => root,
path: "/validate",
beforeLoad: ({ context }) => {
const ctx = context as RouterContext;
if (!moduleOn(ctx.user, "validation") || !can(ctx.user, "validation:create")) {
throw redirect({ to: "/booth" });
}
},
component: function ValidateRoute() {
const { user } = useRouteContext({ strict: false }) as RouterContext;
if (!user) return null;
return <ValidateScreen user={user} />;
},
});
return [validateRoute];
},
};
+20 -21
View File
@@ -48,7 +48,8 @@ import { DrawerManager } from "./DrawerManager.js";
import { CARD_PAYMENTS_ENABLED } from "./lib/features.js";
import { LogsViewer } from "./LogsViewer.js";
import { BackupSettings } from "./BackupSettings.js";
import { ValidateScreen } from "./ValidateScreen.js";
import { WEB_MODULES } from "./modules/index.js";
import { moduleOn } from "./lib/modules.js";
import { RecycleBin } from "./RecycleBin.js";
import { Profile } from "./Profile.js";
// Reports pulls in Recharts (~heavy) — lazy-loaded so it stays OUT of the booth's
@@ -555,9 +556,14 @@ function RootLayout() {
<nav className="flex items-center gap-1">
{show("session:read") && <NavLink to="/booth" label={t("nav.booth")} />}
{show("shift:read") && <NavLink to="/shifts" label={t("nav.shifts")} />}
{/* The merchant's (bar/lavazh) scan-and-validate screen. Their typical role
grants ONLY validation:create, so this is often their whole nav. */}
{show("validation:create") && <NavLink to="/validate" label={t("nav.validate")} />}
{/* Venue-module nav entries (e.g. the Bar merchant's scan-and-validate screen,
often that role's whole nav): shown iff the module is effective at this
site AND the role holds the entry's permission. See lib/modules.ts. */}
{WEB_MODULES.flatMap((m) =>
m.nav
.filter((n) => moduleOn(user, m.id) && show(n.perm))
.map((n) => <NavLink key={n.to} to={n.to} label={t(n.labelKey)} />),
)}
{/* Drawer — record cash movements (operator) / review them (admin). Shown if the
user can do either. See wiki/concepts/shift.md. */}
{(show("drawer:create") || show("drawer:review")) && (
@@ -625,8 +631,13 @@ const indexRoute = createRoute({
path: "/",
beforeLoad: ({ context }) => {
// A merchant-only user (validation:create without the booth's session:read)
// lands on their scan-and-validate screen; everyone else on the booth.
if (can(context.user, "validation:create") && !can(context.user, "session:read")) {
// lands on their scan-and-validate screen — if the validation module is on at
// this site; everyone else on the booth.
if (
moduleOn(context.user, "validation") &&
can(context.user, "validation:create") &&
!can(context.user, "session:read")
) {
throw redirect({ to: "/validate" });
}
throw redirect({ to: "/booth" });
@@ -639,20 +650,6 @@ const boothRoute = createRoute({
component: BoothScreen,
});
// The merchant (bar/lavazh) scan-and-validate screen — usually the ONLY page a
// merchant user's role can reach. The server enforces the program↔user binding on
// apply; this gate is defence in depth. See wiki/concepts/validation-discounts.md.
const validateRoute = createRoute({
getParentRoute: () => rootRoute,
path: "/validate",
beforeLoad: ({ context }) => requirePerm("validation:create")(context),
component: function ValidateRoute() {
const { user } = rootRoute.useRouteContext();
if (!user) return null;
return <ValidateScreen user={user} />;
},
});
// Back-compat redirects for paths that moved. Most config screens live under /setup;
// Subscriptions/Plans/Tariff-Lab were promoted OUT of /setup into the standalone
// /subscriptions section (2026-06-21) — redirect the old /setup/* paths too so existing
@@ -898,7 +895,9 @@ const profileRoute = createRoute({
const routeTree = rootRoute.addChildren([
indexRoute,
boothRoute,
validateRoute,
// Venue-module routes (e.g. /validate) — each module gates its own routes on
// moduleOn + permission. See modules/index.ts.
...WEB_MODULES.flatMap((m) => m.routes(rootRoute)),
...legacyRedirects,
profileRoute,
shiftRoute,