From 590757e040b0b4bc40278ce5865683194e47a067 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Mon, 23 Nov 2026 11:14:05 +0200 Subject: [PATCH] Hub 2.14.0: customer page as a summary and tabs, popups for every edit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Customer page: header tiles (products, owing, next invoice, address, AI) and three tabs (Overview, Products, Invoices and payments), the tab in the URL; #billing links open Invoices and payments and Billing's links use ?tab=invoices. - Every add or edit is a popup (new Modal in components/ui.tsx: Esc / click outside, asks before discarding changes, focus kept inside, full screen on a phone). The page shows only read views. Record payment is a popup on Billing and the invoice page too. - One card per product: licence and billing fields in one Edit with one Save (each endpoint called only if its fields changed); suspend/revoke/reactivate/release in a ⋯ menu. Contact and billing details edited together. One page-level message. - History as one timeline with a filter; each kind on its own keeps its sortable table. - CustomerBilling.tsx split into components/customer/; plan in docs/CUSTOMER-PAGE-PLAN.md. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 26 ++ backend/package-lock.json | 4 +- backend/package.json | 2 +- docs/CUSTOMER-PAGE-PLAN.md | 145 ++++++ frontend/package-lock.json | 4 +- frontend/package.json | 2 +- .../app/(hub)/billing/invoices/[id]/page.tsx | 4 +- frontend/src/app/(hub)/billing/page.tsx | 6 +- .../src/app/(hub)/customers/[id]/page.tsx | 314 +++++-------- .../components/billing/CustomerBilling.tsx | 436 ------------------ .../src/components/billing/OneOffInvoice.tsx | 42 ++ .../src/components/billing/RecordPayment.tsx | 19 +- .../components/customer/AddProductModal.tsx | 51 ++ .../src/components/customer/AddressCard.tsx | 73 +++ frontend/src/components/customer/AiCard.tsx | 59 +++ .../components/customer/CustomerHeader.tsx | 73 +++ .../src/components/customer/DetailsCard.tsx | 97 ++++ frontend/src/components/customer/History.tsx | 207 +++++++++ .../src/components/customer/NextInvoice.tsx | 46 ++ .../src/components/customer/ProductCard.tsx | 225 +++++++++ frontend/src/components/customer/ReadCard.tsx | 45 ++ .../src/components/customer/ScheduleCard.tsx | 60 +++ .../src/components/customer/SitesCard.tsx | 28 ++ .../src/components/customer/Statement.tsx | 37 ++ frontend/src/components/customer/shared.ts | 63 +++ frontend/src/components/ui.tsx | 118 ++++- 26 files changed, 1530 insertions(+), 656 deletions(-) create mode 100644 docs/CUSTOMER-PAGE-PLAN.md delete mode 100644 frontend/src/components/billing/CustomerBilling.tsx create mode 100644 frontend/src/components/billing/OneOffInvoice.tsx create mode 100644 frontend/src/components/customer/AddProductModal.tsx create mode 100644 frontend/src/components/customer/AddressCard.tsx create mode 100644 frontend/src/components/customer/AiCard.tsx create mode 100644 frontend/src/components/customer/CustomerHeader.tsx create mode 100644 frontend/src/components/customer/DetailsCard.tsx create mode 100644 frontend/src/components/customer/History.tsx create mode 100644 frontend/src/components/customer/NextInvoice.tsx create mode 100644 frontend/src/components/customer/ProductCard.tsx create mode 100644 frontend/src/components/customer/ReadCard.tsx create mode 100644 frontend/src/components/customer/ScheduleCard.tsx create mode 100644 frontend/src/components/customer/SitesCard.tsx create mode 100644 frontend/src/components/customer/Statement.tsx create mode 100644 frontend/src/components/customer/shared.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index bedec55..4adfa22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,32 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [2.14.0] - 2026-11-23 + +Frontend only: no migration, no API changes. + +### Changed + +- **The customer page is a summary and three tabs.** The header shows the church's products, what + it owes, the next invoice (date and estimated amount), its address and AI allowance; click a tile + to open it. Below are **Overview** (details, billing schedule, address, AI, sites), + **Products** and **Invoices and payments**. The tab is in the address (`?tab=products`), and + links from Billing open Invoices and payments. +- **Every add and edit is a popup.** Details, schedule, address, AI allowance, add product, edit + product, notice of licence change, record payment and one-off invoice open over the page, which + shows only read views. A popup closes on Esc or a click outside, asking first if you've changed + something; its error shows by its Save button. Record payment is a popup on Billing and the + invoice page too. +- **One card per product.** The licence (tier, expiry, grace, notes) and its billing (charged + from, custom price) are one card with one Edit and one Save. Suspend, revoke, reactivate and + release are in the card's ⋯ menu, away from the everyday fields. +- **One details form.** The contact details and the billing details (billing email, postal + address, founding) are edited together. +- **One message** under the header for the whole page, instead of one per section. +- **History as one timeline.** Invoices, payments, notices of licence change and billing emails + in date order, with a filter; picking one kind shows its own table, sortable as before. +- Archive / Restore moved into the ⋯ menu by the customer's name. + ## [2.13.0] - 2026-11-23 Migration `20261123120000_alert_cleared` (one column on `InstallEvent`). diff --git a/backend/package-lock.json b/backend/package-lock.json index 9238cb6..b56adeb 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-backend", - "version": "2.13.0", + "version": "2.14.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "2.13.0", + "version": "2.14.0", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", diff --git a/backend/package.json b/backend/package.json index c88dab1..86a0712 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "2.13.0", + "version": "2.14.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", diff --git a/docs/CUSTOMER-PAGE-PLAN.md b/docs/CUSTOMER-PAGE-PLAN.md new file mode 100644 index 0000000..7843568 --- /dev/null +++ b/docs/CUSTOMER-PAGE-PLAN.md @@ -0,0 +1,145 @@ +# Customer page clean-up plan (`/customers/[id]`) + +Status: done in Hub 2.14.0 (all five steps in one release) · 2026-11-23 + +The customer page has grown one card at a time and is now one long scroll of open forms. This plan +reorganises it into a summary header and tabs, merges the duplicated product settings, and does it in +small steps that can each be released on their own. No backend changes are needed. + +## What's wrong today + +Files: `frontend/src/app/(hub)/customers/[id]/page.tsx` (239 lines) and +`frontend/src/components/billing/CustomerBilling.tsx` (436 lines). + +1. **Everything is an open form, all on one page.** About 13 cards: Details, one per licence, new + licence, billing details, billing schedule, address, products, next invoice, statement, invoices, + payments, notices of licence change, billing emails. +2. **Each product appears twice.** The licence card at the top (plan, status, expiry, grace days, + notes) and the billing card further down (charged from, custom price, notice of change). Both show a + plan/tier and each has its own Save button. +3. **Two "details" forms and two message banners.** Customer details and billing details are separate + forms; the page and the Billing section each have a message area, so feedback often appears far from + the button that was clicked. +4. **No summary.** To see what the church has, what it owes and when it's next invoiced you have to + scroll and add it up. +5. **Risky actions next to everyday ones.** Suspend, revoke and release sit beside notes and grace days. +6. **AI settings are buried** at the bottom of the contact details form. + +## Target layout + +### Header (always visible) + +- Name, founding star, archived badge, "customer since". +- A row of `Stat` tiles (existing component in `components/ui.tsx`): + - **Products**: e.g. "Events · Website · Accounts", red/amber if any is suspended or expiring. + - **Owing**: balance, red when overdue. + - **Next invoice**: date and estimated amount. + - **Address**: own domain / Cross Code address / included domain, with the domain. + - **AI**: monthly cap, or "Off". +- Actions: **Record payment**, **One-off invoice**, **Add product**, each opening a popup. **Archive / + Restore** moves into a "⋯" menu. +- Clicking the **Next invoice** tile opens the next-invoice preview in a popup. + +### Why there is no Billing tab + +The Billing page (`/billing`) is the ledger across all churches: every invoice, every payment, the +founding list. It has nothing that belongs to one church (billing email, postal address, schedule, +next-invoice preview, statement), and its links send you to the customer page for those. So the +customer page still needs them, but they don't need a tab of their own: + +- Billing email, postal address and founding are **details**: they join the contact details in one + Details view and one Edit popup (this also fixes "two details forms"). +- Custom price and charged-from belong to a **product**: they go on the product card. +- Schedule, next invoice and owing are **summary**: they live in the header tiles. +- Statement, invoices, payments, notices and billing emails are this church's **slice of the Billing + page**: one "Invoices and payments" tab. + +Three tabs instead of four. + +### Tabs + +Using the existing `Tabs` component, with the active tab in the URL (`?tab=products`) so links and +reloads keep it. + +| Tab | Contents | +|---|---| +| **Overview** | Details (contact, notes, billing email, postal address, founding), billing schedule, address (own domain / Cross Code / included), AI allowance: each as text with **Edit**. Sites, with their address and last heartbeat (links to `/installs/[id]`). | +| **Products** | **One card per product**, combining the licence and the billing settings (see below). **Add product** button at the top. | +| **Invoices and payments** | Statement (PDF, email) at the top, then invoices, payments, notices of licence change and billing emails. Later, optionally one combined timeline. | + +### Popups, not inline forms + +Every add or edit opens a popup; the page itself only shows read views. That covers: Edit details, +Edit schedule, Edit address, Edit AI allowance, Add product, Edit product, Notice of licence change, +Record payment, One-off invoice, Next-invoice preview. + +- New `Modal` component in `components/ui.tsx` (there is none yet): overlay, title, close button, + closes on Esc or a click outside (asking first if the form has unsaved changes), focus kept inside, + page scroll locked, full-screen sheet at phone width. +- A form's error shows inside the popup next to its Save button; on success the popup closes and the + page message shows the confirmation. +- Confirmations for risky actions (Suspend, Revoke, Release, Archive) stay as they are. +- `RecordPayment` is already a self-contained card with a close button, so it just goes inside a + `Modal`. Using the same popup on `/billing` and the invoice page is a free follow-up. + +### One product card + +Read view: + +``` +Cross Events CE-XXXX-XXXX [copy] ● Active +events.hopefamily.co.za · heartbeat 4 min ago +Tier Medium · R350/month · charged from 1 Dec 2026 · expires never + [Notice of change…] [Edit] [⋯] +``` + +**Edit** opens one popup with one **Save**: + +- Licence: tier, expiry, grace days, notes. +- Billing: charged from, custom price. + +The "⋯" menu holds Suspend, Revoke and Release from site, each with its existing confirmation, so they +are no longer next to the everyday fields. + +The Save still calls the two existing endpoints (`PUT /api/admin/licences/:id` and +`PUT /api/admin/billing/licences/:id`), only those whose fields changed. Accounts keeps its "Free: comes +with the church's other products" line and has no billing fields. + +### Messages + +One page-level message (a toast or a sticky banner under the header) shared by every tab, replacing the +two banners. Keep the existing wording ("The site picks it up with its next heartbeat…"). + +### Existing links + +`/customers/[id]#billing` is used by `billing/page.tsx` (twice) and `billing/invoices/[id]/page.tsx`. +Treat `#billing` as `?tab=invoices` on load, then change those three links to `?tab=invoices`. + +## Steps + +Each step is its own branch and Hub release. + +1. **Split the files, no visual change.** Move the pieces into `frontend/src/components/customer/`: + `CustomerHeader`, `DetailsCard`, `AiCard`, `LicenceCard`, `NewLicenceForm`, and from + `CustomerBilling.tsx`: `BillingDetails`, `Schedule`, `Address`, `LicenceBilling`, `NextInvoice`, + `Statement`, `InvoiceList`, `PaymentList`, `NoticeList`, `EmailLog`. Load the customer and billing + data once in the page and pass them down. This keeps the later diffs small. +2. **Header summary, tabs and one message.** The biggest improvement for the effort. Includes the + `#billing` → `?tab=invoices` handling and updating the three links. +3. **`Modal` and read views.** Add `Modal`; details (merged with billing details), schedule, address + and AI become read views with Edit popups; Record payment and One-off invoice move into popups. +4. **One card per product.** Merge `LicenceCard` and `LicenceBilling` into a read card with an Edit + popup; suspend/revoke/release go in its "⋯" menu; Add product and Notice of change become popups. +5. *(Optional)* **Invoices and payments as one timeline**: invoices, payments, notices and emails in date order with + a filter. + +## Checks for each step + +- `frontend` builds and type-checks; backend tests still pass (no backend changes expected). +- Every existing action still works: save details, AI cap/markup, generate licence (and the free + Accounts licence), save/suspend/revoke/release licence, archive/restore, billing details, schedule, + address, product billing, notice of licence change (send, PDF, send again), statement (PDF, email), + one-off invoice, record payment, receipts. +- Popups: Esc and the close button work, unsaved changes ask before closing, errors show in the popup. +- Phone width: tabs scroll sideways, stat tiles wrap, popups go full-screen, no horizontal page scroll. +- CHANGELOG entry and version bump as usual. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 562a116..9614a13 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-frontend", - "version": "2.13.0", + "version": "2.14.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-frontend", - "version": "2.13.0", + "version": "2.14.0", "dependencies": { "lucide-react": "^0.536.0", "next": "^15.5.24", diff --git a/frontend/package.json b/frontend/package.json index e24ccaa..d84c66e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "2.13.0", + "version": "2.14.0", "private": true, "scripts": { "dev": "next dev -p 3200", diff --git a/frontend/src/app/(hub)/billing/invoices/[id]/page.tsx b/frontend/src/app/(hub)/billing/invoices/[id]/page.tsx index c2bcbf7..fbcde03 100644 --- a/frontend/src/app/(hub)/billing/invoices/[id]/page.tsx +++ b/frontend/src/app/(hub)/billing/invoices/[id]/page.tsx @@ -146,7 +146,7 @@ function InvoiceDetail({ id }: { id: string }) { Billing {inv.customer?.name}{inv.customer?.founding && founding church}} + subtitle={<>{inv.customer?.name}{inv.customer?.founding && founding church}} actions={} />
@@ -184,7 +184,7 @@ function InvoiceDetail({ id }: { id: string }) { )} - {paying &&
setPaying(false)} onSaved={m => { setMsg(m); setPaying(false); load(); }} />
} + {paying && setPaying(false)} onSaved={m => { setMsg(m); setPaying(false); load(); }} />}
diff --git a/frontend/src/app/(hub)/billing/page.tsx b/frontend/src/app/(hub)/billing/page.tsx index f90d063..84b4522 100644 --- a/frontend/src/app/(hub)/billing/page.tsx +++ b/frontend/src/app/(hub)/billing/page.tsx @@ -139,7 +139,7 @@ export default function BillingPage() { )} {paying && accounts && ( -
({ id: a.id, name: a.name }))} onClose={() => setPaying(false)} onSaved={(m) => { setMsg(m); setPaying(false); loadOverview(); loadPayments(); loadInvoices(); }} />
+ ({ id: a.id, name: a.name }))} onClose={() => setPaying(false)} onSaved={(m) => { setMsg(m); setPaying(false); loadOverview(); loadPayments(); loadInvoices(); }} /> )} @@ -184,7 +184,7 @@ export default function BillingPage() { {payPaged.rows.map(p => ( {p.receiptNumber}
{METHOD[p.method] || p.method}{p.reference ? ` · ${p.reference}` : ""}
- {p.customer?.name} + {p.customer?.name} {day(p.paidOn)} {p.invoice ? {p.invoice.number} : "On account"} {money(p.amountCents)} @@ -208,7 +208,7 @@ export default function BillingPage() { {accSorted.rows.map(a => ( - {a.name}
{a.billingEmail || ""}
+ {a.name}
{a.billingEmail || ""}
{a.founding &&
{a.foundingSince ? `since ${day(a.foundingSince)}` : ""}{a.foundingNote ? ` · ${a.foundingNote}` : ""}
} diff --git a/frontend/src/app/(hub)/customers/[id]/page.tsx b/frontend/src/app/(hub)/customers/[id]/page.tsx index 556ae1b..bf0502f 100644 --- a/frontend/src/app/(hub)/customers/[id]/page.tsx +++ b/frontend/src/app/(hub)/customers/[id]/page.tsx @@ -3,237 +3,159 @@ import React, { useCallback, useEffect, useState } from "react"; import Link from "next/link"; import { useParams } from "next/navigation"; -import { Archive, ArchiveRestore, ArrowLeft, Copy, KeyRound } from "lucide-react"; +import { KeyRound, X } from "lucide-react"; import { api, errorText } from "@/lib/api"; -import { ago, fmtDate } from "@/lib/format"; -import { PLANS_BY_PRODUCT } from "@/lib/tiers"; -import { KEY_WHERE, PRODUCTS, PRODUCT_NAMES, byProduct, type Product } from "@/lib/products"; -import type { Customer, Licence, LicenceStatus } from "@/lib/types"; -import { Badge, Loading, Message, PageTitle } from "@/components/ui"; -import { CustomerBilling } from "@/components/billing/CustomerBilling"; -import { EmailList } from "@/components/EmailList"; +import { PRODUCTS, byProduct } from "@/lib/products"; +import type { Customer } from "@/lib/types"; +import { Loading, Message, Tabs } from "@/components/ui"; +import { RecordPayment } from "@/components/billing/RecordPayment"; +import { OneOffInvoice } from "@/components/billing/OneOffInvoice"; +import { CustomerHeader, type HeaderAction } from "@/components/customer/CustomerHeader"; +import { DetailsCard } from "@/components/customer/DetailsCard"; +import { ScheduleCard, ScheduleModal } from "@/components/customer/ScheduleCard"; +import { AddressCard, AddressModal } from "@/components/customer/AddressCard"; +import { AiCard, AiModal } from "@/components/customer/AiCard"; +import { SitesCard } from "@/components/customer/SitesCard"; +import { ProductCard } from "@/components/customer/ProductCard"; +import { AddProductModal } from "@/components/customer/AddProductModal"; +import { NextInvoiceModal } from "@/components/customer/NextInvoice"; +import { Statement } from "@/components/customer/Statement"; +import { History } from "@/components/customer/History"; +import type { CustomerBillingData, Done, Msg, Preview } from "@/components/customer/shared"; -type Msg = { type: "ok" | "err"; text: string } | null; -const dateInput = (d: string | null) => (d ? d.slice(0, 10) : ""); +type Tab = "overview" | "products" | "invoices"; +const TABS: { key: Tab; label: string }[] = [ + { key: "overview", label: "Overview" }, + { key: "products", label: "Products" }, + { key: "invoices", label: "Invoices and payments" }, +]; +type Popup = Exclude | "schedule" | null; -/** One licence: its key, and the settings that go into the next token the install receives. */ -function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: () => void; setMsg: (m: Msg) => void }) { - const [form, setForm] = useState({ - status: licence.status, - plan: licence.plan, - expiresAt: dateInput(licence.expiresAt), - graceDays: String(licence.graceDays), - notes: licence.notes || "", - }); - const [busy, setBusy] = useState(false); - - const save = async () => { - if (form.status !== licence.status && form.status !== "active" && !confirm(`${form.status === "revoked" ? "Revoke" : "Suspend"} this licence? The site becomes read-only after its next heartbeat (tickets still scan, data can still be exported).`)) return; - setBusy(true); - try { - await api(`/api/admin/licences/${licence.id}`, { - method: "PUT", - body: { - status: form.status, - plan: form.plan, - // End of the chosen day, South African time. - expiresAt: form.expiresAt ? `${form.expiresAt}T23:59:59+02:00` : null, - graceDays: form.graceDays, - notes: form.notes, - }, - }); - setMsg({ type: "ok", text: "Licence saved. The site picks it up with its next heartbeat (within 15 minutes)." }); - onSaved(); - } catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); } - }; - - const release = async () => { - if (!confirm("Release this licence from its site? The site's heartbeats are refused from now on, and the key can be registered again from a new address.")) return; - try { - await api(`/api/admin/licences/${licence.id}/release`, { method: "POST" }); - setMsg({ type: "ok", text: "Released." }); - onSaved(); - } catch (e) { setMsg({ type: "err", text: errorText(e) }); } - }; - - return ( -
-
- - {PRODUCT_NAMES[licence.product]} - {licence.key} - - -
-
- {licence.install - ? <>Used by {licence.install.url} · last heartbeat {ago(licence.install.lastHeartbeatAt)} - : `Not used yet — enter this key in ${KEY_WHERE[licence.product]}.`} -
-
-
- - {licence.product === "accounts" ? ( - - ) : ( - - )} -

- {licence.product === "accounts" - ? "Free: comes with the church's other products." - : "Shown on the church's Licence page. Billing and founding status are under Billing below."} -

-
-
- - -
-
- - setForm({ ...form, expiresAt: e.target.value })} /> -

{form.expiresAt ? "" : "No end date"}

-
-
- - setForm({ ...form, graceDays: e.target.value })} /> -
-
-
- - setForm({ ...form, notes: e.target.value })} placeholder="Anything worth remembering about this licence" /> -
-
- - {licence.install && } - Created {fmtDate(licence.createdAt, false)} -
-
- ); +/** The tab in the address (?tab=products); the old #billing link opens Invoices and payments. */ +function tabFromUrl(): Tab { + const q = new URLSearchParams(window.location.search).get("tab"); + if (TABS.some(t => t.key === q)) return q as Tab; + return window.location.hash === "#billing" ? "invoices" : "overview"; } +/** + * Hub 2.14.0: a customer as a summary header and three tabs (Overview, Products, Invoices and + * payments). Every add or edit is a popup; the page only shows read views. The customer, its + * billing and the next-invoice preview are loaded here once and passed down. + */ export default function CustomerPage() { const { id } = useParams<{ id: string }>(); const [c, setC] = useState(null); - const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "", notes: "", aiRand: "0", aiMarkup: "" }); - const [newLicence, setNewLicence] = useState<{ product: Product | ""; expiresAt: string; graceDays: string }>({ product: "", expiresAt: "", graceDays: "14" }); + const [b, setB] = useState(null); + const [preview, setPreview] = useState(null); + const [previewError, setPreviewError] = useState(null); const [msg, setMsg] = useState(null); + const [tab, setTab] = useState("overview"); + const [popup, setPopup] = useState(null); - const load = useCallback(() => api(`/api/admin/customers/${id}`).then(x => { - setC(x); - setForm({ - name: x.name, contactName: x.contactName || "", email: x.email || "", phone: x.phone || "", notes: x.notes || "", - aiRand: String(x.aiMonthlyCapCents / 100), aiMarkup: x.aiMarkupPercent == null ? "" : String(x.aiMarkupPercent), - }); - }).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]); + const load = useCallback(() => Promise.all([ + api(`/api/admin/customers/${id}`).then(setC), + api(`/api/admin/billing/customers/${id}`).then(setB), + api(`/api/admin/billing/customers/${id}/preview`).then(p => { setPreview(p); setPreviewError(null); }).catch(e => setPreviewError(errorText(e))), + ]).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]); useEffect(() => { load(); }, [load]); + useEffect(() => { + const t = tabFromUrl(); + setTab(t); + if (window.location.hash === "#billing") window.history.replaceState(null, "", `?tab=${t}`); + }, []); + const openTab = (t: Tab) => { + setTab(t); + window.history.replaceState(null, "", t === "overview" ? window.location.pathname : `?tab=${t}`); + }; + + // An "ok" message fades after a while; an error stays until it's closed or replaced. + useEffect(() => { + if (msg?.type !== "ok") return; + const t = setTimeout(() => setMsg(m => (m === msg ? null : m)), 12000); + return () => clearTimeout(t); + }, [msg]); + + /** Every card and popup reports here: close the popup, show the message, reload. */ + const done: Done = m => { setPopup(null); setMsg(m); load(); }; + const close = () => setPopup(null); + if (!c) return msg ? : ; // One open (not revoked) licence per product; Accounts comes with the first other product. const taken = new Set(c.licences.filter(l => l.status !== "revoked").map(l => l.product)); const available = PRODUCTS.filter(p => !taken.has(p)); - const product: Product | undefined = newLicence.product && available.includes(newLicence.product) ? newLicence.product : available.find(p => p !== "accounts") || available[0]; - const licences = [...c.licences].sort((a, b) => byProduct(a, b) || (a.status === "revoked" ? 1 : 0) - (b.status === "revoked" ? 1 : 0)); + const licences = [...c.licences].sort((x, y) => (x.status === "revoked" ? 1 : 0) - (y.status === "revoked" ? 1 : 0) || byProduct(x, y)); - const saveDetails = async (e: React.FormEvent) => { - e.preventDefault(); - try { - const { aiRand, aiMarkup, ...details } = form; - await api(`/api/admin/customers/${id}`, { - method: "PUT", - body: { ...details, aiMonthlyCapCents: Math.round((parseFloat(aiRand) || 0) * 100), aiMarkupPercent: aiMarkup.trim() === "" ? null : aiMarkup }, - }); - setMsg({ type: "ok", text: "Saved. The church's sites pick up an AI change with their next heartbeat (within 15 minutes)." }); - load(); - } catch (err) { setMsg({ type: "err", text: errorText(err) }); } - }; - - const generate = async (e: React.FormEvent) => { - e.preventDefault(); - try { - const l = await api(`/api/admin/customers/${id}/licences`, { - method: "POST", - body: { product, expiresAt: newLicence.expiresAt ? `${newLicence.expiresAt}T23:59:59+02:00` : null, graceDays: newLicence.graceDays }, - }); - setMsg({ - type: "ok", - text: `${PRODUCT_NAMES[l.product]} licence ${l.key} created. Send it to the church for their setup.` - + (l.accountsLicence ? ` Their Accounts licence (free) was created too: ${l.accountsLicence.key}.` : ""), - }); - load(); - } catch (err) { setMsg({ type: "err", text: errorText(err) }); } - }; - - // Hub 2.12.0: archive (left out of the list and pickers) or restore. const setArchivedState = async (archive: boolean) => { if (archive && !confirm(`Archive ${c.name}? It's left out of the customer list until you restore it (Customers → Archived). Nothing else changes.`)) return; try { await api(`/api/admin/customers/${id}/${archive ? "archive" : "restore"}`, { method: "POST" }); - setMsg({ type: "ok", text: archive ? "Archived. Find it under Customers → Archived." : "Restored: it's in the customer list again." }); - load(); + done({ type: "ok", text: archive ? "Archived. Find it under Customers → Archived." : "Restored: it's in the customer list again." }); } catch (err) { setMsg({ type: "err", text: errorText(err) }); } }; + const onAction = (a: HeaderAction) => { if (a === "history") openTab("invoices"); else setPopup(a); }; return ( <> - Customers - setArchivedState(false)}> Restore - : } /> -
+ 0} onAction={onAction} onArchive={setArchivedState} /> -
-
-

Details

-
setForm({ ...form, name: e.target.value })} required />
-
setForm({ ...form, contactName: e.target.value })} />
- setForm({ ...form, email })} placeholder="office@church.org" /> -
setForm({ ...form, phone: e.target.value })} />
-