Hub 2.14.0: customer page as a summary and tabs, popups for every edit
- 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 <noreply@anthropic.com>
This commit is contained in:
@@ -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`).
|
||||
|
||||
Generated
+2
-2
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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.
|
||||
Generated
+2
-2
@@ -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",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "events-hub-frontend",
|
||||
"version": "2.13.0",
|
||||
"version": "2.14.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3200",
|
||||
|
||||
@@ -146,7 +146,7 @@ function InvoiceDetail({ id }: { id: string }) {
|
||||
<Link href="/billing" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Billing</Link>
|
||||
<PageTitle
|
||||
title={`Invoice ${inv.number}`}
|
||||
subtitle={<><Link className="text-indigo-600 hover:underline" href={`/customers/${inv.customerId}#billing`}>{inv.customer?.name}</Link>{inv.customer?.founding && <span className="ml-2 inline-flex items-center gap-1 text-amber-700"><Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" /> founding church</span>}</>}
|
||||
subtitle={<><Link className="text-indigo-600 hover:underline" href={`/customers/${inv.customerId}?tab=invoices`}>{inv.customer?.name}</Link>{inv.customer?.founding && <span className="ml-2 inline-flex items-center gap-1 text-amber-700"><Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" /> founding church</span>}</>}
|
||||
actions={<StateBadge state={inv.state} />}
|
||||
/>
|
||||
<div className="mb-4"><Message msg={msg} /></div>
|
||||
@@ -184,7 +184,7 @@ function InvoiceDetail({ id }: { id: string }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{paying && <div className="mb-4"><RecordPayment invoice={inv} onClose={() => setPaying(false)} onSaved={m => { setMsg(m); setPaying(false); load(); }} /></div>}
|
||||
{paying && <RecordPayment invoice={inv} onClose={() => setPaying(false)} onSaved={m => { setMsg(m); setPaying(false); load(); }} />}
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
|
||||
<div className="card space-y-4">
|
||||
|
||||
@@ -139,7 +139,7 @@ export default function BillingPage() {
|
||||
)}
|
||||
|
||||
{paying && accounts && (
|
||||
<div className="mb-6"><RecordPayment customers={accounts.map(a => ({ id: a.id, name: a.name }))} onClose={() => setPaying(false)} onSaved={(m) => { setMsg(m); setPaying(false); loadOverview(); loadPayments(); loadInvoices(); }} /></div>
|
||||
<RecordPayment customers={accounts.map(a => ({ id: a.id, name: a.name }))} onClose={() => setPaying(false)} onSaved={(m) => { setMsg(m); setPaying(false); loadOverview(); loadPayments(); loadInvoices(); }} />
|
||||
)}
|
||||
|
||||
<Tabs tabs={TABS} active={tab} onChange={openTab} />
|
||||
@@ -184,7 +184,7 @@ export default function BillingPage() {
|
||||
{payPaged.rows.map(p => (
|
||||
<tr key={p.id} className="border-t border-slate-100">
|
||||
<td className="p-3 font-medium">{p.receiptNumber}<div className="text-xs text-slate-500">{METHOD[p.method] || p.method}{p.reference ? ` · ${p.reference}` : ""}</div></td>
|
||||
<td className="p-3"><Link className="hover:underline" href={`/customers/${p.customerId}#billing`}>{p.customer?.name}</Link></td>
|
||||
<td className="p-3"><Link className="hover:underline" href={`/customers/${p.customerId}?tab=invoices`}>{p.customer?.name}</Link></td>
|
||||
<td className="p-3 whitespace-nowrap">{day(p.paidOn)}</td>
|
||||
<td className="p-3">{p.invoice ? <Link className="text-indigo-700 hover:underline" href={`/billing/invoices/${p.invoice.id}`}>{p.invoice.number}</Link> : "On account"}</td>
|
||||
<td className="p-3 text-right tabular-nums">{money(p.amountCents)}</td>
|
||||
@@ -208,7 +208,7 @@ export default function BillingPage() {
|
||||
<tbody>
|
||||
{accSorted.rows.map(a => (
|
||||
<tr key={a.id} className="border-t border-slate-100 align-top">
|
||||
<td className="p-3"><Link className="font-medium text-indigo-700 hover:underline" href={`/customers/${a.id}#billing`}>{a.name}</Link><div className="text-xs text-slate-500">{a.billingEmail || ""}</div></td>
|
||||
<td className="p-3"><Link className="font-medium text-indigo-700 hover:underline" href={`/customers/${a.id}?tab=invoices`}>{a.name}</Link><div className="text-xs text-slate-500">{a.billingEmail || ""}</div></td>
|
||||
<td className="p-3">
|
||||
<label className="inline-flex items-center gap-2"><input type="checkbox" checked={a.founding} onChange={() => toggleFounding(a)} /> {a.founding ? "Founding" : "No"}</label>
|
||||
{a.founding && <div className="text-xs text-slate-500">{a.foundingSince ? `since ${day(a.foundingSince)}` : ""}{a.foundingNote ? ` · ${a.foundingNote}` : ""}</div>}
|
||||
|
||||
@@ -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<HeaderAction, "history"> | "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 (
|
||||
<div className="card space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<KeyRound className="h-4 w-4 text-slate-400" />
|
||||
<span className="font-semibold">{PRODUCT_NAMES[licence.product]}</span>
|
||||
<code className="text-sm font-semibold tracking-wide">{licence.key}</code>
|
||||
<button className="text-xs text-indigo-600 hover:underline" onClick={() => navigator.clipboard?.writeText(licence.key)} aria-label="Copy key"><Copy className="inline h-3.5 w-3.5" /> Copy</button>
|
||||
<span className="ml-auto"><Badge value={licence.status} /></span>
|
||||
</div>
|
||||
<div className="text-sm text-slate-600">
|
||||
{licence.install
|
||||
? <>Used by <Link href={`/installs/${licence.install.id}`} className="text-indigo-600 hover:underline">{licence.install.url}</Link> · last heartbeat {ago(licence.install.lastHeartbeatAt)}</>
|
||||
: `Not used yet — enter this key in ${KEY_WHERE[licence.product]}.`}
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-6">
|
||||
<div>
|
||||
<label className="label" htmlFor={`plan-${licence.id}`}>Plan</label>
|
||||
{licence.product === "accounts" ? (
|
||||
<input id={`plan-${licence.id}`} className="input" value="Included" disabled />
|
||||
) : (
|
||||
<select id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })}>
|
||||
{!PLANS_BY_PRODUCT[licence.product].includes(form.plan) && <option value={form.plan}>{form.plan}</option>}
|
||||
{PLANS_BY_PRODUCT[licence.product].map(p => <option key={p} value={p}>{p}</option>)}
|
||||
</select>
|
||||
)}
|
||||
<p className="mt-1 text-xs text-slate-500">
|
||||
{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."}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Status</label>
|
||||
<select className="input" value={form.status} onChange={e => setForm({ ...form, status: e.target.value as LicenceStatus })}>
|
||||
<option value="active">Active</option>
|
||||
<option value="suspended">Suspended</option>
|
||||
<option value="revoked">Revoked</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Expires</label>
|
||||
<input type="date" className="input" value={form.expiresAt} onChange={e => setForm({ ...form, expiresAt: e.target.value })} />
|
||||
<p className="mt-1 text-xs text-slate-500">{form.expiresAt ? "" : "No end date"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Grace (days)</label>
|
||||
<input type="number" min={0} max={90} className="input" value={form.graceDays} onChange={e => setForm({ ...form, graceDays: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Notes</label>
|
||||
<input className="input" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="Anything worth remembering about this licence" />
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button className="btn-primary" onClick={save} disabled={busy}>{busy ? "Saving…" : "Save licence"}</button>
|
||||
{licence.install && <button className="btn-danger" onClick={release}>Release from site</button>}
|
||||
<span className="self-center text-xs text-slate-400">Created {fmtDate(licence.createdAt, false)}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
/** 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<Customer | null>(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<CustomerBillingData | null>(null);
|
||||
const [preview, setPreview] = useState<Preview | null>(null);
|
||||
const [previewError, setPreviewError] = useState<string | null>(null);
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
const [tab, setTab] = useState<Tab>("overview");
|
||||
const [popup, setPopup] = useState<Popup>(null);
|
||||
|
||||
const load = useCallback(() => api<Customer>(`/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<Customer>(`/api/admin/customers/${id}`).then(setC),
|
||||
api<CustomerBillingData>(`/api/admin/billing/customers/${id}`).then(setB),
|
||||
api<Preview>(`/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 ? <Message msg={msg} /> : <Loading />;
|
||||
|
||||
// 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<Licence & { accountsLicence: Licence | null }>(`/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 (
|
||||
<>
|
||||
<Link href="/customers" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Customers</Link>
|
||||
<PageTitle title={c.name}
|
||||
subtitle={c.archivedAt ? `Archived ${fmtDate(c.archivedAt, false)} · customer since ${fmtDate(c.createdAt, false)}` : `Customer since ${fmtDate(c.createdAt, false)}`}
|
||||
actions={c.archivedAt
|
||||
? <button className="btn-secondary" onClick={() => setArchivedState(false)}><ArchiveRestore className="h-4 w-4" /> Restore</button>
|
||||
: <button className="btn-secondary" onClick={() => setArchivedState(true)}><Archive className="h-4 w-4" /> Archive</button>} />
|
||||
<div className="mb-4"><Message msg={msg} /></div>
|
||||
<CustomerHeader c={c} b={b} preview={preview} canAdd={available.length > 0} onAction={onAction} onArchive={setArchivedState} />
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_2fr]">
|
||||
<form onSubmit={saveDetails} className="card space-y-3 self-start">
|
||||
<h2 className="font-semibold">Details</h2>
|
||||
<div><label className="label">Name</label><input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required /></div>
|
||||
<div><label className="label">Contact person</label><input className="input" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} /></div>
|
||||
<EmailList id="c-email" label="Email" value={form.email} onChange={email => setForm({ ...form, email })} placeholder="office@church.org" />
|
||||
<div><label className="label">Phone</label><input className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
|
||||
<div><label className="label">Notes</label><textarea className="input" rows={4} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="Plan, billing, anything worth remembering" /></div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label" htmlFor="ai-cap">AI cap (R / month)</label>
|
||||
<input id="ai-cap" type="number" min={0} step="1" className="input" value={form.aiRand} onChange={e => setForm({ ...form, aiRand: e.target.value })} />
|
||||
{msg && (
|
||||
<div className="sticky top-2 z-30 mb-4 flex items-start gap-2 [&>div]:flex-1 [&>div]:shadow-sm" role="status">
|
||||
<Message msg={msg} />
|
||||
<button type="button" aria-label="Dismiss" onClick={() => setMsg(null)} className="mt-2.5 rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700"><X className="h-4 w-4" /></button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Tabs tabs={TABS} active={tab} onChange={openTab} />
|
||||
|
||||
<div role="tabpanel" id={`panel-${tab}`} aria-labelledby={`tab-${tab}`}>
|
||||
{tab === "overview" && (
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<div className="space-y-4">
|
||||
{b && <DetailsCard c={c} b={b} onDone={done} />}
|
||||
<SitesCard c={c} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label" htmlFor="ai-markup">AI markup (%)</label>
|
||||
<input id="ai-markup" type="number" min={0} max={500} step="1" className="input" placeholder="Default" value={form.aiMarkup} onChange={e => setForm({ ...form, aiMarkup: e.target.value })} />
|
||||
<div className="space-y-4">
|
||||
{b && <ScheduleCard b={b} onEdit={() => setPopup("schedule")} />}
|
||||
{b && <AddressCard b={b} onEdit={() => setPopup("address")} onDone={done} />}
|
||||
<AiCard c={c} onEdit={() => setPopup("ai")} />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">The AI allowance is the church's, shared by all its sites: 0 = off (no AI buttons). Counted in charged rand. A blank markup uses the default (Settings → AI).</p>
|
||||
<button className="btn-secondary">Save details</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
<h2 className="font-semibold">Licences</h2>
|
||||
{licences.map(l => <LicenceCard key={`${l.id}-${l.status}-${l.expiresAt}`} licence={l} onSaved={load} setMsg={setMsg} />)}
|
||||
{product ? (
|
||||
<form onSubmit={generate} className="card flex flex-wrap items-end gap-3">
|
||||
<div>
|
||||
<label className="label" htmlFor="new-product">Product</label>
|
||||
<select id="new-product" className="input" value={product} onChange={e => setNewLicence({ ...newLicence, product: e.target.value as Product })}>
|
||||
{available.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
|
||||
</select>
|
||||
{tab === "products" && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<p className="text-sm text-slate-500">One licence per product. Accounts is free and comes with the first other product.</p>
|
||||
{available.length > 0
|
||||
? <button type="button" className="btn-primary" onClick={() => setPopup("add")}><KeyRound className="h-4 w-4" /> Add product</button>
|
||||
: <span className="text-sm text-slate-500">This customer has a licence for every product.</span>}
|
||||
</div>
|
||||
<div><label className="label">Expires (optional)</label><input type="date" className="input" value={newLicence.expiresAt} onChange={e => setNewLicence({ ...newLicence, expiresAt: e.target.value })} /></div>
|
||||
<div><label className="label">Grace (days)</label><input type="number" min={0} max={90} className="input w-24" value={newLicence.graceDays} onChange={e => setNewLicence({ ...newLicence, graceDays: e.target.value })} /></div>
|
||||
<button className="btn-primary"><KeyRound className="h-4 w-4" /> Generate licence</button>
|
||||
<p className="w-full text-xs text-slate-500">One licence per product (revoke one to replace it). Accounts is free and is created with the first other product.</p>
|
||||
</form>
|
||||
) : <p className="text-sm text-slate-500">This customer has a licence for every product.</p>}
|
||||
</div>
|
||||
{licences.length === 0 && <div className="card text-sm text-slate-500">No products yet: add one to generate its licence key.</div>}
|
||||
{licences.map(l => (
|
||||
<ProductCard key={l.id} licence={l} billing={b?.licences.find(x => x.id === l.id)} plans={b?.plans[l.product] || []} nextInvoiceDate={b?.nextInvoiceDate || null} onDone={done} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === "invoices" && b && (
|
||||
<div className="space-y-4">
|
||||
<Statement b={b} onDone={done} />
|
||||
<History b={b} onDone={done} />
|
||||
<p className="text-xs text-slate-500">All churches' invoices and payments are on <Link href="/billing" className="text-indigo-700 hover:underline">Billing</Link>.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<CustomerBilling key={c.licences.map(l => `${l.id}-${l.status}`).join()} customerId={id} />
|
||||
{popup === "payment" && <RecordPayment customerId={id} onClose={close} onSaved={done} />}
|
||||
{popup === "oneoff" && <OneOffInvoice customerId={id} onClose={close} onSaved={inv => done({ type: "ok", text: `Draft ${inv.number} made. Open it under Invoices and payments to check and approve it.` })} />}
|
||||
{popup === "add" && available.length > 0 && <AddProductModal customerId={id} available={available} onClose={close} onDone={m => { done(m); openTab("products"); }} />}
|
||||
{popup === "preview" && <NextInvoiceModal preview={preview} error={previewError} onClose={close} onSchedule={() => setPopup("schedule")} />}
|
||||
{popup === "schedule" && b && <ScheduleModal b={b} onClose={close} onDone={done} />}
|
||||
{popup === "address" && b && <AddressModal b={b} onClose={close} onDone={done} />}
|
||||
{popup === "ai" && <AiModal c={c} onClose={close} onDone={done} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,436 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { FileText, Mail, Plus, Star } from "lucide-react";
|
||||
import { api, errorText, openPdf } from "@/lib/api";
|
||||
import { fmtDate } from "@/lib/format";
|
||||
import { CYCLE, EMAIL_KIND, METHOD, StateBadge, centsFrom, day, money, randInput, todayYmd, type BillingCycle, type BillingEmail, type Invoice, type LicenceChange, type Line, type Payment, type PlanChange } from "@/lib/billing";
|
||||
import { PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
|
||||
import { RecordPayment } from "./RecordPayment";
|
||||
import { EmailList } from "@/components/EmailList";
|
||||
import { SortSelect, SortTh, useSort, type SortColumn } from "@/lib/sort";
|
||||
|
||||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
/** A plan of a product: the Events tiers have an income ceiling (upTo), the App tiers a member band. */
|
||||
type Plan = { name: string; monthly: number | null; founding: number | null; upTo?: number | null; band?: string };
|
||||
type BillingLicence = {
|
||||
id: string; key: string; product: Product; plan: string; status: string; customMonthlyCents: number | null;
|
||||
billedFrom: string | null; billedUntil: string | null; billable: boolean; url: string | null;
|
||||
incomeBand?: string | null; activeMembers?: string | null; storage?: { usedBytes: number; includedBytes: number } | null;
|
||||
};
|
||||
type CustomerBillingData = {
|
||||
id: string; name: string; billingEmail: string | null; billingAddress: string | null; founding: boolean; foundingSince: string | null; foundingNote: string | null;
|
||||
billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null;
|
||||
addressType: AddressType; domain: string | null; addressCustomCents: number | null; addressMonthlyCents: number; domainRenewsOn: string | null;
|
||||
sendsTo: string | null; balanceCents: number; licences: BillingLicence[]; invoices: Invoice[]; payments: Payment[]; licenceChanges: LicenceChange[]; emails: BillingEmail[];
|
||||
plans: Record<Product, Plan[]>;
|
||||
};
|
||||
type Preview = { billed: false } | { billed: true; empty: boolean; invoice: { periodStart: string; periodEnd: string; issueDate: string; lines: Line[]; totalCents: number; warnings: string[]; planChanges: PlanChange[] } };
|
||||
|
||||
const yearAgo = () => { const d = new Date(`${todayYmd()}T00:00:00Z`); d.setUTCFullYear(d.getUTCFullYear() - 1); d.setUTCDate(d.getUTCDate() + 1); return d.toISOString().slice(0, 10); };
|
||||
const gb = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GB`;
|
||||
|
||||
/** The tier a product's report points to: an Events income band ("R100 001–R150 000") or an App member band. */
|
||||
function suggestedTier(licence: BillingLicence, plans: Plan[]) {
|
||||
if (licence.product === "app") return plans.find(p => p.band && p.band === licence.activeMembers) || null;
|
||||
const band = licence.incomeBand;
|
||||
if (licence.product !== "events" || !band || band === "over R100 000") return null;
|
||||
if (/^over /.test(band)) return plans.find(t => t.upTo == null) || null;
|
||||
const top = Number((band.split("–")[1] || "").replace(/[^\d]/g, ""));
|
||||
return plans.find(t => t.upTo == null || top <= (t.upTo ?? Infinity)) || null;
|
||||
}
|
||||
|
||||
/** What the product reports that its price depends on. */
|
||||
function reportText(l: BillingLicence) {
|
||||
if (l.product === "events") return l.incomeBand ? `12-month event income ${l.incomeBand}` : "No event income reported yet";
|
||||
if (l.product === "app") return l.activeMembers ? `${l.activeMembers} active members (90 days)` : "No active members reported yet";
|
||||
if (l.product === "website") return l.storage ? `${gb(l.storage.usedBytes)} of ${gb(l.storage.includedBytes)} storage used` : "No storage reported yet";
|
||||
return "";
|
||||
}
|
||||
|
||||
/** The church's billing schedule: one for all its products. */
|
||||
function Schedule({ c, onSaved, setMsg }: { c: CustomerBillingData; onSaved: () => void; setMsg: (m: Msg) => void }) {
|
||||
const [form, setForm] = useState({ billingCycle: c.billingCycle, billingStart: c.billingStart || "", nextInvoiceDate: c.nextInvoiceDate || "", reviewDate: c.reviewDate || "" });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const off = form.billingCycle === "none";
|
||||
const save = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(`/api/admin/billing/customers/${c.id}`, { method: "PUT", body: { billingCycle: form.billingCycle, billingStart: form.billingStart || null, nextInvoiceDate: form.nextInvoiceDate || null, reviewDate: form.reviewDate || null } });
|
||||
setMsg({ type: "ok", text: off ? "Saved: this church isn't billed." : "Billing saved. The next draft, for all the church's products, is made 14 days before the next invoice date." });
|
||||
onSaved();
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<form onSubmit={save} className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div>
|
||||
<label className="label" htmlFor="cycle">Billing</label>
|
||||
<select id="cycle" className="input" value={form.billingCycle} onChange={e => setForm({ ...form, billingCycle: e.target.value as BillingCycle })}>
|
||||
{(Object.keys(CYCLE) as BillingCycle[]).map(k => <option key={k} value={k}>{CYCLE[k]}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="start">Billing started</label><input id="start" type="date" className="input" value={form.billingStart} onChange={e => setForm({ ...form, billingStart: e.target.value })} disabled={off} /></div>
|
||||
<div><label className="label" htmlFor="next">Next invoice</label><input id="next" type="date" className="input" value={form.nextInvoiceDate} onChange={e => setForm({ ...form, nextInvoiceDate: e.target.value })} disabled={off} /></div>
|
||||
<div><label className="label" htmlFor="review">Next tier review</label><input id="review" type="date" className="input" value={form.reviewDate} onChange={e => setForm({ ...form, reviewDate: e.target.value })} disabled={off} /></div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">One invoice covers all the church's products, in advance, on the same day of the month as billing started. Leave the next invoice and review blank to start from the billing date and review a year later. Starting billing charges the products that aren't charged yet from the billing date; a product added later starts after its free month.</p>
|
||||
<button className="btn-primary" disabled={busy}>Save billing</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
type AddressType = "own_domain" | "crosscode" | "included";
|
||||
const ADDRESS_OPTIONS: Record<AddressType, { label: string; price: string; help: string }> = {
|
||||
own_domain: { label: "Own domain", price: "R0", help: "The church (or whoever manages its domain) adds the DNS records we send. We look after the certificates." },
|
||||
crosscode: { label: "Cross Code address", price: "R10/month", help: "<church>.crosscode.co.za, with events., app. and so on in front. Free during a trial." },
|
||||
included: { label: "Domain included", price: "R25/month", help: "A .co.za or .org.za registered in the church's name; we renew it and manage the DNS. Other endings at cost: set a custom price." },
|
||||
};
|
||||
|
||||
/** The church's address: one for all its products, billed once per invoice and never discounted. */
|
||||
function Address({ c, onSaved, setMsg }: { c: CustomerBillingData; onSaved: () => void; setMsg: (m: Msg) => void }) {
|
||||
const [form, setForm] = useState({ addressType: c.addressType, domain: c.domain || "", custom: randInput(c.addressCustomCents), domainRenewsOn: c.domainRenewsOn || "" });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const save = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(`/api/admin/billing/customers/${c.id}`, { method: "PUT", body: { addressType: form.addressType, domain: form.domain || null, addressCustomCents: form.custom.trim() ? centsFrom(form.custom) : null, domainRenewsOn: form.domainRenewsOn || null } });
|
||||
setMsg({ type: "ok", text: `Address saved: ${ADDRESS_OPTIONS[form.addressType].label}.` });
|
||||
onSaved();
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); } finally { setBusy(false); }
|
||||
};
|
||||
const renewed = async () => {
|
||||
if (!confirm(`Mark ${c.domain || "the domain"} as renewed? The renewal date moves on a year.`)) return;
|
||||
try {
|
||||
const r = await api<{ message: string }>(`/api/admin/billing/customers/${c.id}/domain-renewed`, { method: "POST" });
|
||||
setMsg({ type: "ok", text: r.message });
|
||||
onSaved();
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||
};
|
||||
const due = c.addressType === "included" && c.domainRenewsOn && c.domainRenewsOn <= new Date(Date.now() + 30 * 864e5).toISOString().slice(0, 10);
|
||||
return (
|
||||
<form onSubmit={save} className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div>
|
||||
<label className="label" htmlFor="addr-type">Address</label>
|
||||
<select id="addr-type" className="input" value={form.addressType} onChange={e => setForm({ ...form, addressType: e.target.value as AddressType })}>
|
||||
{(Object.keys(ADDRESS_OPTIONS) as AddressType[]).map(k => <option key={k} value={k}>{ADDRESS_OPTIONS[k].label} ({ADDRESS_OPTIONS[k].price})</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="addr-domain">Domain</label><input id="addr-domain" className="input" value={form.domain} onChange={e => setForm({ ...form, domain: e.target.value })} placeholder={form.addressType === "crosscode" ? "hopefamily.crosscode.co.za" : "hopefamily.co.za"} /></div>
|
||||
{form.addressType !== "own_domain" && <div><label className="label" htmlFor="addr-price">Custom price (R/month)</label><input id="addr-price" className="input" inputMode="decimal" placeholder={ADDRESS_OPTIONS[form.addressType].price} value={form.custom} onChange={e => setForm({ ...form, custom: e.target.value })} /></div>}
|
||||
{form.addressType === "included" && <div><label className="label" htmlFor="addr-renews">Domain renews on</label><input id="addr-renews" type="date" className="input" value={form.domainRenewsOn} onChange={e => setForm({ ...form, domainRenewsOn: e.target.value })} /></div>}
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">{ADDRESS_OPTIONS[form.addressType].help} Charged once per invoice for all the church's products, never discounted.{form.addressType === "included" ? " You're emailed 30 days before the renewal date." : ""}</p>
|
||||
{due && <p className="rounded-lg bg-amber-50 p-2 text-sm text-amber-900">{c.domain || "The domain"} is due for renewal on {day(c.domainRenewsOn)}.</p>}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button className="btn-primary" disabled={busy}>Save address</button>
|
||||
{c.addressType === "included" && c.domainRenewsOn && <button type="button" className="btn-secondary" onClick={renewed}>Renewed</button>}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** One licence's billing: when it's charged from, a custom price, and a notice of licence change. */
|
||||
function LicenceBilling({ licence, plans, nextInvoiceDate, onSaved, setMsg }: { licence: BillingLicence; plans: Plan[]; nextInvoiceDate: string | null; onSaved: () => void; setMsg: (m: Msg) => void }) {
|
||||
const [form, setForm] = useState({ billedFrom: licence.billedFrom || "", custom: randInput(licence.customMonthlyCents) });
|
||||
const [change, setChange] = useState<{ toPlan: string; effectiveDate: string; price: string; reason: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const suggested = suggestedTier(licence, plans);
|
||||
const tier = plans.find(t => t.name === licence.plan);
|
||||
const name = PRODUCT_NAMES[licence.product];
|
||||
|
||||
if (!licence.billable) {
|
||||
return (
|
||||
<div className="rounded-lg border border-slate-200 p-4 text-sm">
|
||||
<span className="font-medium">{name}</span> <code className="ml-2 text-xs">{licence.key}</code>
|
||||
<span className="ml-2 text-slate-500">Free: comes with the church's other products, never invoiced.</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(`/api/admin/billing/licences/${licence.id}`, { method: "PUT", body: { billedFrom: form.billedFrom || null, customMonthlyCents: form.custom.trim() ? centsFrom(form.custom) : null } });
|
||||
setMsg({ type: "ok", text: form.billedFrom ? `${name}: charged from ${day(form.billedFrom)}.` : `${name}: not charged.` });
|
||||
onSaved();
|
||||
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
|
||||
};
|
||||
|
||||
const sendChange = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!change) return;
|
||||
if (!confirm(`Email ${name}: ${licence.plan} → ${change.toPlan} from ${day(change.effectiveDate)} to the church now?`)) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await api<{ change: LicenceChange; email: { ok: boolean; error: string | null } | null }>("/api/admin/billing/licence-changes", {
|
||||
method: "POST", body: { licenceId: licence.id, toPlan: change.toPlan, effectiveDate: change.effectiveDate, reason: change.reason, toMonthlyCents: change.price.trim() ? centsFrom(change.price) : null },
|
||||
});
|
||||
setMsg({ type: r.email?.ok ? "ok" : "err", text: r.email?.ok ? `Notice ${r.change.number} sent. The tier changes on ${day(r.change.effectiveDate)}.` : `Notice ${r.change.number} recorded but not emailed: ${r.email?.error}` });
|
||||
setChange(null);
|
||||
onSaved();
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); } finally { setBusy(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-slate-200 p-4">
|
||||
<div className="mb-3 flex flex-wrap items-baseline justify-between gap-2">
|
||||
<div><span className="font-medium">{name}</span> <code className="ml-2 text-xs">{licence.key}</code>{licence.url && <span className="ml-2 text-xs text-slate-500">{licence.url.replace(/^https?:\/\//, "")}</span>}</div>
|
||||
<div className="text-sm">
|
||||
{licence.product === "website" ? "Website" : <>Tier <strong>{licence.plan}</strong></>}
|
||||
{licence.customMonthlyCents != null ? ` at ${money(licence.customMonthlyCents)}/month` : tier?.monthly != null ? ` (R${tier.monthly}/month)` : ""}
|
||||
<span className="ml-2 text-xs text-slate-500">{reportText(licence)}{suggested && suggested.name !== licence.plan ? ` → ${suggested.name} at the next review` : ""}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<div>
|
||||
<label className="label" htmlFor={`from-${licence.id}`}>Charged from</label>
|
||||
<input id={`from-${licence.id}`} type="date" className="input" value={form.billedFrom} onChange={e => setForm({ ...form, billedFrom: e.target.value })} />
|
||||
<p className="mt-1 text-xs text-slate-500">{licence.billedUntil ? `Invoiced up to ${day(licence.billedUntil)}.` : "Not invoiced yet."} Blank: not charged (e.g. a trial).</p>
|
||||
</div>
|
||||
<div><label className="label" htmlFor={`custom-${licence.id}`}>Custom price (R/month)</label><input id={`custom-${licence.id}`} className="input" inputMode="decimal" placeholder="Tier price" value={form.custom} onChange={e => setForm({ ...form, custom: e.target.value })} /></div>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-slate-500">A product that starts part-way through a period is charged by the day up to the next period. A custom price replaces the tier's (e.g. Network); founding churches get 35% off it.</p>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button className="btn-primary" onClick={save} disabled={busy}>Save</button>
|
||||
{plans.length > 1 && !change && <button className="btn-secondary" onClick={() => setChange({ toPlan: suggested && suggested.name !== licence.plan ? suggested.name : "", effectiveDate: nextInvoiceDate || todayYmd(), price: "", reason: "" })}>Notice of licence change…</button>}
|
||||
</div>
|
||||
{change && (
|
||||
<form onSubmit={sendChange} className="mt-4 space-y-3 rounded-lg bg-slate-50 p-3">
|
||||
<div className="text-sm font-medium">Notice of licence change (emailed with a PDF)</div>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<div>
|
||||
<label className="label" htmlFor={`to-${licence.id}`}>New tier</label>
|
||||
<select id={`to-${licence.id}`} className="input" value={change.toPlan} onChange={e => setChange({ ...change, toPlan: e.target.value })} required>
|
||||
<option value="">Choose…</option>
|
||||
{plans.map(t => <option key={t.name} value={t.name} disabled={t.name === licence.plan}>{t.name}{t.monthly != null ? ` (R${t.monthly}/month)` : " (custom price)"}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div><label className="label" htmlFor={`eff-${licence.id}`}>Takes effect</label><input id={`eff-${licence.id}`} type="date" className="input" value={change.effectiveDate} onChange={e => setChange({ ...change, effectiveDate: e.target.value })} required /></div>
|
||||
<div><label className="label" htmlFor={`price-${licence.id}`}>New price (R/month, for a custom price)</label><input id={`price-${licence.id}`} className="input" inputMode="decimal" placeholder="Tier price" value={change.price} onChange={e => setChange({ ...change, price: e.target.value })} /></div>
|
||||
</div>
|
||||
<div><label className="label" htmlFor={`why-${licence.id}`}>Why (printed on the notice)</label><input id={`why-${licence.id}`} className="input" value={change.reason} onChange={e => setChange({ ...change, reason: e.target.value })} placeholder="e.g. As agreed on our call." /></div>
|
||||
<div className="flex gap-2"><button className="btn-primary" disabled={busy}>Send notice</button><button type="button" className="btn-secondary" onClick={() => setChange(null)}>Cancel</button></div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The next invoice as it would be drafted now: nothing is saved. */
|
||||
function NextInvoice({ customerId, version }: { customerId: string; version: string }) {
|
||||
const [p, setP] = useState<Preview | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
api<Preview>(`/api/admin/billing/customers/${customerId}/preview`).then(setP).catch(e => setErr(errorText(e)));
|
||||
}, [customerId, version]);
|
||||
if (err) return <p className="text-sm text-red-700">{err}</p>;
|
||||
if (!p) return null;
|
||||
if (!p.billed) return <p className="text-sm text-slate-500">Not billed: set the billing up above to see the next invoice.</p>;
|
||||
if (p.empty) return <p className="text-sm text-slate-500">Nothing to charge for the period from {day(p.invoice.periodStart)}: no product is charged yet.</p>;
|
||||
const inv = p.invoice;
|
||||
return (
|
||||
<div className="space-y-2 text-sm">
|
||||
<p className="text-slate-600">For {day(inv.periodStart)} – {day(inv.periodEnd)}, drafted 14 days before {day(inv.issueDate)}. As it stands today (prices, founding, what each product reports):</p>
|
||||
<table className="w-full">
|
||||
<tbody>
|
||||
{inv.lines.map((l, i) => (
|
||||
<tr key={i} className="border-t border-slate-100 first:border-0">
|
||||
<td className="py-1.5 pr-3">{l.description}{l.quantity !== 1 ? <span className="text-xs text-slate-500"> · {l.quantity} × {money(l.unitCents)}</span> : null}</td>
|
||||
<td className={`py-1.5 text-right tabular-nums ${l.amountCents < 0 ? "text-green-700" : ""}`}>{money(l.amountCents)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr className="border-t border-slate-300 font-semibold"><td className="py-1.5">Total</td><td className="py-1.5 text-right tabular-nums">{money(inv.totalCents)}</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
{inv.planChanges.length > 0 && <p className="text-sky-800">At this review: {inv.planChanges.map(pc => `${PRODUCT_NAMES[pc.product || "events"]} ${pc.from} → ${pc.to}`).join(", ")}.</p>}
|
||||
{inv.warnings.length > 0 && <ul className="list-disc pl-5 text-amber-800">{inv.warnings.map(w => <li key={w}>{w}</li>)}</ul>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Hub 2.13.0: how the church's invoices and payments can be sorted.
|
||||
const CUSTOMER_INVOICE_SORT = {
|
||||
number: { get: i => i.number, first: "desc" },
|
||||
date: { get: i => i.issueDate, first: "desc" },
|
||||
plan: { get: i => i.plan || "One-off" },
|
||||
total: { get: i => i.totalCents, first: "desc" },
|
||||
balance: { get: i => (i.status === "sent" ? i.balanceCents : null), first: "desc" },
|
||||
state: { get: i => i.state },
|
||||
} satisfies Record<string, SortColumn<Invoice>>;
|
||||
const CUSTOMER_PAYMENT_SORT = {
|
||||
received: { get: p => p.paidOn },
|
||||
amount: { get: p => p.amountCents },
|
||||
receipt: { get: p => p.receiptNumber },
|
||||
} satisfies Record<string, SortColumn<Payment>>;
|
||||
const NONE_INVOICES: Invoice[] = [];
|
||||
const NONE_PAYMENTS: Payment[] = [];
|
||||
|
||||
/** Customer page → Billing: founding, where invoices go, each licence's billing, statements, invoices, payments. */
|
||||
export function CustomerBilling({ customerId }: { customerId: string }) {
|
||||
const [c, setC] = useState<CustomerBillingData | null>(null);
|
||||
const [form, setForm] = useState({ founding: false, foundingSince: "", foundingNote: "", billingEmail: "", billingAddress: "" });
|
||||
const [stmt, setStmt] = useState({ from: yearAgo(), to: todayYmd(), email: "" });
|
||||
const [paying, setPaying] = useState(false);
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
|
||||
const load = useCallback(() => api<CustomerBillingData>(`/api/admin/billing/customers/${customerId}`).then(x => {
|
||||
setC(x);
|
||||
setForm({ founding: x.founding, foundingSince: x.foundingSince || "", foundingNote: x.foundingNote || "", billingEmail: x.billingEmail || "", billingAddress: x.billingAddress || "" });
|
||||
}).catch(e => setMsg({ type: "err", text: errorText(e) })), [customerId]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
const invoices = useSort(c?.invoices || NONE_INVOICES, CUSTOMER_INVOICE_SORT, { key: "date", dir: "desc" }, "customer-invoices");
|
||||
const payments = useSort(c?.payments || NONE_PAYMENTS, CUSTOMER_PAYMENT_SORT, { key: "received", dir: "desc" }, "customer-payments");
|
||||
|
||||
if (!c) return msg ? <div className="card text-sm text-red-700">{msg.text}</div> : null;
|
||||
|
||||
const saveDetails = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await api(`/api/admin/billing/customers/${customerId}`, { method: "PUT", body: { ...form, foundingSince: form.foundingSince || null } });
|
||||
setMsg({ type: "ok", text: "Billing details saved. Drafts already made keep their price; recalculate them if needed." });
|
||||
load();
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||
};
|
||||
const emailStatement = async () => {
|
||||
const to = stmt.email || c.sendsTo;
|
||||
if (!confirm(`Email the statement (${day(stmt.from)} – ${day(stmt.to)}) to ${to}?`)) return;
|
||||
try {
|
||||
const r = await api<{ message: string }>(`/api/admin/billing/customers/${customerId}/statement/email`, { method: "POST", body: { from: stmt.from, to: stmt.to, email: stmt.email || undefined } });
|
||||
setMsg({ type: "ok", text: r.message });
|
||||
load();
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||
};
|
||||
const pdf = (path: string) => openPdf(path).catch(e => setMsg({ type: "err", text: errorText(e) }));
|
||||
|
||||
return (
|
||||
<section id="billing" className="mt-8 space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="text-lg font-semibold">Billing</h2>
|
||||
<div className="text-sm">{c.balanceCents > 0 ? <>Owing <strong>{money(c.balanceCents)}</strong></> : "Nothing owing"}</div>
|
||||
</div>
|
||||
{msg && <div role="status" className={`rounded-lg border p-3 text-sm ${msg.type === "ok" ? "border-green-200 bg-green-50 text-green-800" : "border-red-200 bg-red-50 text-red-800"}`}>{msg.text}</div>}
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[1fr_2fr]">
|
||||
<form onSubmit={saveDetails} className="card space-y-3 self-start">
|
||||
<label className="flex items-center gap-2 font-medium"><input type="checkbox" checked={form.founding} onChange={e => setForm({ ...form, founding: e.target.checked, foundingSince: e.target.checked && !form.foundingSince ? todayYmd() : form.foundingSince })} /> <Star className="h-4 w-4 fill-amber-400 text-amber-400" /> Founding church (35% off)</label>
|
||||
{form.founding && (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div><label className="label" htmlFor="f-since">Founding since</label><input id="f-since" type="date" className="input" value={form.foundingSince} onChange={e => setForm({ ...form, foundingSince: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="f-note">Note</label><input id="f-note" className="input" value={form.foundingNote} onChange={e => setForm({ ...form, foundingNote: e.target.value })} placeholder="e.g. Founding church 3 of 10" /></div>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<EmailList id="b-email" label="Billing email" value={form.billingEmail} onChange={billingEmail => setForm({ ...form, billingEmail })} placeholder={c.sendsTo || "accounts@church.org"} />
|
||||
<p className="mt-1 text-xs text-slate-500">Invoices, statements and receipts go to every address here. Blank: the site's admin contact, then the customer's email. Now going to {c.sendsTo || "nobody (add one)"}.</p>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="b-addr">Postal address (on invoices)</label><textarea id="b-addr" className="input" rows={2} value={form.billingAddress} onChange={e => setForm({ ...form, billingAddress: e.target.value })} /></div>
|
||||
<button className="btn-secondary">Save billing details</button>
|
||||
</form>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="card space-y-3">
|
||||
<h3 className="font-semibold">Billing schedule</h3>
|
||||
<Schedule key={`${c.billingCycle}-${c.billingStart}-${c.nextInvoiceDate}-${c.reviewDate}`} c={c} onSaved={load} setMsg={setMsg} />
|
||||
</div>
|
||||
<div className="card space-y-3">
|
||||
<h3 className="font-semibold">Address</h3>
|
||||
<Address key={`${c.addressType}-${c.domain}-${c.addressCustomCents}-${c.domainRenewsOn}`} c={c} onSaved={load} setMsg={setMsg} />
|
||||
</div>
|
||||
<div className="card space-y-3">
|
||||
<h3 className="font-semibold">Products</h3>
|
||||
{c.licences.length === 0 ? <p className="text-sm text-slate-500">Generate a licence first.</p> : [...c.licences].filter(l => l.status !== "revoked").sort(byProduct).map(l => (
|
||||
<LicenceBilling key={`${l.id}-${l.plan}-${l.billedFrom}-${l.billedUntil}-${l.customMonthlyCents}`} licence={l} plans={c.plans[l.product] || []} nextInvoiceDate={c.nextInvoiceDate} onSaved={load} setMsg={setMsg} />
|
||||
))}
|
||||
</div>
|
||||
<div className="card space-y-3">
|
||||
<h3 className="font-semibold">Next invoice</h3>
|
||||
<NextInvoice customerId={customerId} version={JSON.stringify([c.founding, c.billingCycle, c.nextInvoiceDate, c.addressType, c.addressCustomCents, c.licences.map(l => [l.plan, l.billedFrom, l.billedUntil, l.customMonthlyCents, l.status])])} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card space-y-3">
|
||||
<h3 className="font-semibold">Statement</h3>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div><label className="label" htmlFor="s-from">From</label><input id="s-from" type="date" className="input" value={stmt.from} onChange={e => setStmt({ ...stmt, from: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="s-to">To</label><input id="s-to" type="date" className="input" value={stmt.to} onChange={e => setStmt({ ...stmt, to: e.target.value })} /></div>
|
||||
<div className="min-w-56 flex-1"><label className="label" htmlFor="s-email">Send to</label><input id="s-email" type="email" className="input" value={stmt.email} onChange={e => setStmt({ ...stmt, email: e.target.value })} placeholder={c.sendsTo || ""} /></div>
|
||||
<button className="btn-secondary" onClick={() => pdf(`/api/admin/billing/customers/${customerId}/statement.pdf?from=${stmt.from}&to=${stmt.to}`)}><FileText className="h-4 w-4" /> Open PDF</button>
|
||||
<button className="btn-primary" onClick={emailStatement}><Mail className="h-4 w-4" /> Email statement</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{paying && <RecordPayment customerId={customerId} onClose={() => setPaying(false)} onSaved={m => { setMsg(m); setPaying(false); load(); }} />}
|
||||
|
||||
<div className="card overflow-x-auto">
|
||||
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
|
||||
<h3 className="font-semibold">Invoices</h3>
|
||||
<div className="flex gap-2"><Link className="btn-secondary" href={`/billing/invoices/new?customer=${customerId}`}><Plus className="h-4 w-4" /> One-off invoice</Link><button className="btn-primary" onClick={() => setPaying(true)}><Plus className="h-4 w-4" /> Record payment</button></div>
|
||||
</div>
|
||||
{c.invoices.length === 0 ? <p className="text-sm text-slate-500">No invoices yet.</p> : (
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-left text-xs text-slate-500"><tr><SortTh sort={invoices.sort} k="number" className="py-2">Invoice</SortTh><SortTh sort={invoices.sort} k="date" className="py-2">Date</SortTh><SortTh sort={invoices.sort} k="plan" className="py-2">Tier</SortTh><SortTh sort={invoices.sort} k="total" className="py-2" right>Total</SortTh><SortTh sort={invoices.sort} k="balance" className="py-2" right>Balance</SortTh><SortTh sort={invoices.sort} k="state" className="py-2">State</SortTh></tr></thead>
|
||||
<tbody>{invoices.rows.map(i => (
|
||||
<tr key={i.id} className="border-t border-slate-100">
|
||||
<td className="py-2"><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link></td>
|
||||
<td className="py-2">{day(i.issueDate)}</td>
|
||||
<td className="py-2">{i.plan || "One-off"}{i.planChanges.length ? ` (from ${i.planChanges.map(pc => pc.from).join(", ")})` : ""}</td>
|
||||
<td className="py-2 text-right tabular-nums">{money(i.totalCents)}</td>
|
||||
<td className="py-2 text-right tabular-nums">{i.status === "sent" ? money(i.balanceCents) : "—"}</td>
|
||||
<td className="py-2"><StateBadge state={i.state} short /></td>
|
||||
</tr>
|
||||
))}</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<div className="card text-sm">
|
||||
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
|
||||
<h3 className="font-semibold">Payments</h3>
|
||||
{c.payments.length > 1 && <SortSelect sort={payments.sort} options={[["received", "desc", "Newest first"], ["received", "asc", "Oldest first"], ["amount", "desc", "Largest first"], ["amount", "asc", "Smallest first"], ["receipt", "desc", "Receipt number"]]} />}
|
||||
</div>
|
||||
{c.payments.length === 0 ? <p className="text-slate-500">None yet.</p> : payments.rows.map(p => (
|
||||
<div key={p.id} className="flex justify-between gap-3 border-t border-slate-100 py-2 first:border-0">
|
||||
<div>{p.receiptNumber} · {day(p.paidOn)}<div className="text-xs text-slate-500">{METHOD[p.method] || p.method}{p.invoice ? ` · ${p.invoice.number}` : " · on account"}{p.reference && p.reference !== p.invoice?.number ? ` · ${p.reference}` : ""}</div></div>
|
||||
<div className="text-right"><strong className="tabular-nums">{money(p.amountCents)}</strong><div><button className="text-xs text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/payments/${p.id}/pdf`)}>Receipt</button></div></div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="card text-sm">
|
||||
<h3 className="mb-2 font-semibold">Notices of licence change</h3>
|
||||
{c.licenceChanges.length === 0 ? <p className="text-slate-500">None yet.</p> : c.licenceChanges.map(ch => (
|
||||
<div key={ch.id} className="flex justify-between gap-3 border-t border-slate-100 py-2 first:border-0">
|
||||
<div>{ch.number}: {ch.fromPlan} → {ch.toPlan}<div className="text-xs text-slate-500">from {day(ch.effectiveDate)} · {ch.sentAt ? `sent ${fmtDate(ch.sentAt, false)}` : "not sent"}{ch.appliedAt ? " · in effect" : " · not yet in effect"}</div></div>
|
||||
<div className="flex shrink-0 gap-3 text-xs">
|
||||
<button className="text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/licence-changes/${ch.id}/pdf`)}>PDF</button>
|
||||
<button className="text-indigo-700 hover:underline" onClick={() => api<{ message: string }>(`/api/admin/billing/licence-changes/${ch.id}/resend`, { method: "POST" }).then(r => { setMsg({ type: "ok", text: r.message }); load(); }).catch(e => setMsg({ type: "err", text: errorText(e) }))}>Send again</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card text-sm">
|
||||
<h3 className="mb-2 font-semibold">Billing emails</h3>
|
||||
{c.emails.length === 0 ? <p className="text-slate-500">None yet.</p> : (
|
||||
<table className="w-full">
|
||||
<tbody>{c.emails.map(e => (
|
||||
<tr key={e.id} className="border-t border-slate-100 first:border-0">
|
||||
<td className="py-1.5 pr-3 whitespace-nowrap text-slate-500">{fmtDate(e.sentAt)}</td>
|
||||
<td className="py-1.5 pr-3">{EMAIL_KIND[e.kind] || e.kind}</td>
|
||||
<td className="py-1.5 pr-3">{e.subject}<div className="text-xs text-slate-500">to {e.to}</div></td>
|
||||
<td className={`py-1.5 ${e.error ? "text-red-700" : "text-green-700"}`}>{e.error ? `Failed: ${e.error}` : "Sent"}</td>
|
||||
</tr>
|
||||
))}</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { todayYmd, type Invoice } from "@/lib/billing";
|
||||
import { FormError, Modal } from "@/components/ui";
|
||||
import { LinesEditor, editTotal, fromEdit, type EditLine } from "./LinesEditor";
|
||||
|
||||
/**
|
||||
* Hub 2.14.0: a one-off invoice for one church (standby support, set-up…), made as a draft, in a
|
||||
* popup on the customer page. `/billing/invoices/new` is the same form for any church.
|
||||
*/
|
||||
export function OneOffInvoice({ customerId, onClose, onSaved }: { customerId: string; onClose: () => void; onSaved: (inv: Invoice) => void }) {
|
||||
const [form, setForm] = useState({ issueDate: todayYmd(), notes: "" });
|
||||
const [lines, setLines] = useState<EditLine[]>([{ description: "", quantity: "1", unit: "" }]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const dirty = !!form.notes || fromEdit(lines).length > 0;
|
||||
const save = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
onSaved(await api<Invoice>("/api/admin/billing/invoices", { method: "POST", body: { customerId, ...form, lines: fromEdit(lines) } }));
|
||||
} catch (err) { setError(errorText(err)); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<Modal title="One-off invoice" onClose={onClose} dirty={dirty} wide>
|
||||
<form onSubmit={save} className="space-y-4">
|
||||
<p className="text-sm text-slate-600">For anything outside the licence, like standby support for a big event. It's made as a draft for you to approve.</p>
|
||||
<div className="max-w-xs"><label className="label" htmlFor="oo-date">Invoice date</label><input id="oo-date" type="date" className="input" value={form.issueDate} onChange={e => setForm({ ...form, issueDate: e.target.value })} required /><p className="mt-1 text-xs text-slate-500">It goes out on this day once approved.</p></div>
|
||||
<LinesEditor lines={lines} onChange={setLines} />
|
||||
<div><label className="label" htmlFor="oo-notes">Notes (printed on the invoice)</label><textarea id="oo-notes" className="input" rows={2} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} /></div>
|
||||
<FormError error={error} />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button className="btn-primary" disabled={busy || (editTotal(lines) === 0 && !fromEdit(lines).length)}>{busy ? "Saving…" : "Create draft"}</button>
|
||||
<button type="button" className="btn-secondary" onClick={onClose}>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { X } from "lucide-react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { centsFrom, day, money, randInput, todayYmd, type Invoice } from "@/lib/billing";
|
||||
import { FormError, Modal } from "@/components/ui";
|
||||
|
||||
type Msg = { type: "ok" | "err"; text: string };
|
||||
|
||||
/**
|
||||
* Record money received: from which church, against which invoice (or on account), and the
|
||||
* receipt emailed unless unticked. `customerId` / `invoice` fix the choice (customer and invoice pages).
|
||||
* Hub 2.14.0: a popup.
|
||||
*/
|
||||
export function RecordPayment({ customers, customerId, invoice, onClose, onSaved }: {
|
||||
customers?: { id: string; name: string }[];
|
||||
@@ -31,6 +32,7 @@ export function RecordPayment({ customers, customerId, invoice, onClose, onSaved
|
||||
const [open, setOpen] = useState<Invoice[]>(invoice ? [invoice] : []);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const dirty = (!invoice && !!form.amount) || !!form.notes || form.reference !== (invoice?.number || "");
|
||||
|
||||
// The church's invoices that still owe something.
|
||||
useEffect(() => {
|
||||
@@ -61,11 +63,11 @@ export function RecordPayment({ customers, customerId, invoice, onClose, onSaved
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={save} className="card space-y-3 border-indigo-200">
|
||||
<div className="flex items-center justify-between"><h2 className="font-semibold">Record a payment</h2><button type="button" onClick={onClose} aria-label="Close" className="text-slate-400 hover:text-slate-700"><X className="h-4 w-4" /></button></div>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Modal title="Record a payment" onClose={onClose} dirty={dirty}>
|
||||
<form onSubmit={save} className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{!invoice && !customerId && (
|
||||
<div className="lg:col-span-2">
|
||||
<div className="sm:col-span-2">
|
||||
<label className="label" htmlFor="pay-customer">Church</label>
|
||||
<select id="pay-customer" className="input" value={form.customerId} onChange={e => setForm({ ...form, customerId: e.target.value, invoiceId: "" })} required>
|
||||
<option value="">Choose…</option>
|
||||
@@ -74,7 +76,7 @@ export function RecordPayment({ customers, customerId, invoice, onClose, onSaved
|
||||
</div>
|
||||
)}
|
||||
{!invoice && (
|
||||
<div className="lg:col-span-2">
|
||||
<div className="sm:col-span-2">
|
||||
<label className="label" htmlFor="pay-invoice">For invoice</label>
|
||||
<select id="pay-invoice" className="input" value={form.invoiceId} onChange={e => pickInvoice(e.target.value)} disabled={!form.customerId}>
|
||||
<option value="">On account (no invoice)</option>
|
||||
@@ -91,11 +93,12 @@ export function RecordPayment({ customers, customerId, invoice, onClose, onSaved
|
||||
</select>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="pay-ref">Their reference</label><input id="pay-ref" className="input" value={form.reference} onChange={e => setForm({ ...form, reference: e.target.value })} /></div>
|
||||
<div className="sm:col-span-2 lg:col-span-4"><label className="label" htmlFor="pay-notes">Notes (printed on the receipt)</label><input id="pay-notes" className="input" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} /></div>
|
||||
<div className="sm:col-span-2"><label className="label" htmlFor="pay-notes">Notes (printed on the receipt)</label><input id="pay-notes" className="input" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} /></div>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.sendReceipt} onChange={e => setForm({ ...form, sendReceipt: e.target.checked })} /> Email the receipt (PDF) to the church</label>
|
||||
{error && <p className="text-sm text-red-700">{error}</p>}
|
||||
<FormError error={error} />
|
||||
<div className="flex gap-2"><button className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Record payment"}</button><button type="button" className="btn-secondary" onClick={onClose}>Cancel</button></div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { PRODUCT_NAMES, type Product } from "@/lib/products";
|
||||
import type { Licence } from "@/lib/types";
|
||||
import { FormError, Modal } from "@/components/ui";
|
||||
import { ModalButtons } from "./ReadCard";
|
||||
import { endOfDay, type Done } from "./shared";
|
||||
|
||||
/** A new licence for a product the church doesn't have yet. Accounts comes free with the first other one. */
|
||||
export function AddProductModal({ customerId, available, onClose, onDone }: { customerId: string; available: Product[]; onClose: () => void; onDone: Done }) {
|
||||
const form0 = { product: available.find(p => p !== "accounts") || available[0], expiresAt: "", graceDays: "14" };
|
||||
const [form, setForm] = useState(form0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const save = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const l = await api<Licence & { accountsLicence: Licence | null }>(`/api/admin/customers/${customerId}/licences`, {
|
||||
method: "POST", body: { product: form.product, expiresAt: endOfDay(form.expiresAt), graceDays: form.graceDays },
|
||||
});
|
||||
onDone({
|
||||
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}.` : ""),
|
||||
});
|
||||
} catch (err) { setError(errorText(err)); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<Modal title="Add a product" onClose={onClose} dirty={form.expiresAt !== "" || form.graceDays !== "14"}>
|
||||
<form onSubmit={save} className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<div>
|
||||
<label className="label" htmlFor="new-product">Product</label>
|
||||
<select id="new-product" className="input" value={form.product} onChange={e => setForm({ ...form, product: e.target.value as Product })}>
|
||||
{available.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="new-exp">Expires (optional)</label><input id="new-exp" type="date" className="input" value={form.expiresAt} onChange={e => setForm({ ...form, expiresAt: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="new-grace">Grace (days)</label><input id="new-grace" type="number" min={0} max={90} className="input" value={form.graceDays} onChange={e => setForm({ ...form, graceDays: e.target.value })} /></div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">One licence per product (revoke one to replace it). Accounts is free and is created with the first other product.</p>
|
||||
<FormError error={error} />
|
||||
<ModalButtons busy={busy} onCancel={onClose} label="Generate licence" />
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { centsFrom, day, money, randInput } from "@/lib/billing";
|
||||
import { FormError, Modal } from "@/components/ui";
|
||||
import { Field, Fields, ModalButtons, ReadCard } from "./ReadCard";
|
||||
import { ADDRESS_OPTIONS, changed, type AddressType, type CustomerBillingData, type Done } from "./shared";
|
||||
|
||||
/** Whether the included domain is due for renewal within 30 days. */
|
||||
const renewalDue = (b: CustomerBillingData) => b.addressType === "included" && !!b.domainRenewsOn && b.domainRenewsOn <= new Date(Date.now() + 30 * 864e5).toISOString().slice(0, 10);
|
||||
|
||||
/**
|
||||
* The church's address: one for all its products, billed once per invoice and never discounted.
|
||||
* The popup is opened from here or from the Address tile in the header, so the page holds it.
|
||||
*/
|
||||
export function AddressCard({ b, onEdit, onDone }: { b: CustomerBillingData; onEdit: () => void; onDone: Done }) {
|
||||
const renewed = async () => {
|
||||
if (!confirm(`Mark ${b.domain || "the domain"} as renewed? The renewal date moves on a year.`)) return;
|
||||
try {
|
||||
const r = await api<{ message: string }>(`/api/admin/billing/customers/${b.id}/domain-renewed`, { method: "POST" });
|
||||
onDone({ type: "ok", text: r.message });
|
||||
} catch (err) { onDone({ type: "err", text: errorText(err) }); }
|
||||
};
|
||||
return (
|
||||
<ReadCard title="Address" onEdit={onEdit}
|
||||
actions={b.addressType === "included" && b.domainRenewsOn ? <button type="button" className="btn-secondary px-2.5 py-1.5" onClick={renewed}>Renewed</button> : null}>
|
||||
<Fields>
|
||||
<Field label="Type">{ADDRESS_OPTIONS[b.addressType].label}</Field>
|
||||
<Field label="Domain">{b.domain}</Field>
|
||||
<Field label="Price">{b.addressMonthlyCents ? `${money(b.addressMonthlyCents)} / month` : "Free"}{b.addressCustomCents != null ? " (custom)" : ""}</Field>
|
||||
{b.addressType === "included" && <Field label="Domain renews on">{b.domainRenewsOn && day(b.domainRenewsOn)}</Field>}
|
||||
</Fields>
|
||||
{renewalDue(b) && <p className="rounded-lg bg-amber-50 p-2 text-sm text-amber-900">{b.domain || "The domain"} is due for renewal on {day(b.domainRenewsOn)}.</p>}
|
||||
</ReadCard>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddressModal({ b, onClose, onDone }: { b: CustomerBillingData; onClose: () => void; onDone: Done }) {
|
||||
const form0 = { addressType: b.addressType, domain: b.domain || "", custom: randInput(b.addressCustomCents), domainRenewsOn: b.domainRenewsOn || "" };
|
||||
const [form, setForm] = useState(form0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const save = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/api/admin/billing/customers/${b.id}`, { method: "PUT", body: { addressType: form.addressType, domain: form.domain || null, addressCustomCents: form.custom.trim() ? centsFrom(form.custom) : null, domainRenewsOn: form.domainRenewsOn || null } });
|
||||
onDone({ type: "ok", text: `Address saved: ${ADDRESS_OPTIONS[form.addressType].label}.` });
|
||||
} catch (err) { setError(errorText(err)); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<Modal title="Address" onClose={onClose} dirty={changed(form, form0)}>
|
||||
<form onSubmit={save} className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label" htmlFor="addr-type">Address</label>
|
||||
<select id="addr-type" className="input" value={form.addressType} onChange={e => setForm({ ...form, addressType: e.target.value as AddressType })}>
|
||||
{(Object.keys(ADDRESS_OPTIONS) as AddressType[]).map(k => <option key={k} value={k}>{ADDRESS_OPTIONS[k].label} ({ADDRESS_OPTIONS[k].price})</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="addr-domain">Domain</label><input id="addr-domain" className="input" value={form.domain} onChange={e => setForm({ ...form, domain: e.target.value })} placeholder={form.addressType === "crosscode" ? "hopefamily.crosscode.co.za" : "hopefamily.co.za"} /></div>
|
||||
{form.addressType !== "own_domain" && <div><label className="label" htmlFor="addr-price">Custom price (R/month)</label><input id="addr-price" className="input" inputMode="decimal" placeholder={ADDRESS_OPTIONS[form.addressType].price} value={form.custom} onChange={e => setForm({ ...form, custom: e.target.value })} /></div>}
|
||||
{form.addressType === "included" && <div><label className="label" htmlFor="addr-renews">Domain renews on</label><input id="addr-renews" type="date" className="input" value={form.domainRenewsOn} onChange={e => setForm({ ...form, domainRenewsOn: e.target.value })} /></div>}
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">{ADDRESS_OPTIONS[form.addressType].help} Charged once per invoice for all the church's products, never discounted.{form.addressType === "included" ? " You're emailed 30 days before the renewal date." : ""}</p>
|
||||
<FormError error={error} />
|
||||
<ModalButtons busy={busy} onCancel={onClose} />
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { money } from "@/lib/billing";
|
||||
import type { Customer } from "@/lib/types";
|
||||
import { FormError, Modal } from "@/components/ui";
|
||||
import { Field, Fields, ModalButtons, ReadCard } from "./ReadCard";
|
||||
import { changed, type Done } from "./shared";
|
||||
|
||||
/** The church's AI allowance, shared by all its sites (Hub 2.0). Hub 2.14.0: its own card; the page holds the popup (the AI tile opens it too). */
|
||||
export function AiCard({ c, onEdit }: { c: Customer; onEdit: () => void }) {
|
||||
return (
|
||||
<ReadCard title="AI allowance" onEdit={onEdit}>
|
||||
<Fields>
|
||||
<Field label="Monthly cap">{c.aiMonthlyCapCents > 0 ? `${money(c.aiMonthlyCapCents)} / month` : "Off (no AI buttons)"}</Field>
|
||||
<Field label="Markup">{c.aiMarkupPercent == null ? "Default (Settings → AI)" : `${c.aiMarkupPercent}%`}</Field>
|
||||
</Fields>
|
||||
</ReadCard>
|
||||
);
|
||||
}
|
||||
|
||||
export function AiModal({ c, onClose, onDone }: { c: Customer; onClose: () => void; onDone: Done }) {
|
||||
const form0 = { aiRand: String(c.aiMonthlyCapCents / 100), aiMarkup: c.aiMarkupPercent == null ? "" : String(c.aiMarkupPercent) };
|
||||
const [form, setForm] = useState(form0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const save = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/api/admin/customers/${c.id}`, {
|
||||
method: "PUT",
|
||||
body: { aiMonthlyCapCents: Math.round((parseFloat(form.aiRand) || 0) * 100), aiMarkupPercent: form.aiMarkup.trim() === "" ? null : form.aiMarkup },
|
||||
});
|
||||
onDone({ type: "ok", text: "AI allowance saved. The church's sites pick it up with their next heartbeat (within 15 minutes)." });
|
||||
} catch (err) { setError(errorText(err)); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<Modal title="AI allowance" onClose={onClose} dirty={changed(form, form0)}>
|
||||
<form onSubmit={save} className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label" htmlFor="ai-cap">AI cap (R / month)</label>
|
||||
<input id="ai-cap" type="number" min={0} step="1" className="input" value={form.aiRand} onChange={e => setForm({ ...form, aiRand: e.target.value })} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label" htmlFor="ai-markup">AI markup (%)</label>
|
||||
<input id="ai-markup" type="number" min={0} max={500} step="1" className="input" placeholder="Default" value={form.aiMarkup} onChange={e => setForm({ ...form, aiMarkup: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">The AI allowance is the church's, shared by all its sites: 0 = off (no AI buttons). Counted in charged rand. A blank markup uses the default (Settings → AI).</p>
|
||||
<FormError error={error} />
|
||||
<ModalButtons busy={busy} onCancel={onClose} />
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import Link from "next/link";
|
||||
import { ArrowLeft, FilePlus, KeyRound, Plus, Star } from "lucide-react";
|
||||
import { day, money } from "@/lib/billing";
|
||||
import { fmtDate } from "@/lib/format";
|
||||
import { PRODUCT_NAMES, byProduct } from "@/lib/products";
|
||||
import type { Customer } from "@/lib/types";
|
||||
import { Menu, Stat } from "@/components/ui";
|
||||
import { ADDRESS_OPTIONS, type CustomerBillingData, type Preview } from "./shared";
|
||||
|
||||
/** What the header's tiles open, and its buttons. */
|
||||
export type HeaderAction = "payment" | "oneoff" | "add" | "preview" | "address" | "ai" | "history";
|
||||
|
||||
/**
|
||||
* Hub 2.14.0: always at the top of the customer page: who the church is, what it has, what it
|
||||
* owes and when it's next invoiced, and the everyday actions.
|
||||
*/
|
||||
export function CustomerHeader({ c, b, preview, canAdd, onAction, onArchive }: {
|
||||
c: Customer; b: CustomerBillingData | null; preview: Preview | null; canAdd: boolean;
|
||||
onAction: (a: HeaderAction) => void; onArchive: (archive: boolean) => void;
|
||||
}) {
|
||||
const open = [...c.licences].filter(l => l.status !== "revoked").sort(byProduct);
|
||||
const soon = Date.now() + 30 * 864e5;
|
||||
const expired = open.some(l => l.expiresAt && new Date(l.expiresAt).getTime() < Date.now());
|
||||
const productsTone = open.some(l => l.status === "suspended") || expired ? "red" : open.some(l => l.expiresAt && new Date(l.expiresAt).getTime() < soon) ? "amber" : undefined;
|
||||
const suspended = open.filter(l => l.status === "suspended").map(l => PRODUCT_NAMES[l.product]);
|
||||
const overdue = b?.invoices.filter(i => i.state === "overdue") || [];
|
||||
const estimate = preview?.billed && !preview.empty ? preview.invoice.totalCents : null;
|
||||
|
||||
return (
|
||||
<header className="mb-6 space-y-4">
|
||||
<Link href="/customers" className="inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Customers</Link>
|
||||
<div className="flex flex-wrap items-end justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h1 className="flex flex-wrap items-center gap-2 text-2xl font-semibold">
|
||||
<span className="break-words">{c.name}</span>
|
||||
{b?.founding && <span title="Founding church (35% off)" className="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-xs font-medium text-amber-800 ring-1 ring-inset ring-amber-200"><Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" /> Founding</span>}
|
||||
{c.archivedAt && <span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-600 ring-1 ring-inset ring-slate-200">Archived {fmtDate(c.archivedAt, false)}</span>}
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-slate-500">Customer since {fmtDate(c.createdAt, false)}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button type="button" className="btn-primary" onClick={() => onAction("payment")}><Plus className="h-4 w-4" /> Record payment</button>
|
||||
<button type="button" className="btn-secondary" onClick={() => onAction("oneoff")}><FilePlus className="h-4 w-4" /> One-off invoice</button>
|
||||
{canAdd && <button type="button" className="btn-secondary" onClick={() => onAction("add")}><KeyRound className="h-4 w-4" /> Add product</button>}
|
||||
<Menu label="More actions for this customer" items={[
|
||||
c.archivedAt ? { label: "Restore", onClick: () => onArchive(false) } : { label: "Archive…", onClick: () => onArchive(true) },
|
||||
]} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3 lg:grid-cols-5">
|
||||
<Stat label="Products" small tone={productsTone}
|
||||
value={open.length ? open.map(l => PRODUCT_NAMES[l.product]).join(" · ") : "None yet"}
|
||||
sub={suspended.length ? `${suspended.join(", ")} suspended` : expired ? "A licence has expired" : productsTone === "amber" ? "A licence expires within 30 days" : undefined} />
|
||||
<Stat label="Owing" tone={overdue.length ? "red" : undefined} onClick={() => onAction("history")}
|
||||
value={b ? money(b.balanceCents) : "…"}
|
||||
sub={overdue.length ? `${overdue.length} overdue` : b && b.balanceCents <= 0 ? "Nothing owing" : undefined} />
|
||||
<Stat label="Next invoice" small onClick={() => onAction("preview")}
|
||||
value={!b ? "…" : b.billingCycle === "none" ? "Not billed" : b.nextInvoiceDate ? day(b.nextInvoiceDate) : "Not set"}
|
||||
sub={b && b.billingCycle !== "none" ? (estimate != null ? `About ${money(estimate)} · see it` : preview?.billed && preview.empty ? "Nothing to charge yet" : "See it") : "Set up billing"} />
|
||||
<Stat label="Address" small onClick={() => onAction("address")}
|
||||
value={b ? ADDRESS_OPTIONS[b.addressType].label : "…"}
|
||||
sub={b?.domain || "No domain yet"} />
|
||||
<Stat label="AI" small onClick={() => onAction("ai")}
|
||||
value={c.aiMonthlyCapCents > 0 ? `${money(c.aiMonthlyCapCents)} / month` : "Off"}
|
||||
sub={c.aiMarkupPercent == null ? "Default markup" : `${c.aiMarkupPercent}% markup`} />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { Star } from "lucide-react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { day, todayYmd } from "@/lib/billing";
|
||||
import type { Customer } from "@/lib/types";
|
||||
import { EmailList, emailsOf } from "@/components/EmailList";
|
||||
import { FormError, Modal } from "@/components/ui";
|
||||
import { Field, Fields, ModalButtons, ReadCard } from "./ReadCard";
|
||||
import { changed, type CustomerBillingData, type Done } from "./shared";
|
||||
|
||||
/**
|
||||
* Hub 2.14.0: the church's details in one place: who to talk to, and where invoices go. Before,
|
||||
* the contact details and the billing details were two forms far apart on the page.
|
||||
*/
|
||||
export function DetailsCard({ c, b, onDone }: { c: Customer; b: CustomerBillingData; onDone: Done }) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
return (
|
||||
<ReadCard title="Details" onEdit={() => setEditing(true)}>
|
||||
<Fields>
|
||||
<Field label="Contact person">{c.contactName}</Field>
|
||||
<Field label="Phone">{c.phone}</Field>
|
||||
<Field label="Email">{emailsOf(c.email).join(", ")}</Field>
|
||||
<Field label="Billing email">
|
||||
{b.billingEmail ? emailsOf(b.billingEmail).join(", ") : b.sendsTo ? <span className="text-slate-500">Blank: going to {b.sendsTo}</span> : <span className="text-red-700">Nobody yet: add one</span>}
|
||||
</Field>
|
||||
<Field label="Postal address (on invoices)" wide>{b.billingAddress && <span className="whitespace-pre-line">{b.billingAddress}</span>}</Field>
|
||||
<Field label="Founding church" wide>
|
||||
{b.founding
|
||||
? <span className="inline-flex items-center gap-1"><Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" /> Yes, 35% off{b.foundingSince ? ` since ${day(b.foundingSince)}` : ""}{b.foundingNote ? ` · ${b.foundingNote}` : ""}</span>
|
||||
: "No"}
|
||||
</Field>
|
||||
<Field label="Notes" wide>{c.notes && <span className="whitespace-pre-line">{c.notes}</span>}</Field>
|
||||
</Fields>
|
||||
{editing && <DetailsModal c={c} b={b} onClose={() => setEditing(false)} onDone={m => { setEditing(false); onDone(m); }} />}
|
||||
</ReadCard>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailsModal({ c, b, onClose, onDone }: { c: Customer; b: CustomerBillingData; onClose: () => void; onDone: Done }) {
|
||||
const contact0 = { name: c.name, contactName: c.contactName || "", email: c.email || "", phone: c.phone || "", notes: c.notes || "" };
|
||||
const billing0 = { founding: b.founding, foundingSince: b.foundingSince || "", foundingNote: b.foundingNote || "", billingEmail: b.billingEmail || "", billingAddress: b.billingAddress || "" };
|
||||
const [contact, setContact] = useState(contact0);
|
||||
const [billing, setBilling] = useState(billing0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const contactChanged = changed(contact, contact0);
|
||||
const billingChanged = changed(billing, billing0);
|
||||
|
||||
const save = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!contactChanged && !billingChanged) { onClose(); return; }
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
// Two endpoints, as before; only the one whose fields changed is called.
|
||||
if (contactChanged) await api(`/api/admin/customers/${c.id}`, { method: "PUT", body: contact });
|
||||
if (billingChanged) await api(`/api/admin/billing/customers/${c.id}`, { method: "PUT", body: { ...billing, foundingSince: billing.foundingSince || null } });
|
||||
onDone({ type: "ok", text: billingChanged ? "Details saved. Drafts already made keep their price; recalculate them if needed." : "Details saved." });
|
||||
} catch (err) { setError(errorText(err)); } finally { setBusy(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal title="Edit details" onClose={onClose} dirty={contactChanged || billingChanged}>
|
||||
<form onSubmit={save} className="space-y-4">
|
||||
<div className="space-y-3">
|
||||
<div><label className="label" htmlFor="d-name">Name</label><input id="d-name" className="input" value={contact.name} onChange={e => setContact({ ...contact, name: e.target.value })} required /></div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div><label className="label" htmlFor="d-contact">Contact person</label><input id="d-contact" className="input" value={contact.contactName} onChange={e => setContact({ ...contact, contactName: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="d-phone">Phone</label><input id="d-phone" className="input" value={contact.phone} onChange={e => setContact({ ...contact, phone: e.target.value })} /></div>
|
||||
</div>
|
||||
<EmailList id="d-email" label="Email" value={contact.email} onChange={email => setContact({ ...contact, email })} placeholder="office@church.org" />
|
||||
<div><label className="label" htmlFor="d-notes">Notes</label><textarea id="d-notes" className="input" rows={3} value={contact.notes} onChange={e => setContact({ ...contact, notes: e.target.value })} placeholder="Anything worth remembering" /></div>
|
||||
</div>
|
||||
|
||||
<fieldset className="space-y-3 border-t border-slate-200 pt-4">
|
||||
<legend className="sr-only">Billing</legend>
|
||||
<div>
|
||||
<EmailList id="d-bemail" label="Billing email" value={billing.billingEmail} onChange={billingEmail => setBilling({ ...billing, billingEmail })} placeholder={b.sendsTo || "accounts@church.org"} />
|
||||
<p className="mt-1 text-xs text-slate-500">Invoices, statements and receipts go to every address here. Blank: the site's admin contact, then the customer's email. Now going to {b.sendsTo || "nobody (add one)"}.</p>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="d-addr">Postal address (on invoices)</label><textarea id="d-addr" className="input" rows={2} value={billing.billingAddress} onChange={e => setBilling({ ...billing, billingAddress: e.target.value })} /></div>
|
||||
<label className="flex items-center gap-2 text-sm font-medium"><input type="checkbox" checked={billing.founding} onChange={e => setBilling({ ...billing, founding: e.target.checked, foundingSince: e.target.checked && !billing.foundingSince ? todayYmd() : billing.foundingSince })} /> <Star className="h-4 w-4 fill-amber-400 text-amber-400" /> Founding church (35% off)</label>
|
||||
{billing.founding && (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div><label className="label" htmlFor="d-since">Founding since</label><input id="d-since" type="date" className="input" value={billing.foundingSince} onChange={e => setBilling({ ...billing, foundingSince: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="d-fnote">Note</label><input id="d-fnote" className="input" value={billing.foundingNote} onChange={e => setBilling({ ...billing, foundingNote: e.target.value })} placeholder="e.g. Founding church 3 of 10" /></div>
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
<FormError error={error} />
|
||||
<ModalButtons busy={busy} onCancel={onClose} />
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { api, errorText, openPdf } from "@/lib/api";
|
||||
import { EMAIL_KIND, METHOD, StateBadge, day, money, type BillingEmail, type Invoice, type LicenceChange, type Payment } from "@/lib/billing";
|
||||
import { fmtDate } from "@/lib/format";
|
||||
import { SortSelect, SortTh, useSort, type SortColumn } from "@/lib/sort";
|
||||
import type { CustomerBillingData, Done } from "./shared";
|
||||
|
||||
type View = "all" | "invoices" | "payments" | "notices" | "emails";
|
||||
const VIEWS: [View, string][] = [["all", "Everything"], ["invoices", "Invoices"], ["payments", "Payments"], ["notices", "Notices of licence change"], ["emails", "Billing emails"]];
|
||||
const VIEW_KEY = "customer-history-view";
|
||||
|
||||
/**
|
||||
* Hub 2.14.0: the church's invoices, payments, notices and billing emails. "Everything" is one
|
||||
* timeline, newest first; each kind on its own is its table, sortable as before.
|
||||
*/
|
||||
export function History({ b, onDone }: { b: CustomerBillingData; onDone: Done }) {
|
||||
const [view, setView] = useState<View>("all");
|
||||
useEffect(() => {
|
||||
try { const v = localStorage.getItem(VIEW_KEY); if (VIEWS.some(([k]) => k === v)) setView(v as View); } catch { /* not remembered */ }
|
||||
}, []);
|
||||
const pick = (v: View) => { setView(v); try { localStorage.setItem(VIEW_KEY, v); } catch { /* not remembered */ } };
|
||||
const pdf = (path: string) => openPdf(path).catch(e => onDone({ type: "err", text: errorText(e) }));
|
||||
const resend = (ch: LicenceChange) => api<{ message: string }>(`/api/admin/billing/licence-changes/${ch.id}/resend`, { method: "POST" })
|
||||
.then(r => onDone({ type: "ok", text: r.message })).catch(e => onDone({ type: "err", text: errorText(e) }));
|
||||
const count: Record<View, number> = { all: 0, invoices: b.invoices.length, payments: b.payments.length, notices: b.licenceChanges.length, emails: b.emails.length };
|
||||
count.all = count.invoices + count.payments + count.notices + count.emails;
|
||||
|
||||
return (
|
||||
<section className="card space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="font-semibold">History</h2>
|
||||
<div role="group" aria-label="Show" className="flex flex-wrap gap-1">
|
||||
{VIEWS.map(([k, label]) => (
|
||||
<button key={k} type="button" aria-pressed={view === k} onClick={() => pick(k)}
|
||||
className={`rounded-full px-3 py-1 text-xs ring-1 ring-inset ${view === k ? "bg-indigo-600 text-white ring-indigo-600" : "bg-white text-slate-600 ring-slate-300 hover:bg-slate-50"}`}>
|
||||
{label} <span className={view === k ? "text-indigo-100" : "text-slate-400"}>{count[k]}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{view === "all" && <Timeline b={b} pdf={pdf} resend={resend} />}
|
||||
{view === "invoices" && <InvoiceList invoices={b.invoices} />}
|
||||
{view === "payments" && <PaymentList payments={b.payments} pdf={pdf} />}
|
||||
{view === "notices" && <NoticeList changes={b.licenceChanges} pdf={pdf} resend={resend} />}
|
||||
{view === "emails" && <EmailLog emails={b.emails} />}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type Entry =
|
||||
| { kind: "invoice"; at: string; item: Invoice }
|
||||
| { kind: "payment"; at: string; item: Payment }
|
||||
| { kind: "notice"; at: string; item: LicenceChange }
|
||||
| { kind: "email"; at: string; item: BillingEmail };
|
||||
const KIND_LABEL: Record<Entry["kind"], string> = { invoice: "Invoice", payment: "Payment", notice: "Notice", email: "Email" };
|
||||
const KIND_TONE: Record<Entry["kind"], string> = {
|
||||
invoice: "bg-indigo-50 text-indigo-700", payment: "bg-green-50 text-green-700", notice: "bg-sky-50 text-sky-700", email: "bg-slate-100 text-slate-600",
|
||||
};
|
||||
/** Dates and times sort together: a bare date counts as midday South African time. */
|
||||
const when = (d: string) => (d.length === 10 ? `${d}T10:00:00.000Z` : new Date(d).toISOString());
|
||||
|
||||
function Timeline({ b, pdf, resend }: { b: CustomerBillingData; pdf: (p: string) => void; resend: (ch: LicenceChange) => void }) {
|
||||
const entries = useMemo<Entry[]>(() => [
|
||||
...b.invoices.map(i => ({ kind: "invoice" as const, at: when(i.issueDate), item: i })),
|
||||
...b.payments.map(p => ({ kind: "payment" as const, at: when(p.paidOn), item: p })),
|
||||
...b.licenceChanges.map(ch => ({ kind: "notice" as const, at: when(ch.sentAt || ch.createdAt), item: ch })),
|
||||
...b.emails.map(e => ({ kind: "email" as const, at: when(e.sentAt), item: e })),
|
||||
].sort((x, y) => (x.at < y.at ? 1 : x.at > y.at ? -1 : 0)), [b]);
|
||||
if (!entries.length) return <p className="text-sm text-slate-500">Nothing yet.</p>;
|
||||
return (
|
||||
<>
|
||||
<ol className="divide-y divide-slate-100 text-sm">
|
||||
{entries.map(e => (
|
||||
<li key={`${e.kind}-${e.item.id}`} className="grid grid-cols-[5.5rem_1fr] gap-x-3 gap-y-1 py-2 sm:grid-cols-[6.5rem_4.5rem_1fr_auto] sm:items-baseline">
|
||||
<span className="whitespace-nowrap text-slate-500">{day(e.at.slice(0, 10))}</span>
|
||||
<span className={`w-fit rounded px-1.5 py-0.5 text-xs font-medium ${KIND_TONE[e.kind]}`}>{KIND_LABEL[e.kind]}</span>
|
||||
<div className="col-span-2 min-w-0 sm:col-span-1"><EntryText e={e} /></div>
|
||||
<div className="col-span-2 flex flex-wrap items-baseline justify-end gap-3 text-right sm:col-span-1"><EntryEnd e={e} pdf={pdf} resend={resend} /></div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{b.emails.length >= 50 && <p className="text-xs text-slate-500">Showing the last 50 billing emails.</p>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function EntryText({ e }: { e: Entry }) {
|
||||
switch (e.kind) {
|
||||
case "invoice": {
|
||||
const i = e.item;
|
||||
return <><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link> <span className="text-slate-600">{i.plan || "One-off"}{i.planChanges.length ? ` (from ${i.planChanges.map(pc => pc.from).join(", ")})` : ""}</span></>;
|
||||
}
|
||||
case "payment": {
|
||||
const p = e.item;
|
||||
return <>{p.receiptNumber} <span className="text-slate-600">· {METHOD[p.method] || p.method}{p.invoice ? ` · ${p.invoice.number}` : " · on account"}{p.reference && p.reference !== p.invoice?.number ? ` · ${p.reference}` : ""}</span></>;
|
||||
}
|
||||
case "notice": {
|
||||
const ch = e.item;
|
||||
return <>{ch.number}: {ch.fromPlan} → {ch.toPlan} <span className="text-slate-600">· from {day(ch.effectiveDate)}{ch.sentAt ? "" : " · not sent"}{ch.appliedAt ? " · in effect" : " · not yet in effect"}</span></>;
|
||||
}
|
||||
case "email": {
|
||||
const m = e.item;
|
||||
return <>{EMAIL_KIND[m.kind] || m.kind}: {m.subject} <span className="break-all text-xs text-slate-500">to {m.to}</span></>;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function EntryEnd({ e, pdf, resend }: { e: Entry; pdf: (p: string) => void; resend: (ch: LicenceChange) => void }) {
|
||||
switch (e.kind) {
|
||||
case "invoice": return <><span className="tabular-nums">{money(e.item.totalCents)}</span><StateBadge state={e.item.state} short /></>;
|
||||
case "payment": return <><strong className="tabular-nums text-green-700">{money(e.item.amountCents)}</strong><button className="text-xs text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/payments/${e.item.id}/pdf`)}>Receipt</button></>;
|
||||
case "notice": return <><button className="text-xs text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/licence-changes/${e.item.id}/pdf`)}>PDF</button><button className="text-xs text-indigo-700 hover:underline" onClick={() => resend(e.item)}>Send again</button></>;
|
||||
case "email": return <span className={`text-xs ${e.item.error ? "text-red-700" : "text-green-700"}`}>{e.item.error ? `Failed: ${e.item.error}` : "Sent"}</span>;
|
||||
}
|
||||
}
|
||||
|
||||
// Hub 2.13.0: how the church's invoices and payments can be sorted.
|
||||
const CUSTOMER_INVOICE_SORT = {
|
||||
number: { get: i => i.number, first: "desc" },
|
||||
date: { get: i => i.issueDate, first: "desc" },
|
||||
plan: { get: i => i.plan || "One-off" },
|
||||
total: { get: i => i.totalCents, first: "desc" },
|
||||
balance: { get: i => (i.status === "sent" ? i.balanceCents : null), first: "desc" },
|
||||
state: { get: i => i.state },
|
||||
} satisfies Record<string, SortColumn<Invoice>>;
|
||||
const CUSTOMER_PAYMENT_SORT = {
|
||||
received: { get: p => p.paidOn },
|
||||
amount: { get: p => p.amountCents },
|
||||
receipt: { get: p => p.receiptNumber },
|
||||
} satisfies Record<string, SortColumn<Payment>>;
|
||||
|
||||
export function InvoiceList({ invoices: all }: { invoices: Invoice[] }) {
|
||||
const invoices = useSort(all, CUSTOMER_INVOICE_SORT, { key: "date", dir: "desc" }, "customer-invoices");
|
||||
if (!all.length) return <p className="text-sm text-slate-500">No invoices yet.</p>;
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-left text-xs text-slate-500"><tr><SortTh sort={invoices.sort} k="number" className="py-2 pr-3">Invoice</SortTh><SortTh sort={invoices.sort} k="date" className="py-2 pr-3">Date</SortTh><SortTh sort={invoices.sort} k="plan" className="py-2 pr-3">Tier</SortTh><SortTh sort={invoices.sort} k="total" className="py-2 pr-3" right>Total</SortTh><SortTh sort={invoices.sort} k="balance" className="py-2 pr-3" right>Balance</SortTh><SortTh sort={invoices.sort} k="state" className="py-2">State</SortTh></tr></thead>
|
||||
<tbody>{invoices.rows.map(i => (
|
||||
<tr key={i.id} className="border-t border-slate-100">
|
||||
<td className="py-2 pr-3"><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link></td>
|
||||
<td className="whitespace-nowrap py-2 pr-3">{day(i.issueDate)}</td>
|
||||
<td className="py-2 pr-3">{i.plan || "One-off"}{i.planChanges.length ? ` (from ${i.planChanges.map(pc => pc.from).join(", ")})` : ""}</td>
|
||||
<td className="py-2 pr-3 text-right tabular-nums">{money(i.totalCents)}</td>
|
||||
<td className="py-2 pr-3 text-right tabular-nums">{i.status === "sent" ? money(i.balanceCents) : "—"}</td>
|
||||
<td className="py-2"><StateBadge state={i.state} short /></td>
|
||||
</tr>
|
||||
))}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PaymentList({ payments: all, pdf }: { payments: Payment[]; pdf: (p: string) => void }) {
|
||||
const payments = useSort(all, CUSTOMER_PAYMENT_SORT, { key: "received", dir: "desc" }, "customer-payments");
|
||||
if (!all.length) return <p className="text-sm text-slate-500">None yet.</p>;
|
||||
return (
|
||||
<div className="text-sm">
|
||||
{all.length > 1 && <div className="mb-1 flex justify-end"><SortSelect sort={payments.sort} options={[["received", "desc", "Newest first"], ["received", "asc", "Oldest first"], ["amount", "desc", "Largest first"], ["amount", "asc", "Smallest first"], ["receipt", "desc", "Receipt number"]]} /></div>}
|
||||
{payments.rows.map(p => (
|
||||
<div key={p.id} className="flex justify-between gap-3 border-t border-slate-100 py-2 first:border-0">
|
||||
<div>{p.receiptNumber} · {day(p.paidOn)}<div className="text-xs text-slate-500">{METHOD[p.method] || p.method}{p.invoice ? ` · ${p.invoice.number}` : " · on account"}{p.reference && p.reference !== p.invoice?.number ? ` · ${p.reference}` : ""}</div></div>
|
||||
<div className="text-right"><strong className="tabular-nums">{money(p.amountCents)}</strong><div><button className="text-xs text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/payments/${p.id}/pdf`)}>Receipt</button></div></div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function NoticeList({ changes, pdf, resend }: { changes: LicenceChange[]; pdf: (p: string) => void; resend: (ch: LicenceChange) => void }) {
|
||||
if (!changes.length) return <p className="text-sm text-slate-500">None yet.</p>;
|
||||
return (
|
||||
<div className="text-sm">
|
||||
{changes.map(ch => (
|
||||
<div key={ch.id} className="flex justify-between gap-3 border-t border-slate-100 py-2 first:border-0">
|
||||
<div>{ch.number}: {ch.fromPlan} → {ch.toPlan}<div className="text-xs text-slate-500">from {day(ch.effectiveDate)} · {ch.sentAt ? `sent ${fmtDate(ch.sentAt, false)}` : "not sent"}{ch.appliedAt ? " · in effect" : " · not yet in effect"}</div></div>
|
||||
<div className="flex shrink-0 gap-3 text-xs">
|
||||
<button className="text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/licence-changes/${ch.id}/pdf`)}>PDF</button>
|
||||
<button className="text-indigo-700 hover:underline" onClick={() => resend(ch)}>Send again</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmailLog({ emails }: { emails: BillingEmail[] }) {
|
||||
if (!emails.length) return <p className="text-sm text-slate-500">None yet.</p>;
|
||||
return (
|
||||
<div className="overflow-x-auto text-sm">
|
||||
<table className="w-full">
|
||||
<tbody>{emails.map(e => (
|
||||
<tr key={e.id} className="border-t border-slate-100 first:border-0">
|
||||
<td className="whitespace-nowrap py-1.5 pr-3 text-slate-500">{fmtDate(e.sentAt)}</td>
|
||||
<td className="py-1.5 pr-3">{EMAIL_KIND[e.kind] || e.kind}</td>
|
||||
<td className="py-1.5 pr-3">{e.subject}<div className="break-all text-xs text-slate-500">to {e.to}</div></td>
|
||||
<td className={`py-1.5 ${e.error ? "text-red-700" : "text-green-700"}`}>{e.error ? `Failed: ${e.error}` : "Sent"}</td>
|
||||
</tr>
|
||||
))}</tbody>
|
||||
</table>
|
||||
{emails.length >= 50 && <p className="mt-2 text-xs text-slate-500">Showing the last 50.</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import React from "react";
|
||||
import { day, money } from "@/lib/billing";
|
||||
import { PRODUCT_NAMES } from "@/lib/products";
|
||||
import { Modal } from "@/components/ui";
|
||||
import type { Preview } from "./shared";
|
||||
|
||||
/** The next invoice as it would be drafted now: nothing is saved. Opened from the Next invoice tile. */
|
||||
export function NextInvoiceModal({ preview, error, onClose, onSchedule }: { preview: Preview | null; error: string | null; onClose: () => void; onSchedule: () => void }) {
|
||||
return (
|
||||
<Modal title="Next invoice" onClose={onClose} wide>
|
||||
<div className="space-y-3 text-sm">
|
||||
<NextInvoiceBody preview={preview} error={error} />
|
||||
<div className="flex flex-wrap gap-2 pt-1">
|
||||
<button type="button" className="btn-secondary" onClick={onSchedule}>Billing schedule…</button>
|
||||
<button type="button" className="btn-secondary" onClick={onClose}>Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function NextInvoiceBody({ preview: p, error }: { preview: Preview | null; error: string | null }) {
|
||||
if (error) return <p className="text-red-700">{error}</p>;
|
||||
if (!p) return <p className="text-slate-400">Loading…</p>;
|
||||
if (!p.billed) return <p className="text-slate-500">Not billed: set up the billing schedule to see the next invoice.</p>;
|
||||
if (p.empty) return <p className="text-slate-500">Nothing to charge for the period from {day(p.invoice.periodStart)}: no product is charged yet.</p>;
|
||||
const inv = p.invoice;
|
||||
return (
|
||||
<>
|
||||
<p className="text-slate-600">For {day(inv.periodStart)} – {day(inv.periodEnd)}, drafted 14 days before {day(inv.issueDate)}. As it stands today (prices, founding, what each product reports):</p>
|
||||
<table className="w-full">
|
||||
<tbody>
|
||||
{inv.lines.map((l, i) => (
|
||||
<tr key={i} className="border-t border-slate-100 first:border-0">
|
||||
<td className="py-1.5 pr-3">{l.description}{l.quantity !== 1 ? <span className="text-xs text-slate-500"> · {l.quantity} × {money(l.unitCents)}</span> : null}</td>
|
||||
<td className={`py-1.5 text-right tabular-nums ${l.amountCents < 0 ? "text-green-700" : ""}`}>{money(l.amountCents)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr className="border-t border-slate-300 font-semibold"><td className="py-1.5">Total</td><td className="py-1.5 text-right tabular-nums">{money(inv.totalCents)}</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
{inv.planChanges.length > 0 && <p className="text-sky-800">At this review: {inv.planChanges.map(pc => `${PRODUCT_NAMES[pc.product || "events"]} ${pc.from} → ${pc.to}`).join(", ")}.</p>}
|
||||
{inv.warnings.length > 0 && <ul className="list-disc pl-5 text-amber-800">{inv.warnings.map(w => <li key={w}>{w}</li>)}</ul>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Copy, KeyRound, Pencil } from "lucide-react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { centsFrom, day, money, randInput, todayYmd, type LicenceChange } from "@/lib/billing";
|
||||
import { ago, fmtDate } from "@/lib/format";
|
||||
import { KEY_WHERE, PRODUCT_NAMES } from "@/lib/products";
|
||||
import { PLANS_BY_PRODUCT } from "@/lib/tiers";
|
||||
import type { Licence, LicenceStatus } from "@/lib/types";
|
||||
import { Badge, FormError, Menu, Modal } from "@/components/ui";
|
||||
import { ModalButtons } from "./ReadCard";
|
||||
import { changed, dateInput, endOfDay, reportText, suggestedTier, type BillingLicence, type Done, type Plan } from "./shared";
|
||||
|
||||
const HEARTBEAT = "The site picks it up with its next heartbeat (within 15 minutes).";
|
||||
|
||||
/**
|
||||
* Hub 2.14.0: one card per product, joining what used to be two: the licence (tier, expiry, grace,
|
||||
* notes) and its billing (charged from, custom price). Suspend, revoke and release are in the ⋯ menu.
|
||||
*/
|
||||
export function ProductCard({ licence, billing, plans, nextInvoiceDate, onDone }: {
|
||||
licence: Licence; billing: BillingLicence | undefined; plans: Plan[]; nextInvoiceDate: string | null; onDone: Done;
|
||||
}) {
|
||||
const [open, setOpen] = useState<"edit" | "notice" | null>(null);
|
||||
const name = PRODUCT_NAMES[licence.product];
|
||||
const revoked = licence.status === "revoked";
|
||||
const billed = !!billing?.billable && !revoked;
|
||||
const tier = plans.find(t => t.name === licence.plan);
|
||||
const suggested = billing && billed ? suggestedTier(billing, plans) : null;
|
||||
const done: Done = m => { setOpen(null); onDone(m); };
|
||||
|
||||
const setStatus = async (status: LicenceStatus) => {
|
||||
const text = status === "active"
|
||||
? `Reactivate this ${name} licence?`
|
||||
: `${status === "revoked" ? "Revoke" : "Suspend"} this ${name} licence? The site becomes read-only after its next heartbeat (tickets still scan, data can still be exported).`;
|
||||
if (!confirm(text)) return;
|
||||
try {
|
||||
await api(`/api/admin/licences/${licence.id}`, { method: "PUT", body: { status } });
|
||||
onDone({ type: "ok", text: `${name}: ${status === "active" ? "active again" : status}. ${HEARTBEAT}` });
|
||||
} catch (e) { onDone({ type: "err", text: errorText(e) }); }
|
||||
};
|
||||
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" });
|
||||
onDone({ type: "ok", text: `${name}: released from ${licence.install?.url}.` });
|
||||
} catch (e) { onDone({ type: "err", text: errorText(e) }); }
|
||||
};
|
||||
|
||||
const price = billing?.customMonthlyCents != null ? `${money(billing.customMonthlyCents)}/month (custom)` : tier?.monthly != null ? `R${tier.monthly}/month` : null;
|
||||
const facts = licence.product === "accounts"
|
||||
? ["Free: comes with the church's other products"]
|
||||
: [
|
||||
licence.product === "website" ? "Website" : `Tier ${licence.plan}`,
|
||||
price,
|
||||
billed ? (billing?.billedFrom ? `charged from ${day(billing.billedFrom)}` : "not charged") : null,
|
||||
];
|
||||
facts.push(licence.expiresAt ? `expires ${fmtDate(licence.expiresAt, false)}` : "expires never", `grace ${licence.graceDays} days`);
|
||||
|
||||
return (
|
||||
<article className={`card space-y-2 ${revoked ? "bg-slate-50 opacity-80" : ""}`}>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<KeyRound className="h-4 w-4 text-slate-400" />
|
||||
<h3 className="font-semibold">{name}</h3>
|
||||
<code className="text-sm font-semibold tracking-wide">{licence.key}</code>
|
||||
<button type="button" className="text-xs text-indigo-600 hover:underline" onClick={() => navigator.clipboard?.writeText(licence.key)} aria-label={`Copy the ${name} key`}><Copy className="inline h-3.5 w-3.5" /> Copy</button>
|
||||
<span className="ml-auto"><Badge value={licence.status} /></span>
|
||||
</div>
|
||||
<p className="text-sm text-slate-600">
|
||||
{licence.install
|
||||
? <><Link href={`/installs/${licence.install.id}`} className="break-all text-indigo-700 hover:underline">{licence.install.url.replace(/^https?:\/\//, "")}</Link> · heartbeat {ago(licence.install.lastHeartbeatAt)}</>
|
||||
: revoked ? "Not in use." : `Not used yet: enter this key in ${KEY_WHERE[licence.product]}.`}
|
||||
</p>
|
||||
<p className="text-sm">{facts.filter(Boolean).join(" · ")}</p>
|
||||
{billed && billing && (
|
||||
<p className="text-xs text-slate-500">
|
||||
{reportText(billing)}{suggested && suggested.name !== licence.plan ? ` → ${suggested.name} at the next review` : ""}
|
||||
{billing.billedUntil ? ` · invoiced up to ${day(billing.billedUntil)}` : billing.billedFrom ? " · not invoiced yet" : ""}
|
||||
</p>
|
||||
)}
|
||||
{licence.notes && <p className="text-sm italic text-slate-600">{licence.notes}</p>}
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 pt-1">
|
||||
<span className="mr-auto text-xs text-slate-400">Created {fmtDate(licence.createdAt, false)}</span>
|
||||
{billed && plans.length > 1 && <button type="button" className="btn-secondary" onClick={() => setOpen("notice")}>Notice of change…</button>}
|
||||
<button type="button" className="btn-secondary" onClick={() => setOpen("edit")}><Pencil className="h-3.5 w-3.5" /> Edit</button>
|
||||
<Menu label={`More actions for ${name}`} items={[
|
||||
licence.status !== "active" && { label: "Reactivate", onClick: () => setStatus("active") },
|
||||
licence.status === "active" && { label: "Suspend…", onClick: () => setStatus("suspended"), danger: true },
|
||||
!revoked && { label: "Revoke…", onClick: () => setStatus("revoked"), danger: true },
|
||||
!!licence.install && { label: "Release from site…", onClick: release, danger: true },
|
||||
]} />
|
||||
</div>
|
||||
{open === "edit" && <EditProduct licence={licence} billing={billed ? billing : undefined} onClose={() => setOpen(null)} onDone={done} />}
|
||||
{open === "notice" && billing && (
|
||||
<NoticeModal licence={billing} plans={plans} initialPlan={suggested && suggested.name !== licence.plan ? suggested.name : ""} nextInvoiceDate={nextInvoiceDate} onClose={() => setOpen(null)} onDone={done} />
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
/** One popup, one Save: the licence fields and the billing fields, each sent only if changed. */
|
||||
function EditProduct({ licence, billing, onClose, onDone }: { licence: Licence; billing: BillingLicence | undefined; onClose: () => void; onDone: Done }) {
|
||||
const lic0 = { plan: licence.plan, expiresAt: dateInput(licence.expiresAt), graceDays: String(licence.graceDays), notes: licence.notes || "" };
|
||||
const bill0 = { billedFrom: billing?.billedFrom || "", custom: randInput(billing?.customMonthlyCents) };
|
||||
const [lic, setLic] = useState(lic0);
|
||||
const [bill, setBill] = useState(bill0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const name = PRODUCT_NAMES[licence.product];
|
||||
const plans = PLANS_BY_PRODUCT[licence.product];
|
||||
const licChanged = changed(lic, lic0);
|
||||
const billChanged = !!billing && changed(bill, bill0);
|
||||
|
||||
const save = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!licChanged && !billChanged) { onClose(); return; }
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const said: string[] = [];
|
||||
if (licChanged) {
|
||||
await api(`/api/admin/licences/${licence.id}`, { method: "PUT", body: { plan: lic.plan, expiresAt: endOfDay(lic.expiresAt), graceDays: lic.graceDays, notes: lic.notes } });
|
||||
said.push(`Licence saved. ${HEARTBEAT}`);
|
||||
}
|
||||
if (billChanged && billing) {
|
||||
await api(`/api/admin/billing/licences/${billing.id}`, { method: "PUT", body: { billedFrom: bill.billedFrom || null, customMonthlyCents: bill.custom.trim() ? centsFrom(bill.custom) : null } });
|
||||
said.push(bill.billedFrom ? `Charged from ${day(bill.billedFrom)}.` : "Not charged.");
|
||||
}
|
||||
onDone({ type: "ok", text: `${name}: ${said.join(" ")}` });
|
||||
} catch (err) { setError(errorText(err)); } finally { setBusy(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal title={`Edit ${name}`} onClose={onClose} dirty={licChanged || billChanged}>
|
||||
<form onSubmit={save} className="space-y-4">
|
||||
<section className="space-y-3">
|
||||
<h3 className="text-sm font-semibold text-slate-700">Licence</h3>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<div>
|
||||
<label className="label" htmlFor="p-plan">Tier</label>
|
||||
{licence.product === "accounts" ? (
|
||||
<input id="p-plan" className="input" value="Included" disabled />
|
||||
) : (
|
||||
<select id="p-plan" className="input" value={lic.plan} onChange={e => setLic({ ...lic, plan: e.target.value })}>
|
||||
{!plans.includes(lic.plan) && <option value={lic.plan}>{lic.plan}</option>}
|
||||
{plans.map(p => <option key={p} value={p}>{p}</option>)}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<label className="label" htmlFor="p-exp">Expires</label>
|
||||
<input id="p-exp" type="date" className="input" value={lic.expiresAt} onChange={e => setLic({ ...lic, expiresAt: e.target.value })} />
|
||||
<p className="mt-1 text-xs text-slate-500">{lic.expiresAt ? "" : "No end date"}</p>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="p-grace">Grace (days)</label><input id="p-grace" type="number" min={0} max={90} className="input" value={lic.graceDays} onChange={e => setLic({ ...lic, graceDays: e.target.value })} /></div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">{licence.product === "accounts" ? "Free: comes with the church's other products." : "The tier is shown on the church's Licence page and priced on its invoices."}</p>
|
||||
<div><label className="label" htmlFor="p-notes">Notes</label><input id="p-notes" className="input" value={lic.notes} onChange={e => setLic({ ...lic, notes: e.target.value })} placeholder="Anything worth remembering about this licence" /></div>
|
||||
</section>
|
||||
|
||||
{billing && (
|
||||
<section className="space-y-3 border-t border-slate-200 pt-4">
|
||||
<h3 className="text-sm font-semibold text-slate-700">Billing</h3>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label" htmlFor="p-from">Charged from</label>
|
||||
<input id="p-from" type="date" className="input" value={bill.billedFrom} onChange={e => setBill({ ...bill, billedFrom: e.target.value })} />
|
||||
<p className="mt-1 text-xs text-slate-500">{billing.billedUntil ? `Invoiced up to ${day(billing.billedUntil)}.` : "Not invoiced yet."} Blank: not charged (e.g. a trial).</p>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="p-custom">Custom price (R/month)</label><input id="p-custom" className="input" inputMode="decimal" placeholder="Tier price" value={bill.custom} onChange={e => setBill({ ...bill, custom: e.target.value })} /></div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">A product that starts part-way through a period is charged by the day up to the next period. A custom price replaces the tier's (e.g. Network); founding churches get 35% off it.</p>
|
||||
</section>
|
||||
)}
|
||||
<FormError error={error} />
|
||||
<ModalButtons busy={busy} onCancel={onClose} />
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/** A notice of licence change, emailed to the church with a PDF. */
|
||||
function NoticeModal({ licence, plans, initialPlan, nextInvoiceDate, onClose, onDone }: {
|
||||
licence: BillingLicence; plans: Plan[]; initialPlan: string; nextInvoiceDate: string | null; onClose: () => void; onDone: Done;
|
||||
}) {
|
||||
const form0 = { toPlan: initialPlan, effectiveDate: nextInvoiceDate || todayYmd(), price: "", reason: "" };
|
||||
const [change, setChange] = useState(form0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const name = PRODUCT_NAMES[licence.product];
|
||||
const send = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!confirm(`Email ${name}: ${licence.plan} → ${change.toPlan} from ${day(change.effectiveDate)} to the church now?`)) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const r = await api<{ change: LicenceChange; email: { ok: boolean; error: string | null } | null }>("/api/admin/billing/licence-changes", {
|
||||
method: "POST", body: { licenceId: licence.id, toPlan: change.toPlan, effectiveDate: change.effectiveDate, reason: change.reason, toMonthlyCents: change.price.trim() ? centsFrom(change.price) : null },
|
||||
});
|
||||
onDone({ type: r.email?.ok ? "ok" : "err", text: r.email?.ok ? `Notice ${r.change.number} sent. The tier changes on ${day(r.change.effectiveDate)}.` : `Notice ${r.change.number} recorded but not emailed: ${r.email?.error}` });
|
||||
} catch (err) { setError(errorText(err)); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<Modal title={`${name}: notice of licence change`} onClose={onClose} dirty={changed(change, form0)}>
|
||||
<form onSubmit={send} className="space-y-3">
|
||||
<p className="text-sm text-slate-600">Now on <strong>{licence.plan}</strong>. The notice is emailed to the church with a PDF; the tier changes on the date it takes effect.</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label" htmlFor="n-to">New tier</label>
|
||||
<select id="n-to" className="input" value={change.toPlan} onChange={e => setChange({ ...change, toPlan: e.target.value })} required>
|
||||
<option value="">Choose…</option>
|
||||
{plans.map(t => <option key={t.name} value={t.name} disabled={t.name === licence.plan}>{t.name}{t.monthly != null ? ` (R${t.monthly}/month)` : " (custom price)"}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="n-eff">Takes effect</label><input id="n-eff" type="date" className="input" value={change.effectiveDate} onChange={e => setChange({ ...change, effectiveDate: e.target.value })} required /></div>
|
||||
<div className="sm:col-span-2"><label className="label" htmlFor="n-price">New price (R/month, for a custom price)</label><input id="n-price" className="input" inputMode="decimal" placeholder="Tier price" value={change.price} onChange={e => setChange({ ...change, price: e.target.value })} /></div>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="n-why">Why (printed on the notice)</label><input id="n-why" className="input" value={change.reason} onChange={e => setChange({ ...change, reason: e.target.value })} placeholder="e.g. As agreed on our call." /></div>
|
||||
<FormError error={error} />
|
||||
<ModalButtons busy={busy} onCancel={onClose} label="Send notice" />
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import React from "react";
|
||||
import { Pencil } from "lucide-react";
|
||||
|
||||
/** A card that shows settings as text, with an Edit button that opens their popup. */
|
||||
export function ReadCard({ title, onEdit, editLabel = "Edit", actions, children }: {
|
||||
title: React.ReactNode; onEdit?: () => void; editLabel?: string; actions?: React.ReactNode; children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="card space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="font-semibold">{title}</h2>
|
||||
<div className="flex gap-2">
|
||||
{actions}
|
||||
{onEdit && <button type="button" className="btn-secondary px-2.5 py-1.5" onClick={onEdit}><Pencil className="h-3.5 w-3.5" /> {editLabel}</button>}
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** One "label: value" row of a read view; a blank value shows as a dash. */
|
||||
export function Field({ label, children, wide }: { label: string; children: React.ReactNode; wide?: boolean }) {
|
||||
const empty = children == null || children === "" || children === false;
|
||||
return (
|
||||
<div className={wide ? "sm:col-span-2" : ""}>
|
||||
<dt className="text-xs text-slate-500">{label}</dt>
|
||||
<dd className={`mt-0.5 break-words text-sm ${empty ? "text-slate-400" : "text-slate-900"}`}>{empty ? "—" : children}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Fields({ children }: { children: React.ReactNode }) {
|
||||
return <dl className="grid gap-3 sm:grid-cols-2">{children}</dl>;
|
||||
}
|
||||
|
||||
/** Save and Cancel at the foot of a popup form. */
|
||||
export function ModalButtons({ busy, onCancel, label = "Save" }: { busy: boolean; onCancel: () => void; label?: string }) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2 pt-1">
|
||||
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : label}</button>
|
||||
<button type="button" className="btn-secondary" onClick={onCancel}>Cancel</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { CYCLE, day, type BillingCycle } from "@/lib/billing";
|
||||
import { FormError, Modal } from "@/components/ui";
|
||||
import { Field, Fields, ModalButtons, ReadCard } from "./ReadCard";
|
||||
import { changed, type CustomerBillingData, type Done } from "./shared";
|
||||
|
||||
/** The church's billing schedule: one for all its products. The page holds the popup (the Next invoice popup opens it too). */
|
||||
export function ScheduleCard({ b, onEdit }: { b: CustomerBillingData; onEdit: () => void }) {
|
||||
const off = b.billingCycle === "none";
|
||||
return (
|
||||
<ReadCard title="Billing schedule" onEdit={onEdit}>
|
||||
<Fields>
|
||||
<Field label="Billing">{CYCLE[b.billingCycle]}</Field>
|
||||
{!off && <Field label="Billing started">{b.billingStart && day(b.billingStart)}</Field>}
|
||||
{!off && <Field label="Next invoice">{b.nextInvoiceDate && day(b.nextInvoiceDate)}</Field>}
|
||||
{!off && <Field label="Next tier review">{b.reviewDate && day(b.reviewDate)}</Field>}
|
||||
</Fields>
|
||||
</ReadCard>
|
||||
);
|
||||
}
|
||||
|
||||
export function ScheduleModal({ b, onClose, onDone }: { b: CustomerBillingData; onClose: () => void; onDone: Done }) {
|
||||
const form0 = { billingCycle: b.billingCycle, billingStart: b.billingStart || "", nextInvoiceDate: b.nextInvoiceDate || "", reviewDate: b.reviewDate || "" };
|
||||
const [form, setForm] = useState(form0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const off = form.billingCycle === "none";
|
||||
const save = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/api/admin/billing/customers/${b.id}`, { method: "PUT", body: { billingCycle: form.billingCycle, billingStart: form.billingStart || null, nextInvoiceDate: form.nextInvoiceDate || null, reviewDate: form.reviewDate || null } });
|
||||
onDone({ type: "ok", text: off ? "Saved: this church isn't billed." : "Billing saved. The next draft, for all the church's products, is made 14 days before the next invoice date." });
|
||||
} catch (err) { setError(errorText(err)); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<Modal title="Billing schedule" onClose={onClose} dirty={changed(form, form0)}>
|
||||
<form onSubmit={save} className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label" htmlFor="cycle">Billing</label>
|
||||
<select id="cycle" className="input" value={form.billingCycle} onChange={e => setForm({ ...form, billingCycle: e.target.value as BillingCycle })}>
|
||||
{(Object.keys(CYCLE) as BillingCycle[]).map(k => <option key={k} value={k}>{CYCLE[k]}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="start">Billing started</label><input id="start" type="date" className="input" value={form.billingStart} onChange={e => setForm({ ...form, billingStart: e.target.value })} disabled={off} /></div>
|
||||
<div><label className="label" htmlFor="next">Next invoice</label><input id="next" type="date" className="input" value={form.nextInvoiceDate} onChange={e => setForm({ ...form, nextInvoiceDate: e.target.value })} disabled={off} /></div>
|
||||
<div><label className="label" htmlFor="review">Next tier review</label><input id="review" type="date" className="input" value={form.reviewDate} onChange={e => setForm({ ...form, reviewDate: e.target.value })} disabled={off} /></div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">One invoice covers all the church's products, in advance, on the same day of the month as billing started. Leave the next invoice and review blank to start from the billing date and review a year later. Starting billing charges the products that aren't charged yet from the billing date; a product added later starts after its free month.</p>
|
||||
<FormError error={error} />
|
||||
<ModalButtons busy={busy} onCancel={onClose} />
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import React from "react";
|
||||
import Link from "next/link";
|
||||
import { ago } from "@/lib/format";
|
||||
import { PRODUCT_NAMES, byProduct } from "@/lib/products";
|
||||
import type { Customer } from "@/lib/types";
|
||||
import { ReadCard } from "./ReadCard";
|
||||
|
||||
/** The church's sites: where each product runs and when it last checked in. */
|
||||
export function SitesCard({ c }: { c: Customer }) {
|
||||
const sites = [...c.installs].sort((a, b) => (a.releasedAt ? 1 : 0) - (b.releasedAt ? 1 : 0) || byProduct(a, b));
|
||||
return (
|
||||
<ReadCard title="Sites">
|
||||
{sites.length === 0 ? <p className="text-sm text-slate-500">No site has registered yet: enter a product's licence key in its setup.</p> : (
|
||||
<ul className="divide-y divide-slate-100 text-sm">
|
||||
{sites.map(s => (
|
||||
<li key={s.id} className={`flex flex-wrap items-baseline justify-between gap-x-3 gap-y-0.5 py-2 first:pt-0 last:pb-0 ${s.releasedAt ? "text-slate-400" : ""}`}>
|
||||
<div className="min-w-0">
|
||||
<span className="font-medium">{PRODUCT_NAMES[s.product]}</span>{" "}
|
||||
<Link href={`/installs/${s.id}`} className="break-all text-indigo-700 hover:underline">{s.url.replace(/^https?:\/\//, "")}</Link>
|
||||
</div>
|
||||
<span className="text-xs text-slate-500">{s.releasedAt ? "released" : `${s.version ? `${s.version} · ` : ""}heartbeat ${ago(s.lastHeartbeatAt)}`}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</ReadCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { FileText, Mail } from "lucide-react";
|
||||
import { api, errorText, openPdf } from "@/lib/api";
|
||||
import { day, todayYmd } from "@/lib/billing";
|
||||
import type { CustomerBillingData, Done } from "./shared";
|
||||
|
||||
const yearAgo = () => { const d = new Date(`${todayYmd()}T00:00:00Z`); d.setUTCFullYear(d.getUTCFullYear() - 1); d.setUTCDate(d.getUTCDate() + 1); return d.toISOString().slice(0, 10); };
|
||||
|
||||
/** A statement for a period: open the PDF, or email it to the church. */
|
||||
export function Statement({ b, onDone }: { b: CustomerBillingData; onDone: Done }) {
|
||||
const [stmt, setStmt] = useState({ from: yearAgo(), to: todayYmd(), email: "" });
|
||||
const emailStatement = async () => {
|
||||
const to = stmt.email || b.sendsTo;
|
||||
if (!confirm(`Email the statement (${day(stmt.from)} – ${day(stmt.to)}) to ${to}?`)) return;
|
||||
try {
|
||||
const r = await api<{ message: string }>(`/api/admin/billing/customers/${b.id}/statement/email`, { method: "POST", body: { from: stmt.from, to: stmt.to, email: stmt.email || undefined } });
|
||||
onDone({ type: "ok", text: r.message });
|
||||
} catch (err) { onDone({ type: "err", text: errorText(err) }); }
|
||||
};
|
||||
const pdf = () => openPdf(`/api/admin/billing/customers/${b.id}/statement.pdf?from=${stmt.from}&to=${stmt.to}`).catch(e => onDone({ type: "err", text: errorText(e) }));
|
||||
return (
|
||||
<section className="card space-y-3">
|
||||
<h2 className="font-semibold">Statement</h2>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div><label className="label" htmlFor="s-from">From</label><input id="s-from" type="date" className="input" value={stmt.from} onChange={e => setStmt({ ...stmt, from: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="s-to">To</label><input id="s-to" type="date" className="input" value={stmt.to} onChange={e => setStmt({ ...stmt, to: e.target.value })} /></div>
|
||||
<div className="min-w-0 flex-1 basis-56"><label className="label" htmlFor="s-email">Send to</label><input id="s-email" type="email" className="input" value={stmt.email} onChange={e => setStmt({ ...stmt, email: e.target.value })} placeholder={b.sendsTo || ""} /></div>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" className="btn-secondary" onClick={pdf}><FileText className="h-4 w-4" /> Open PDF</button>
|
||||
<button type="button" className="btn-primary" onClick={emailStatement}><Mail className="h-4 w-4" /> Email</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { BillingCycle, BillingEmail, Invoice, LicenceChange, Line, Payment, PlanChange } from "@/lib/billing";
|
||||
import type { Product } from "@/lib/products";
|
||||
|
||||
// Hub 2.14.0: the shapes the customer page loads once and passes down to its cards and popups.
|
||||
|
||||
export type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
/** Each card reports its outcome to the one message under the page header, and asks for a reload. */
|
||||
export type Done = (msg: Msg) => void;
|
||||
|
||||
/** A plan of a product: the Events tiers have an income ceiling (upTo), the App tiers a member band. */
|
||||
export type Plan = { name: string; monthly: number | null; founding: number | null; upTo?: number | null; band?: string };
|
||||
|
||||
export type BillingLicence = {
|
||||
id: string; key: string; product: Product; plan: string; status: string; customMonthlyCents: number | null;
|
||||
billedFrom: string | null; billedUntil: string | null; billable: boolean; url: string | null;
|
||||
incomeBand?: string | null; activeMembers?: string | null; storage?: { usedBytes: number; includedBytes: number } | null;
|
||||
};
|
||||
|
||||
export type AddressType = "own_domain" | "crosscode" | "included";
|
||||
|
||||
export type CustomerBillingData = {
|
||||
id: string; name: string; billingEmail: string | null; billingAddress: string | null; founding: boolean; foundingSince: string | null; foundingNote: string | null;
|
||||
billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null;
|
||||
addressType: AddressType; domain: string | null; addressCustomCents: number | null; addressMonthlyCents: number; domainRenewsOn: string | null;
|
||||
sendsTo: string | null; balanceCents: number; licences: BillingLicence[]; invoices: Invoice[]; payments: Payment[]; licenceChanges: LicenceChange[]; emails: BillingEmail[];
|
||||
plans: Record<Product, Plan[]>;
|
||||
};
|
||||
|
||||
export type Preview = { billed: false } | { billed: true; empty: boolean; invoice: { periodStart: string; periodEnd: string; issueDate: string; lines: Line[]; totalCents: number; warnings: string[]; planChanges: PlanChange[] } };
|
||||
|
||||
export const ADDRESS_OPTIONS: Record<AddressType, { label: string; price: string; help: string }> = {
|
||||
own_domain: { label: "Own domain", price: "R0", help: "The church (or whoever manages its domain) adds the DNS records we send. We look after the certificates." },
|
||||
crosscode: { label: "Cross Code address", price: "R10/month", help: "<church>.crosscode.co.za, with events., app. and so on in front. Free during a trial." },
|
||||
included: { label: "Domain included", price: "R25/month", help: "A .co.za or .org.za registered in the church's name; we renew it and manage the DNS. Other endings at cost: set a custom price." },
|
||||
};
|
||||
|
||||
/** A date input's value from an ISO date. */
|
||||
export const dateInput = (d: string | null | undefined) => (d ? d.slice(0, 10) : "");
|
||||
/** End of the chosen day, South African time. */
|
||||
export const endOfDay = (ymd: string) => (ymd ? `${ymd}T23:59:59+02:00` : null);
|
||||
|
||||
const gb = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GB`;
|
||||
|
||||
/** The tier a product's report points to: an Events income band ("R100 001–R150 000") or an App member band. */
|
||||
export function suggestedTier(licence: BillingLicence, plans: Plan[]) {
|
||||
if (licence.product === "app") return plans.find(p => p.band && p.band === licence.activeMembers) || null;
|
||||
const band = licence.incomeBand;
|
||||
if (licence.product !== "events" || !band || band === "over R100 000") return null;
|
||||
if (/^over /.test(band)) return plans.find(t => t.upTo == null) || null;
|
||||
const top = Number((band.split("–")[1] || "").replace(/[^\d]/g, ""));
|
||||
return plans.find(t => t.upTo == null || top <= (t.upTo ?? Infinity)) || null;
|
||||
}
|
||||
|
||||
/** What the product reports that its price depends on. */
|
||||
export function reportText(l: BillingLicence) {
|
||||
if (l.product === "events") return l.incomeBand ? `12-month event income ${l.incomeBand}` : "No event income reported yet";
|
||||
if (l.product === "app") return l.activeMembers ? `${l.activeMembers} active members (90 days)` : "No active members reported yet";
|
||||
if (l.product === "website") return l.storage ? `${gb(l.storage.usedBytes)} of ${gb(l.storage.includedBytes)} storage used` : "No storage reported yet";
|
||||
return "";
|
||||
}
|
||||
|
||||
/** Whether a form differs from what it started with. */
|
||||
export const changed = <T,>(a: T, b: T) => JSON.stringify(a) !== JSON.stringify(b);
|
||||
@@ -1,5 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { ChevronLeft, ChevronRight, Search } from "lucide-react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
import { ChevronLeft, ChevronRight, MoreHorizontal, Search, X } from "lucide-react";
|
||||
import type { LicenceStatus, Problem } from "@/lib/types";
|
||||
|
||||
const STATUS_TONE: Record<string, string> = {
|
||||
@@ -59,12 +63,116 @@ export function Message({ msg }: { msg: { type: "ok" | "err"; text: string } | n
|
||||
);
|
||||
}
|
||||
|
||||
export function Stat({ label, value, tone }: { label: string; value: React.ReactNode; tone?: "red" | "amber" | "green" }) {
|
||||
/** A figure in a tile. With `onClick` the whole tile is a button; `sub` is a small line under the value. */
|
||||
export function Stat({ label, value, tone, sub, onClick, small }: {
|
||||
label: string; value: React.ReactNode; tone?: "red" | "amber" | "green"; sub?: React.ReactNode; onClick?: () => void; small?: boolean;
|
||||
}) {
|
||||
const color = tone === "red" ? "text-red-700" : tone === "amber" ? "text-amber-700" : tone === "green" ? "text-green-700" : "text-slate-900";
|
||||
return (
|
||||
<div className="card">
|
||||
const body = (
|
||||
<>
|
||||
<div className="text-sm text-slate-500">{label}</div>
|
||||
<div className={`mt-1 text-2xl font-semibold tabular-nums ${color}`}>{value}</div>
|
||||
<div className={`mt-1 font-semibold tabular-nums ${small ? "text-base leading-snug" : "text-2xl"} ${color}`}>{value}</div>
|
||||
{sub && <div className="mt-0.5 truncate text-xs text-slate-500">{sub}</div>}
|
||||
</>
|
||||
);
|
||||
if (onClick) return <button type="button" onClick={onClick} className="card min-w-0 text-left hover:border-indigo-300 hover:bg-indigo-50/40">{body}</button>;
|
||||
return <div className="card min-w-0">{body}</div>;
|
||||
}
|
||||
|
||||
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
||||
|
||||
/**
|
||||
* Hub 2.14.0: a popup over the page. Closes on Esc, the close button or a click outside; with
|
||||
* `dirty` it asks first. Focus stays inside while it's open and goes back where it was after. At
|
||||
* phone width it fills the screen. Drawn at the end of <body>, so nothing around it (a faded card)
|
||||
* changes how it looks.
|
||||
*/
|
||||
export function Modal({ title, onClose, dirty = false, wide = false, children }: {
|
||||
title: React.ReactNode; onClose: () => void; dirty?: boolean; wide?: boolean; children: React.ReactNode;
|
||||
}) {
|
||||
const panel = React.useRef<HTMLDivElement>(null);
|
||||
const titleId = React.useId();
|
||||
// The latest values, read by the listeners added once.
|
||||
const state = React.useRef({ onClose, dirty });
|
||||
state.current = { onClose, dirty };
|
||||
const requestClose = React.useCallback(() => {
|
||||
if (state.current.dirty && !confirm("Close without saving your changes?")) return;
|
||||
state.current.onClose();
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
const before = document.activeElement as HTMLElement | null;
|
||||
const overflow = document.body.style.overflow;
|
||||
document.body.style.overflow = "hidden";
|
||||
const first = panel.current?.querySelector<HTMLElement>("[autofocus], input:not([disabled]), select:not([disabled]), textarea:not([disabled])")
|
||||
|| panel.current?.querySelector<HTMLElement>(FOCUSABLE);
|
||||
(first || panel.current)?.focus();
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") { e.stopPropagation(); requestClose(); return; }
|
||||
if (e.key !== "Tab" || !panel.current) return;
|
||||
const items = Array.from(panel.current.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(el => el.offsetParent !== null);
|
||||
if (!items.length) return;
|
||||
const [a, z] = [items[0], items[items.length - 1]];
|
||||
if (e.shiftKey && document.activeElement === a) { e.preventDefault(); z.focus(); }
|
||||
else if (!e.shiftKey && document.activeElement === z) { e.preventDefault(); a.focus(); }
|
||||
};
|
||||
document.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
document.removeEventListener("keydown", onKey);
|
||||
document.body.style.overflow = overflow;
|
||||
before?.focus?.();
|
||||
};
|
||||
}, [requestClose]);
|
||||
|
||||
// A press that starts and ends on the backdrop closes; dragging out of a field doesn't.
|
||||
const downOnBackdrop = React.useRef(false);
|
||||
return createPortal(
|
||||
<div className="fixed inset-0 z-50 flex items-stretch justify-center bg-slate-900/40 sm:items-center sm:p-4"
|
||||
onMouseDown={e => { downOnBackdrop.current = e.target === e.currentTarget; }}
|
||||
onMouseUp={e => { if (downOnBackdrop.current && e.target === e.currentTarget) requestClose(); downOnBackdrop.current = false; }}>
|
||||
<div ref={panel} role="dialog" aria-modal="true" aria-labelledby={titleId} tabIndex={-1}
|
||||
className={`flex w-full flex-col bg-white shadow-xl outline-none sm:max-h-[90vh] sm:rounded-xl ${wide ? "sm:max-w-3xl" : "sm:max-w-xl"}`}>
|
||||
<div className="flex items-center justify-between gap-3 border-b border-slate-200 px-5 py-3">
|
||||
<h2 id={titleId} className="font-semibold">{title}</h2>
|
||||
<button type="button" onClick={requestClose} aria-label="Close" className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700"><X className="h-4 w-4" /></button>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-5">{children}</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
/** The error of a form in a popup, next to its Save button. */
|
||||
export function FormError({ error }: { error: string | null }) {
|
||||
return error ? <p role="alert" className="text-sm text-red-700">{error}</p> : null;
|
||||
}
|
||||
|
||||
/** A "⋯" button with a short list of actions under it. */
|
||||
export function Menu({ label = "More actions", items }: { label?: string; items: ({ label: string; onClick: () => void; danger?: boolean } | false | null | undefined)[] }) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const box = React.useRef<HTMLDivElement>(null);
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
const away = (e: MouseEvent) => { if (!box.current?.contains(e.target as Node)) setOpen(false); };
|
||||
const esc = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); };
|
||||
document.addEventListener("mousedown", away);
|
||||
document.addEventListener("keydown", esc);
|
||||
return () => { document.removeEventListener("mousedown", away); document.removeEventListener("keydown", esc); };
|
||||
}, [open]);
|
||||
const shown = items.filter(Boolean) as { label: string; onClick: () => void; danger?: boolean }[];
|
||||
if (!shown.length) return null;
|
||||
return (
|
||||
<div ref={box} className="relative">
|
||||
<button type="button" className="btn-secondary px-2" aria-label={label} aria-haspopup="menu" aria-expanded={open} onClick={() => setOpen(o => !o)}><MoreHorizontal className="h-4 w-4" /></button>
|
||||
{open && (
|
||||
<div role="menu" className="absolute right-0 z-40 mt-1 min-w-44 rounded-lg border border-slate-200 bg-white py-1 shadow-lg">
|
||||
{shown.map(i => (
|
||||
<button key={i.label} type="button" role="menuitem" onClick={() => { setOpen(false); i.onClick(); }}
|
||||
className={`block w-full whitespace-nowrap px-3 py-2 text-left text-sm hover:bg-slate-50 ${i.danger ? "text-red-700" : "text-slate-700"}`}>{i.label}</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user