feat: subscription v2 — quantity pricing, plan timeframes (tariff bridge), reserved spots

Three subscriber enhancements driven by real scenarios (migration 0011, all
additive columns — backward-compatible).

1. QUANTITY. One subscription covers N cars (a family pays once for two). Sale
   amount = span price × quantity; maxConcurrent defaults to the quantity so all
   N cars can be inside. Quantity rides in the payment payload.

2. PLAN TIMEFRAMES → TARIFF BRIDGE. A plan may restrict WHEN a subscriber may
   park (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 (the subscriber is a transient for that time):
     - early entry: arrival → window-open, DEFERRED (signed as windowOwedMinor on
       the vehicle_entry payload), collected at exit;
     - late exit: window-close → departure, and exit is GATED
       (sub.refused.unpaidWindow) until paid at the booth.
   Pure, tz-aware outOfWindowGap in @parking/shared (12 unit tests); pricing
   reuses computeFee + the active tariff version
   (apps/server/src/subscription-window.ts). The exit refusal is a host-ONLINE
   business gate — the fail-open rule still governs the offline path.

3. RESERVED SPOTS. Site toggle reserve_subscriber_spots: occupancy holds
   max(0, quantity − itsCarsInside) per active subscription, so transients see
   "full" sooner; effectiveFree = capacity − count − reserved. Subscribers are
   never gated by full.

UI: quantity field + ×N quote (SubscriptionManager); timeframes editor
(SubscriptionPlansManager); reserve checkbox (SiteSettings); booth pay modal
shows an "OUT-OF-WINDOW" charge and takes payment to clear the exit gate.

Verified on a copy of the live DB: qty 2 = 2× price; a night-plan 19:30 entry →
30min/15,000 ALL owed, stamped + paid → gate clears, chain verifies; the reserve
toggle holds a qty-2 sub's 2 spots. Build+lint 12/12; 80 shared tests pass.

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
This commit is contained in:
2026-06-20 18:22:50 +02:00
parent fd4608a8f1
commit 53e1e7b25c
23 changed files with 929 additions and 40 deletions
@@ -0,0 +1,7 @@
-- Subscription plans v2: per-plan allowed-time windows (tariff bridge), per-subscription
-- car quantity, and a site toggle to reserve subscriber spots in the occupancy count.
-- All additive ALTER ADD COLUMN — backward-compatible (existing rows take the defaults:
-- timeframes null = 24/7, quantity 1, reserve off). SQLite ADD COLUMN is in-place.
ALTER TABLE `subscription_plans` ADD `timeframes` text;--> statement-breakpoint
ALTER TABLE `subscriptions` ADD `quantity` integer DEFAULT 1 NOT NULL;--> statement-breakpoint
ALTER TABLE `site_config` ADD `reserve_subscriber_spots` integer DEFAULT 0 NOT NULL;
+7
View File
@@ -78,6 +78,13 @@
"when": 1781885300000,
"tag": "0010_subscription_plans",
"breakpoints": true
},
{
"idx": 11,
"version": "6",
"when": 1781885400000,
"tag": "0011_subscription_plan_v2",
"breakpoints": true
}
]
}
+17 -1
View File
@@ -218,6 +218,14 @@ export const siteConfig = sqliteTable("site_config", {
* own price and may differ. null = no site default set. See
* wiki/entities/subscription.md. */
subscriptionMonthlyPriceMinor: integer("subscription_monthly_price_minor"),
/** When ON, the occupancy/full gate RESERVES a spot for each active subscriber's car
* (by quantity) even when they're not parked — so transients see "full" sooner and
* the subscriber's spot is held. When OFF (default), only cars physically inside
* count (the operator handles overflow by valet/key-juggling). Stored 0/1.
* See wiki/concepts/capacity-occupancy.md. */
reserveSubscriberSpots: integer("reserve_subscriber_spots", { mode: "boolean" })
.notNull()
.default(false),
/** IANA timezone the site operates in (e.g. "Europe/Tirane"). Used to evaluate a
* tariff's wall-clock pricing windows (happy hour / night / seasonal). COPIED into
* each published tariff version's structure.tz so the windows are frozen/immutable
@@ -295,6 +303,11 @@ export const subscriptionPlans = sqliteTable("subscription_plans", {
currency: text("currency").notNull(),
// Latest version with effectiveFrom ≤ the sale instant prices the sale.
effectiveFrom: text("effective_from").notNull(),
// Composed allowed-time windows (PlanTimeframes in @parking/shared); null = 24/7, no
// restriction. When set, a scan OUTSIDE the window is charged the transient tariff for
// the out-of-window minutes (a "night plan" subscriber arriving early owes that gap).
// Evaluated in the site timezone. See wiki/entities/subscription.md (tariff bridge).
timeframes: text("timeframes", { mode: "json" }).$type<Record<string, unknown>>(),
// Soft-retire (0) without deleting history; active=1 plans are sellable.
active: integer("active", { mode: "boolean" }).notNull().default(true),
createdBy: text("created_by"),
@@ -321,8 +334,11 @@ export const subscriptions = sqliteTable("subscriptions", {
// tariffVersionId.
planId: text("plan_id"),
planVersionId: text("plan_version_id"),
// How many cars this ONE subscription covers (e.g. a family pays once for 2 cars).
// Sale amount = plan span price × quantity; maxConcurrent defaults to it. Default 1.
quantity: integer("quantity").notNull().default(1),
// Car-count binding: how many of the subscription's cars may be inside at once.
// null = unbound. Default 1.
// null = unbound. Defaults to `quantity` at sale.
maxConcurrent: integer("max_concurrent").default(1),
validFrom: text("valid_from"),
validTo: text("valid_to"),
+95
View File
@@ -68,6 +68,29 @@ export const ADMIN_ROLE_ID = "admin";
export type SubscriptionPeriod = "day" | "week" | "month";
export const SUBSCRIPTION_PERIODS: readonly SubscriptionPeriod[] = ["day", "week", "month"];
/** A subscriber's allowed parking window for a day-type, as minutes-from-local-midnight
* (0–1439). The window is the interval [fromMin, toMin); `toMin <= fromMin` means it
* WRAPS past midnight (e.g. 20:00→08:00 = a night window: 1200..480). `allDay` = the
* whole day is allowed (no charge). An ABSENT day-window = no restriction (24/7) for
* that day-type. */
export interface DayWindow {
readonly allDay?: boolean;
readonly fromMin?: number; // window opens (minutes-of-day, local)
readonly toMin?: number; // window closes (minutes-of-day, local)
}
/** Composed allowed-time windows on a [[subscription]] plan. A scan OUTSIDE the window
* is charged the transient tariff for the out-of-window minutes (the "tariff bridge").
* null/absent timeframes on a plan = 24/7, no charge ever. Evaluated in the site tz. */
export interface PlanTimeframes {
readonly weekday?: DayWindow; // Mon–Fri
readonly weekend?: DayWindow; // Sat–Sun
/** Tolerance (minutes) around the window edges before a charge applies. */
readonly graceMin?: number;
/** IANA tz the windows are wall-clock evaluated in (the site tz, captured at sale). */
readonly tz?: string;
}
/** One immutable VERSION of a subscription plan (admin-composed catalog; latest with
* effectiveFrom ≤ sale instant prices a sale — the tariff-version pattern). The
* operator SELLS from this catalog; they never type a price. */
@@ -80,6 +103,8 @@ export interface SubscriptionPlan {
readonly currency: string;
readonly effectiveFrom: string;
readonly active: boolean;
/** Allowed-time windows (tariff bridge). null/absent = 24/7, no time charge. */
readonly timeframes?: PlanTimeframes | null;
readonly createdBy?: string | null;
readonly createdAt?: string;
}
@@ -302,6 +327,9 @@ export const REASON_CODES = [
"sub.refused.outOfWindow",
"sub.refused.noSession",
"sub.refused.atCapacity",
// a subscriber owes an out-of-window (early-entry / late-exit) transient charge and
// hasn't paid it — exit is gated until they settle (the tariff-bridge gate).
"sub.refused.unpaidWindow",
] as const;
export type ReasonCode = (typeof REASON_CODES)[number];
@@ -329,6 +357,7 @@ export const REASON_EN: Record<ReasonCode, string> = {
"sub.refused.outOfWindow": "subscription refused — {status}/out-of-window",
"sub.refused.noSession": "subscription exit with no open session (already out / never entered)",
"sub.refused.atCapacity": "subscription refused — at capacity ({inUse}/{max} cars in)",
"sub.refused.unpaidWindow": "exit refused — out-of-window charge unpaid ({amount} {currency} owed); pay at the booth",
};
/**
@@ -1042,6 +1071,72 @@ export function localBreakdown(instantMs: number, tz: string): WallClock {
};
}
// --- Subscription plan timeframes — the "tariff bridge" gap (pure, tz-aware) -------
/** Is a day-of-week a weekend (Sat/Sun)? */
function isWeekend(dow: number): boolean {
return dow === 0 || dow === 6;
}
/** Minute-of-day is inside the window [fromMin, toMin)? A window with toMin ≤ fromMin
* WRAPS past midnight (night window 20:00→08:00 ⇒ in = m ≥ 1200 OR m < 480). */
function inWindow(m: number, fromMin: number, toMin: number): boolean {
return toMin <= fromMin ? m >= fromMin || m < toMin : m >= fromMin && m < toMin;
}
/**
* The out-of-window GAP for a subscriber scan, or null when the scan is in-window (or
* the plan/day is unrestricted/all-day). This is the portion charged at the transient
* tariff (the "tariff bridge"):
* - edge "entry" (early arrival): gap = [scan, next window-OPEN] — they pay transient
* from arrival until their window starts (a 09:00 arrival to a 20:00 night window
* owes 09:00→20:00, capped by the tariff's daily cap).
* - edge "exit" (late departure): gap = [last window-CLOSE, scan] — they pay transient
* from when their window ended until they actually leave (08:00→08:45).
* Grace widens the allowed window by `graceMin` on the relevant edge. Pure + tz-aware
* (wall-clock in `timeframes.tz` or the passed `tz`). Minutes-of-day arithmetic anchored
* on the scan's own local day keeps it DST-robust for the short gaps involved.
*/
export function outOfWindowGap(
timeframes: PlanTimeframes | null | undefined,
tz: string,
atISO: string,
edge: "entry" | "exit",
): { start: string; end: string; minutes: number } | null {
if (!timeframes) return null;
const atMs = Date.parse(atISO);
if (Number.isNaN(atMs)) return null;
const zone = timeframes.tz || tz;
const wall = localBreakdown(atMs, zone);
const day: DayWindow | undefined = isWeekend(wall.dow) ? timeframes.weekend : timeframes.weekday;
// No window for this day-type, or explicitly all-day ⇒ unrestricted, no charge.
if (!day || day.allDay) return null;
if (typeof day.fromMin !== "number" || typeof day.toMin !== "number") return null;
const grace = Math.max(0, timeframes.graceMin ?? 0);
const nowMin = wall.hour * 60 + wall.minute;
if (inWindow(nowMin, day.fromMin, day.toMin)) return null; // already allowed
// Minutes (always ≥ 0) until the window OPENS, measured forward from the scan.
const minsUntil = (target: number) => ((target - nowMin) % 1440 + 1440) % 1440;
// Minutes (always ≥ 0) since the window CLOSED, measured backward from the scan.
const minsSince = (target: number) => ((nowMin - target) % 1440 + 1440) % 1440;
if (edge === "entry") {
// Early: charge from the scan until the window opens (minus grace tolerance).
let mins = minsUntil(day.fromMin) - grace;
if (mins <= 0) return null; // within grace of opening
const end = new Date(atMs + mins * 60_000).toISOString();
return { start: atISO, end, minutes: mins };
}
// Late exit: charge from when the window closed (plus grace) until the scan.
let mins = minsSince(day.toMin) - grace;
if (mins <= 0) return null; // within grace of closing
const start = new Date(atMs - mins * 60_000).toISOString();
return { start, end: atISO, minutes: mins };
}
/** "HH:MM" → minutes-of-day (0-1439). Invalid → NaN (validation rejects those). */
function hourToMin(hhmm: string): number {
const m = /^(\d{2}):(\d{2})$/.exec(hhmm);
@@ -0,0 +1,82 @@
import { describe, it, expect } from "vitest";
import { outOfWindowGap, type PlanTimeframes } from "./index.js";
// The "tariff bridge" gap for a subscriber scan outside their allowed window. UTC tz
// keeps the wall-clock arithmetic obvious in the tests. See wiki/entities/subscription.md.
// Night plan: weekday allowed 20:00→08:00 (wraps midnight); weekend all-day.
const night: PlanTimeframes = {
weekday: { fromMin: 20 * 60, toMin: 8 * 60 }, // 1200 → 480
weekend: { allDay: true },
graceMin: 0,
tz: "UTC",
};
// A weekday + a weekend (2026-06-22 is a Monday; 2026-06-20 is a Saturday).
const monday = (hhmm: string) => `2026-06-22T${hhmm}:00.000Z`;
const saturday = (hhmm: string) => `2026-06-20T${hhmm}:00.000Z`;
describe("outOfWindowGap — entry edge (early arrival)", () => {
it("19:30 arrival to a 20:00 window owes 30 min", () => {
const g = outOfWindowGap(night, "UTC", monday("19:30"), "entry");
expect(g).not.toBeNull();
expect(g!.minutes).toBe(30);
expect(g!.start).toBe(monday("19:30"));
expect(g!.end).toBe(monday("20:00"));
});
it("09:00 daytime arrival owes the whole gap to 20:00 (11h)", () => {
const g = outOfWindowGap(night, "UTC", monday("09:00"), "entry");
expect(g!.minutes).toBe(11 * 60);
expect(g!.end).toBe(monday("20:00"));
});
it("in-window arrival (22:00) owes nothing", () => {
expect(outOfWindowGap(night, "UTC", monday("22:00"), "entry")).toBeNull();
});
it("after-midnight in-window arrival (02:00) owes nothing", () => {
expect(outOfWindowGap(night, "UTC", monday("02:00"), "entry")).toBeNull();
});
});
describe("outOfWindowGap — exit edge (late departure)", () => {
it("08:45 exit after an 08:00 window close owes 45 min", () => {
const g = outOfWindowGap(night, "UTC", monday("08:45"), "exit");
expect(g!.minutes).toBe(45);
expect(g!.start).toBe(monday("08:00"));
expect(g!.end).toBe(monday("08:45"));
});
it("in-window exit (07:00) owes nothing", () => {
expect(outOfWindowGap(night, "UTC", monday("07:00"), "exit")).toBeNull();
});
});
describe("outOfWindowGap — weekend all-day", () => {
it("any Saturday scan is free (entry + exit)", () => {
expect(outOfWindowGap(night, "UTC", saturday("09:00"), "entry")).toBeNull();
expect(outOfWindowGap(night, "UTC", saturday("23:30"), "exit")).toBeNull();
});
});
describe("outOfWindowGap — grace tolerance", () => {
const withGrace: PlanTimeframes = { ...night, graceMin: 15 };
it("19:50 entry (10 min before open) is within a 15-min grace → no charge", () => {
expect(outOfWindowGap(withGrace, "UTC", monday("19:50"), "entry")).toBeNull();
});
it("19:30 entry (30 min before) still charged, minus 15 grace = 15 min", () => {
const g = outOfWindowGap(withGrace, "UTC", monday("19:30"), "entry");
expect(g!.minutes).toBe(15);
});
it("08:10 exit within a 15-min grace of the 08:00 close → no charge", () => {
expect(outOfWindowGap(withGrace, "UTC", monday("08:10"), "exit")).toBeNull();
});
});
describe("outOfWindowGap — unrestricted", () => {
it("null timeframes → never a charge", () => {
expect(outOfWindowGap(null, "UTC", monday("09:00"), "entry")).toBeNull();
});
it("a day-type with no window → no charge", () => {
const weekdayOnly: PlanTimeframes = { weekday: { fromMin: 1200, toMin: 480 }, tz: "UTC" };
// weekend absent ⇒ unrestricted on Saturday.
expect(outOfWindowGap(weekdayOnly, "UTC", saturday("09:00"), "entry")).toBeNull();
});
});