feat: subscription plan catalog — config-defined pricing, dated spans, no typed amounts

Re-model subscription pricing from per-row, operator-typed prices into an
admin-composed, versioned PLAN CATALOG (the tariff pattern). The operator now
SELLS by picking a plan over a date span; the price is LOOKED UP, never typed —
removing the fat-finger risk on a money field — and day/week/month periods make
the hotel "guest stays 1–N days" case a daily plan over a check-in→check-out span.

- Schema/migration 0010: new `subscription_plans` (immutable, effective-dated,
  keyed by a stable planId; period day/week/month + per-period price + active
  flag). `subscriptions` gains planId/planVersionId; period enum widened. Seeds a
  "Monthly" plan from the existing site default price (no data loss).
- Pricing (pure, unit-tested in @parking/shared): periods = ceil(span / period),
  amount = periods × per-period price. Ceil = any started period is full (hotel
  practice). `resolvePlanVersion` picks the latest active version ≤ sale instant.
- Backend: new admin-only plan CRUD (`subscription:plan` permission); reworked
  sell path derives the amount from the plan; `POST /api/subscriptions/quote`
  returns a server-computed quote so the operator can't override it. The
  signed-payment sale fix is unchanged — only the amount SOURCE moved; payload
  now carries planId/planVersionId/periods. Updates never re-sell (price frozen).
- Frontend: SubscriptionManager sell form swaps the price field for a plan
  picker + start/end dates + a live quote line. New SubscriptionPlansManager
  (Setup tab) for the admin catalog. i18n (sq+en) for both.

Verified on a copy of the live DB: 0010 applies (existing subs intact), a
3-night hotel sale prices to 2,400 ALL, appends one signed payment with
planVersionId, chain verifies. Build+lint 12/12; 68 shared tests pass.

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
This commit is contained in:
2026-06-20 17:13:42 +02:00
parent 052da8c3a7
commit fd4608a8f1
19 changed files with 1022 additions and 223 deletions
+124 -93
View File
@@ -7,37 +7,37 @@ import {
createSubscription,
deleteSubscription,
fetchReaders,
fetchSiteConfig,
fetchSubscriptionPlans,
fetchSubscriptions,
pollCapture,
printSubscription,
quoteSubscription,
revokeSubscription,
updateSubscription,
type ReaderInfo,
type Subscription,
type SubscriptionCredential,
type SubscriptionInput,
type SubscriptionPlan,
type SubscriptionQuote,
} from "./api.js";
import { Modal } from "./ui/Modal.js";
// Subscription admin. Create/edit/revoke/delete subscriptions + their credentials
// (card/QR) and bound plates, and the recurring monthly price (e.g. 10,000 ALL). A
// subscription is mutable master data; every USE of it is a signed ledger event
// elsewhere. See wiki/entities/subscription.md.
const DEFAULT_CURRENCY = "ALL";
// (card/QR) and bound plates. A SALE is priced by selecting an admin-defined PLAN over
// a date span — the operator never types a price (the amount is looked up: ceil(periods)
// × per-period price). A subscription is mutable master data; every USE of it is a
// signed ledger event elsewhere. See wiki/entities/subscription.md.
interface FormState {
holderName: string;
contact: string;
priceMajor: string; // major units as typed (e.g. "10000"); "" = no price
currency: string;
planId: string; // selected plan (sells/prices it); "" = comp (no charge)
tender: "cash" | "card"; // how the sale fee is collected (cash → drawer, card → bank)
carBound: boolean; // false = unbound (maxConcurrent null)
maxConcurrent: string;
validFrom: string;
months: string; // months paid for; "" = none (use explicit validTo / open-ended)
validTo: string;
validFrom: string; // span start (date)
validTo: string; // span end (date) — required when a plan is selected
credentials: SubscriptionCredential[];
platesText: string; // comma/space separated
}
@@ -47,17 +47,15 @@ function todayISODate(): string {
return new Date().toISOString().slice(0, 10);
}
function emptyForm(defaultPriceMajor = "", currency = DEFAULT_CURRENCY): FormState {
function emptyForm(): FormState {
return {
holderName: "",
contact: "",
priceMajor: defaultPriceMajor,
currency,
planId: "",
tender: "cash",
carBound: true,
maxConcurrent: "1",
validFrom: todayISODate(),
months: "1",
validTo: "",
credentials: [{ kind: "qr", value: "" }],
platesText: "",
@@ -67,51 +65,42 @@ function formFrom(s: Subscription): FormState {
return {
holderName: s.holderName ?? "",
contact: s.contact ?? "",
priceMajor: s.priceMinor != null ? String(s.priceMinor / 100) : "",
currency: s.currency ?? DEFAULT_CURRENCY,
planId: s.planId ?? "", // edit doesn't re-sell; plan shown read-only
tender: "cash", // edit doesn't re-collect money; tender only matters on a new sale
carBound: s.maxConcurrent != null,
maxConcurrent: s.maxConcurrent != null ? String(s.maxConcurrent) : "1",
validFrom: s.validFrom ?? "",
months: "", // on edit, default to leaving the window as-is (explicit validTo below)
validTo: s.validTo ?? "",
validFrom: (s.validFrom ?? "").slice(0, 10),
validTo: (s.validTo ?? "").slice(0, 10),
credentials: s.credentials.length ? s.credentials : [{ kind: "qr", value: "" }],
platesText: s.plates.join(", "),
};
}
/** Add whole months to a yyyy-mm-dd (clamps day overflow), → yyyy-mm-dd. Mirrors the
* server's addMonths so the form can preview the coverage end. */
function addMonthsDate(date: string, months: number): string | null {
const d = new Date(`${date}T00:00:00Z`);
if (Number.isNaN(d.getTime())) return null;
const day = d.getUTCDate();
d.setUTCMonth(d.getUTCMonth() + months);
if (d.getUTCDate() < day) d.setUTCDate(0);
return d.toISOString().slice(0, 10);
}
const STATUS_KEY: Record<Subscription["status"], string> = {
active: "subs.statusActive",
suspended: "subs.statusSuspended",
revoked: "subs.statusRevoked",
};
function toInput(f: FormState): SubscriptionInput {
const major = Number(f.priceMajor);
const priceSet = f.priceMajor.trim() !== "" && Number.isFinite(major) && major >= 0;
const monthsNum = f.months.trim() === "" ? null : Math.max(1, Math.round(Number(f.months) || 0));
/** A yyyy-mm-dd date → an ISO instant (UTC midnight) for the span endpoints. */
function dateToISO(d: string): string | null {
if (!d.trim()) return null;
const t = Date.parse(`${d}T00:00:00Z`);
return Number.isNaN(t) ? null : new Date(t).toISOString();
}
function toInput(f: FormState, isNew: boolean): SubscriptionInput {
const planSelected = isNew && f.planId.trim() !== "";
return {
holderName: f.holderName.trim() || null,
contact: f.contact.trim() || null,
priceMinor: priceSet ? Math.round(major * 100) : null,
period: "monthly",
currency: priceSet ? f.currency.trim() || DEFAULT_CURRENCY : null,
// A SALE: send the chosen plan; price is looked up server-side. On edit we never
// re-sell, so no planId is sent (price/plan stay frozen).
planId: planSelected ? f.planId.trim() : null,
tender: f.tender,
maxConcurrent: f.carBound ? Math.max(1, Math.round(Number(f.maxConcurrent) || 1)) : null,
validFrom: f.validFrom.trim() || null,
// months (with validFrom) drives validTo server-side; else send the explicit end.
months: monthsNum && f.validFrom.trim() ? monthsNum : null,
validTo: f.validTo.trim() || null,
validFrom: dateToISO(f.validFrom),
validTo: dateToISO(f.validTo),
// A QR credential with a blank value is sent as { kind:'qr' } (no value) so the
// server auto-generates the code. RF (and pre-existing QR) keep their value.
credentials: f.credentials
@@ -121,15 +110,23 @@ function toInput(f: FormState): SubscriptionInput {
};
}
const PERIOD_KEY: Record<SubscriptionPlan["period"], string> = {
day: "subs.perDay",
week: "subs.perWeek",
month: "subs.perMonth",
};
function priceLabel(s: Subscription, t: (k: string) => string): string {
if (s.priceMinor == null) return t("subs.noPrice");
return `${(s.priceMinor / 100).toLocaleString()} ${s.currency ?? ""} / ${t("subs.perMonth")}`.trim();
return `${(s.priceMinor / 100).toLocaleString()} ${s.currency ?? ""}`.trim();
}
export function SubscriptionManager() {
const { t } = useTranslation();
const [subs, setSubs] = useState<Subscription[] | null>(null);
const [defaultPriceMajor, setDefaultPriceMajor] = useState("");
const [plans, setPlans] = useState<SubscriptionPlan[]>([]);
const [quote, setQuote] = useState<SubscriptionQuote | null>(null);
const [quoting, setQuoting] = useState(false);
const [editing, setEditing] = useState<string | "new" | null>(null);
const [form, setForm] = useState<FormState>(() => emptyForm());
const [msg, setMsg] = useState<{ kind: "ok" | "err"; text: string } | null>(null);
@@ -146,18 +143,45 @@ export function SubscriptionManager() {
}
useEffect(() => {
reload();
// Pull the site default monthly price to pre-fill new subscriptions.
fetchSiteConfig()
.then((c) => {
if (c.subscriptionMonthlyPriceMinor != null) setDefaultPriceMajor(String(c.subscriptionMonthlyPriceMinor / 100));
})
// Load the sellable plan catalog (the operator picks one instead of typing a price).
fetchSubscriptionPlans()
.then((r) => setPlans(r.plans))
.catch(() => {
/* non-fatal — the form just won't pre-fill */
/* non-fatal — the form will show "no plans" */
});
}, []);
// Live server-computed quote for the sell form: ceil(periods) × per-period price.
// Debounced; re-runs when the plan or the span changes. The operator can't override
// the amount — it's whatever the server returns.
useEffect(() => {
if (editing !== "new" || !form.planId.trim() || !form.validTo.trim() || !form.validFrom.trim()) {
setQuote(null);
return;
}
const from = dateToISO(form.validFrom);
const to = dateToISO(form.validTo);
if (!from || !to || Date.parse(to) <= Date.parse(from)) {
setQuote(null);
return;
}
let cancelled = false;
setQuoting(true);
const h = setTimeout(() => {
quoteSubscription({ planId: form.planId.trim(), validFrom: from, validTo: to })
.then((q) => !cancelled && setQuote(q))
.catch(() => !cancelled && setQuote(null))
.finally(() => !cancelled && setQuoting(false));
}, 200);
return () => {
cancelled = true;
clearTimeout(h);
};
}, [editing, form.planId, form.validFrom, form.validTo]);
function startNew() {
setForm(emptyForm(defaultPriceMajor));
setForm(emptyForm());
setQuote(null);
setEditing("new");
setMsg(null);
}
@@ -171,7 +195,7 @@ export function SubscriptionManager() {
setMsg(null);
try {
if (editing === "new") {
const created = await createSubscription(toInput(form));
const created = await createSubscription(toInput(form, true));
setEditing(null);
reload();
// The recorded SALE (signed payment) — confirm the amount taken so the operator
@@ -197,7 +221,7 @@ export function SubscriptionManager() {
}
return;
}
if (editing) await updateSubscription(editing, toInput(form));
if (editing) await updateSubscription(editing, toInput(form, false));
setEditing(null);
reload();
setMsg({ kind: "ok", text: t("subs.saved") });
@@ -286,19 +310,6 @@ export function SubscriptionManager() {
// Stop polling if the form closes or the component unmounts.
useEffect(() => clearPoll, []);
// Live coverage preview: when months + validFrom are set, show the end date and
// (if priced) the N×monthly total the operator should collect.
const monthsN = form.months.trim() === "" ? 0 : Math.max(0, Math.round(Number(form.months) || 0));
const coverageEnd = monthsN >= 1 && form.validFrom.trim() ? addMonthsDate(form.validFrom.trim(), monthsN) : null;
const priceMajorN = form.priceMajor.trim() === "" ? null : Number(form.priceMajor);
const totalDue =
coverageEnd && priceMajorN != null && Number.isFinite(priceMajorN)
? `${(priceMajorN * monthsN).toLocaleString()} ${form.currency.trim() || DEFAULT_CURRENCY}`
: null;
const coverageHint = coverageEnd
? t("subs.coverageHint", { end: coverageEnd }) + (totalDue ? ` · ${t("subs.totalDue", { total: totalDue })}` : "")
: null;
if (!subs) return null;
return (
@@ -340,21 +351,36 @@ export function SubscriptionManager() {
<input className="input" value={form.holderName} onChange={(e) => setForm((f) => ({ ...f, holderName: e.target.value }))} />
<label className="label">{t("subs.contact")}</label>
<input className="input" value={form.contact} onChange={(e) => setForm((f) => ({ ...f, contact: e.target.value }))} />
<label className="label">{t("subs.monthlyPrice")}</label>
<span className="flex items-center gap-2">
<input
className="input w-28"
value={form.priceMajor}
onChange={(e) => setForm((f) => ({ ...f, priceMajor: e.target.value }))}
inputMode="decimal"
placeholder={t("subs.pricePlaceholder")}
/>
<input className="input w-16" value={form.currency} onChange={(e) => setForm((f) => ({ ...f, currency: e.target.value }))} />
<span className="text-[12px] text-term-muted">/ {t("subs.perMonth")}</span>
</span>
{/* Tender — only relevant when there's a price to collect (a SALE). The sale
appends a signed payment so the money shows in the feed/drawer/Z-report. */}
{form.priceMajor.trim() !== "" && editing === "new" && (
{/* PLAN — the operator selects an admin-defined plan; the price is looked up
(never typed). On edit the plan/price is frozen, shown read-only. */}
{editing === "new" ? (
<>
<label className="label">{t("subs.plan")}</label>
<span className="flex flex-wrap items-center gap-2">
<select
className="select input w-auto"
value={form.planId}
onChange={(e) => setForm((f) => ({ ...f, planId: e.target.value }))}
>
<option value="">{t("subs.planNone")}</option>
{plans.map((p) => (
<option key={p.planId} value={p.planId}>
{p.name} — {(p.pricePerPeriodMinor / 100).toLocaleString()} {p.currency} / {t(PERIOD_KEY[p.period])}
</option>
))}
</select>
{plans.length === 0 && <span className="text-[12px] text-term-amber">{t("subs.planNoneAvail")}</span>}
</span>
</>
) : (
<>
<label className="label">{t("subs.plan")}</label>
<span className="text-[13px] text-term-text">{form.planId || t("subs.noPrice")}</span>
</>
)}
{/* Tender — only relevant when selling a plan (a SALE). The sale appends a
signed payment so the money shows in the feed/drawer/Z-report. */}
{form.planId.trim() !== "" && editing === "new" && (
<>
<label className="label">{t("subs.tender")}</label>
<span className="flex items-center gap-3">
@@ -393,21 +419,26 @@ export function SubscriptionManager() {
</span>
<label className="label">{t("subs.validFrom")}</label>
<input type="date" className="input w-44" value={form.validFrom} onChange={(e) => setForm((f) => ({ ...f, validFrom: e.target.value }))} />
<label className="label">{t("subs.months")}</label>
<label className="label">{t("subs.validToEnd")}</label>
<span className="flex flex-wrap items-center gap-2">
<input
className="input w-16"
value={form.months}
onChange={(e) => setForm((f) => ({ ...f, months: e.target.value }))}
inputMode="numeric"
placeholder="1"
/>
<span className="text-[12px] text-term-muted">{t("subs.monthsHint")}</span>
{/* Live preview of the coverage end + the N×price total. */}
{coverageHint && <span className="text-[12px] text-term-cyan">{coverageHint}</span>}
<input type="date" className="input w-44" value={form.validTo} onChange={(e) => setForm((f) => ({ ...f, validTo: e.target.value }))} />
{/* Live SERVER quote: ceil(periods) × per-period price. The operator can't
override it — this is exactly what will be charged + signed. */}
{editing === "new" && form.planId.trim() !== "" && (
<span className="text-[12px] text-term-cyan">
{quoting
? t("subs.quoting")
: quote
? t("subs.quoteLine", {
periods: quote.periods,
unit: t(PERIOD_KEY[quote.period]),
amount: (quote.amountMinor / 100).toLocaleString(),
currency: quote.currency,
})
: t("subs.quotePrompt")}
</span>
)}
</span>
<label className="label">{t("subs.validToOverride")}</label>
<input type="date" className="input w-44" value={form.validTo} onChange={(e) => setForm((f) => ({ ...f, validTo: e.target.value }))} />
<label className="label">{t("subs.boundPlates")}</label>
<input className="input" value={form.platesText} onChange={(e) => setForm((f) => ({ ...f, platesText: e.target.value }))} placeholder={t("subs.commaSeparatedOptional")} />
</div>