Hub 2.13.0: clear alerts by hand, sortable billing tables, no stray tab scrollbars

- Alerts: Clear one or Clear all. A cleared alert leaves the open list and dashboard count
  but stays open to the checks, so it isn't re-raised or re-emailed until the problem goes
  away and comes back. Audited. Migration 20261123120000_alert_cleared.
- Billing invoices, payments, churches and a customer's invoices/payments can be sorted by
  column (remembered per browser). Invoices show the due date in its own column.
- Tabs: the grey rule is an inset shadow, so the active underline no longer overflows the
  row by a pixel and makes it scroll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 10:20:23 +02:00
co-authored by Claude Opus 5.5
parent 7ae95f737c
commit be27b4f5f0
15 changed files with 229 additions and 27 deletions
+21
View File
@@ -5,6 +5,27 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.13.0] - 2026-11-23
Migration `20261123120000_alert_cleared` (one column on `InstallEvent`).
### Added
- **Clear alerts by hand.** Each open alert has a Clear link, and Alerts → Open has Clear all. A
cleared alert leaves the open list and the dashboard count but stays open to the 5-minute
checks, so it isn't raised or emailed again while the problem lasts; when the problem goes away
it's resolved as usual, and if it comes back it's a new alert. Clearing is in the audit log.
- **Sort invoices, payments and churches.** Click a column heading on Billing (invoices, payments,
churches) or a customer's invoices to sort by it, again to turn it round; a customer's payments
have a sort menu. The choice is remembered in this browser. Invoices now show the due date in a
column of its own.
### Fixed
- **A small scrollbar beside tab rows** (Settings, Billing, Servers → Updates). The active tab's
underline overflowed the row by a pixel, so the browser made it scroll; the rule under the tabs
no longer takes up room.
## [2.12.0] - 2026-11-23
Needs agent 1.5.0 (`agent@1.5.0`) to uninstall one product of a church; vendors contracts 1.16.0.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "2.12.0",
"version": "2.13.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.12.0",
"version": "2.13.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.12.0",
"version": "2.13.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
@@ -0,0 +1,2 @@
-- Hub 2.13.0: an alert cleared by hand is left out of the open alerts until its problem goes away.
ALTER TABLE "InstallEvent" ADD COLUMN "clearedAt" TIMESTAMP(3);
+3
View File
@@ -242,6 +242,9 @@ model InstallEvent {
message String
createdAt DateTime @default(now())
resolvedAt DateTime?
/// Hub 2.13.0: cleared by hand. Left out of the open alerts, but still open to the checks, so it
/// isn't raised (or emailed) again until the problem has gone away and come back.
clearedAt DateTime?
@@index([installId, createdAt])
@@index([type, resolvedAt])
+22 -2
View File
@@ -26,6 +26,9 @@ const { emailList } = require('../utils/emails');
const router = express.Router();
router.use(protect);
/** An open alert: a warning or critical problem that is neither resolved nor cleared by hand (Hub 2.13.0). */
const OPEN_ALERT = { resolvedAt: null, clearedAt: null, level: { not: 'info' } };
const smtpTestLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many test emails — wait a few minutes.' } });
const wrap = fn => (req, res) => fn(req, res).catch(e => {
@@ -76,7 +79,7 @@ router.get('/dashboard', wrap(async (req, res) => {
const [customers, licences, openAlerts, billed, sentInvoices] = await Promise.all([
prisma.customer.count({ where: { archivedAt: null } }),
prisma.licence.groupBy({ by: ['product', 'status'], _count: { _all: true } }),
prisma.installEvent.count({ where: { resolvedAt: null, level: { not: 'info' } } }),
prisma.installEvent.count({ where: OPEN_ALERT }),
prisma.customer.findMany({ where: { billingCycle: { not: 'none' } }, include: { licences: { include: { install: true } } } }),
prisma.invoice.findMany({ where: { status: 'sent' }, include: { payments: true } }),
]);
@@ -335,7 +338,7 @@ router.post('/installs/:id/public-key/clear', wrap(async (req, res) => {
// Hub 2.6.0: both paged (?page, ?pageSize) with a search (?q), instead of the last 200 / 300.
router.get('/events', wrap(async (req, res) => {
const and = [];
if (req.query.open === 'true') and.push({ resolvedAt: null, level: { not: 'info' } });
if (req.query.open === 'true') and.push(OPEN_ALERT);
const term = searchTerm(req.query.q);
if (term) {
and.push({ OR: [
@@ -350,6 +353,23 @@ router.get('/events', wrap(async (req, res) => {
res.json({ events: out.rows, total: out.total, page: out.page, pageSize: out.pageSize, pages: out.pages });
}));
// Hub 2.13.0: clear an open alert by hand (one, or every open one). It stays open to the checks, so it
// is resolved as usual when the problem goes away, and raised (and emailed) again only if it comes back.
router.post('/events/clear', wrap(async (req, res) => {
const out = await prisma.installEvent.updateMany({ where: OPEN_ALERT, data: { clearedAt: new Date() } });
await audit(req, 'alerts_cleared', null, { count: out.count });
res.json({ cleared: out.count });
}));
router.post('/events/:id/clear', wrap(async (req, res) => {
const event = await prisma.installEvent.findUnique({ where: { id: req.params.id }, include: { install: { select: { name: true } } } });
if (!event) throw bad('Alert not found', 404);
if (event.level === 'info' || event.resolvedAt || event.clearedAt) throw bad('That alert is not open.', 409);
const cleared = await prisma.installEvent.update({ where: { id: event.id }, data: { clearedAt: new Date() } });
await audit(req, 'alert_cleared', event.id, { install: event.install?.name, message: event.message });
res.json({ id: cleared.id, clearedAt: cleared.clearedAt });
}));
router.get('/audit', wrap(async (req, res) => {
const term = searchTerm(req.query.q);
const where = term ? { OR: [
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.12.0",
"version": "2.13.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.12.0",
"version": "2.13.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.12.0",
"version": "2.13.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
+29 -3
View File
@@ -2,29 +2,51 @@
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { Check } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { useServerPaged } from "@/lib/paging";
import type { InstallEvent } from "@/lib/types";
import { Badge, Loading, PageTitle, Pager, SearchInput } from "@/components/ui";
import { Badge, Loading, Message, PageTitle, Pager, SearchInput } from "@/components/ui";
/** Open alerts, and the history of everything that happened to installs, a page at a time (Hub 2.6.0: paged on the server). */
export default function AlertsPage() {
const [openOnly, setOpenOnly] = useState(true);
const [query, setQuery] = useState("");
const [q, setQ] = useState("");
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => { const t = setTimeout(() => setQ(query.trim()), 300); return () => clearTimeout(t); }, [query]);
const paged = useServerPaged<InstallEvent>("/api/admin/events", { open: openOnly ? "true" : "", q }, r => r.events as InstallEvent[]);
const events = paged.rows;
const error = paged.error;
// Hub 2.13.0: clear an alert by hand. It comes back only if the problem goes away and returns.
const clear = async (path: string, done: (r: { cleared?: number }) => string) => {
setBusy(true);
try {
const r = await api<{ cleared?: number }>(path, { method: "POST" });
setMsg({ type: "ok", text: done(r) });
paged.reload();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
const clearOne = (e: InstallEvent) => clear(`/api/admin/events/${e.id}/clear`, () => `Cleared: ${e.message}`);
const clearAll = () => {
if (!confirm(`Clear all ${paged.total} open alert${paged.total === 1 ? "" : "s"}? Each is raised again only if its problem goes away and comes back.`)) return;
clear("/api/admin/events/clear", r => `${r.cleared ?? 0} alert${r.cleared === 1 ? "" : "s"} cleared.`);
};
const isOpen = (e: InstallEvent) => e.level !== "info" && !e.resolvedAt && !e.clearedAt;
return (
<>
<PageTitle title="Alerts" subtitle="Checked every 5 minutes. New warnings and critical alerts are emailed once (Settings → Alerts → Alert email)." />
<PageTitle title="Alerts" subtitle="Checked every 5 minutes. New warnings and critical alerts are emailed once (Settings → Alerts → Alert email). A cleared alert stays away until its problem is fixed and comes back." />
<div className="mb-4 flex flex-wrap gap-2">
<button className={openOnly ? "btn-primary" : "btn-secondary"} onClick={() => setOpenOnly(true)}>Open</button>
<button className={!openOnly ? "btn-primary" : "btn-secondary"} onClick={() => setOpenOnly(false)}>Everything</button>
{openOnly && !q && paged.total > 1 && <button className="btn-secondary" disabled={busy} onClick={clearAll}><Check className="h-4 w-4" /> Clear all</button>}
<SearchInput className="w-full sm:ml-auto sm:w-72" value={query} onChange={setQuery} placeholder="Search alerts or install" />
</div>
{msg && <div className="mb-4"><Message msg={msg} /></div>}
{error && <p className="text-sm text-red-700">{error}</p>}
{!events ? <Loading /> : events.length === 0 && !q ? <p className="text-sm text-slate-500">{openOnly ? "No open alerts. 🎉" : "Nothing yet."}</p> : (
<div className="card overflow-x-auto p-0">
@@ -37,7 +59,11 @@ export default function AlertsPage() {
<td className="p-3 whitespace-nowrap text-xs text-slate-500">{fmtDate(e.createdAt)}</td>
<td className="p-3">{e.install ? <Link href={`/installs/${e.install.id}`} className="text-indigo-700 hover:underline">{e.install.name}</Link> : "—"}</td>
<td className="p-3"><Badge value={e.level} /> <span className="ml-1">{e.message}</span></td>
<td className="p-3 text-xs text-slate-500">{e.level === "info" ? "" : e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : "open"}</td>
<td className="p-3 whitespace-nowrap text-xs text-slate-500">
{isOpen(e)
? <span className="inline-flex items-center gap-3">open <button type="button" className="font-medium text-indigo-700 hover:underline disabled:opacity-50" disabled={busy} onClick={() => clearOne(e)} title="Clear this alert; it's raised again only if the problem goes away and comes back">Clear</button></span>
: e.level === "info" ? "" : e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : `cleared ${ago(e.clearedAt)}`}
</td>
</tr>
))}
</tbody>
+39 -8
View File
@@ -9,6 +9,7 @@ import { Loading, Message, PageTitle, Pager, SearchInput, Stat, Tabs } from "@/c
import { CYCLE, METHOD, StateBadge, day, money, todayYmd, type BillingCycle, type Invoice, type Payment } from "@/lib/billing";
import { RecordPayment } from "@/components/billing/RecordPayment";
import { PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
import { SortTh, useSort, type SortColumn } from "@/lib/sort";
type Msg = { type: "ok" | "err"; text: string } | null;
type Overview = { drafts: number; approved: number; owingCents: number; overdueCents: number; overdue: number; receivedThisMonthCents: number };
@@ -30,6 +31,31 @@ const FILTERS = [
["overdue", "Overdue"], ["paid", "Paid"], ["void", "Void"],
] as const;
// Hub 2.13.0: the columns each table can be sorted by (click a heading).
const INVOICE_SORT = {
number: { get: i => i.number, first: "desc" },
church: { get: i => i.customer?.name },
date: { get: i => i.issueDate, first: "desc" },
due: { get: i => i.dueDate, first: "desc" },
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 PAYMENT_SORT = {
receipt: { get: p => p.receiptNumber, first: "desc" },
church: { get: p => p.customer?.name },
received: { get: p => p.paidOn, first: "desc" },
invoice: { get: p => p.invoice?.number },
amount: { get: p => p.amountCents, first: "desc" },
sent: { get: p => p.receiptSentAt, first: "desc" },
} satisfies Record<string, SortColumn<Payment>>;
const ACCOUNT_SORT = {
church: { get: a => a.name },
founding: { get: a => (a.founding ? 1 : 0), first: "desc" },
billing: { get: a => (a.billingCycle === "none" ? null : a.nextInvoiceDate) },
owing: { get: a => a.balanceCents || null, first: "desc" },
} satisfies Record<string, SortColumn<Account>>;
/** Billing: invoices (drafted automatically, approved here), payments and receipts, churches and founding status. */
export default function BillingPage() {
const [tab, setTab] = useState<Tab>("invoices");
@@ -81,8 +107,12 @@ export default function BillingPage() {
const shownInvoices = useMemo(() => (invoices || []).filter(i => matches(query, i.number, i.customer?.name, i.plan, i.recipientEmail)), [invoices, query]);
const shownPayments = useMemo(() => (payments || []).filter(p => matches(query, p.receiptNumber, p.customer?.name, p.reference, p.invoice?.number)), [payments, query]);
const shownAccounts = useMemo(() => (accounts || []).filter(a => matches(query, a.name, a.billingEmail, ...a.licences.map(l => l.plan))), [accounts, query]);
const invPaged = usePaged(shownInvoices, `${query}|${filter}`, 25);
const payPaged = usePaged(shownPayments, query, 25);
const invSorted = useSort(shownInvoices, INVOICE_SORT, { key: "date", dir: "desc" }, "billing-invoices");
const paySorted = useSort(shownPayments, PAYMENT_SORT, { key: "received", dir: "desc" }, "billing-payments");
const accSorted = useSort(shownAccounts, ACCOUNT_SORT, { key: "church", dir: "asc" }, "billing-churches");
const invSort = invSorted.sort, paySort = paySorted.sort, accSort = accSorted.sort;
const invPaged = usePaged(invSorted.rows, `${query}|${filter}|${invSort.key}|${invSort.dir}`, 25);
const payPaged = usePaged(paySorted.rows, `${query}|${paySort.key}|${paySort.dir}`, 25);
const founding = (accounts || []).filter(a => a.founding).length;
return (
@@ -125,20 +155,21 @@ export default function BillingPage() {
{tab === "invoices" && (!invoices ? <Loading /> : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Invoice</th><th className="p-3">Church</th><th className="p-3">Date</th><th className="p-3 text-right">Total</th><th className="p-3 text-right">Balance</th><th className="p-3">State</th><th className="p-3" /></tr></thead>
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><SortTh sort={invSort} k="number">Invoice</SortTh><SortTh sort={invSort} k="church">Church</SortTh><SortTh sort={invSort} k="date">Date</SortTh><SortTh sort={invSort} k="due">Due</SortTh><SortTh sort={invSort} k="total" right>Total</SortTh><SortTh sort={invSort} k="balance" right>Balance</SortTh><SortTh sort={invSort} k="state">State</SortTh><th className="p-3" /></tr></thead>
<tbody>
{invPaged.rows.map(i => (
<tr key={i.id} className="border-t border-slate-100">
<td className="p-3"><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link>{i.planChanges.map(pc => <div key={`${pc.product}-${pc.to}`} className="text-xs text-amber-700">{pc.product && pc.product !== "events" ? `${PRODUCT_NAMES[pc.product]}: ` : ""}{pc.from} → {pc.to}</div>)}{i.warnings.length > 0 && i.status === "draft" && <div className="text-xs text-amber-700">Check {i.warnings.length === 1 ? "1 note" : `${i.warnings.length} notes`}</div>}</td>
<td className="p-3">{i.customer?.name}{i.customer?.founding && <Star className="ml-1 inline h-3.5 w-3.5 fill-amber-400 text-amber-400" aria-label="Founding church" />}<div className="text-xs text-slate-500">{i.plan || "One-off"}</div></td>
<td className="p-3 whitespace-nowrap">{day(i.issueDate)}<div className="text-xs text-slate-500">due {day(i.dueDate)}</div></td>
<td className="p-3 whitespace-nowrap">{day(i.issueDate)}</td>
<td className="p-3 whitespace-nowrap">{day(i.dueDate)}</td>
<td className="p-3 text-right tabular-nums">{money(i.totalCents)}</td>
<td className="p-3 text-right tabular-nums">{i.status === "sent" ? money(i.balanceCents) : "—"}</td>
<td className="p-3"><StateBadge state={i.state} short /></td>
<td className="p-3 text-right"><button className="text-slate-500 hover:text-indigo-700" title="Open the PDF" onClick={() => openPdf(`/api/admin/billing/invoices/${i.id}/pdf`).catch(e => setMsg({ type: "err", text: errorText(e) }))}><FileText className="h-4 w-4" /></button></td>
</tr>
))}
{shownInvoices.length === 0 && <tr><td colSpan={7} className="p-6 text-center text-slate-500">No invoices{filter || query ? " match" : " yet. Set up billing on a customer's licence and the drafts appear here 14 days before each invoice date"}.</td></tr>}
{shownInvoices.length === 0 && <tr><td colSpan={8} className="p-6 text-center text-slate-500">No invoices{filter || query ? " match" : " yet. Set up billing on a customer's licence and the drafts appear here 14 days before each invoice date"}.</td></tr>}
</tbody>
</table>
<div className="p-3"><Pager {...invPaged} /></div>
@@ -148,7 +179,7 @@ export default function BillingPage() {
{tab === "payments" && (!payments ? <Loading /> : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Receipt</th><th className="p-3">Church</th><th className="p-3">Received</th><th className="p-3">For</th><th className="p-3 text-right">Amount</th><th className="p-3">Receipt sent</th><th className="p-3" /></tr></thead>
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><SortTh sort={paySort} k="receipt">Receipt</SortTh><SortTh sort={paySort} k="church">Church</SortTh><SortTh sort={paySort} k="received">Received</SortTh><SortTh sort={paySort} k="invoice">For</SortTh><SortTh sort={paySort} k="amount" right>Amount</SortTh><SortTh sort={paySort} k="sent">Receipt sent</SortTh><th className="p-3" /></tr></thead>
<tbody>
{payPaged.rows.map(p => (
<tr key={p.id} className="border-t border-slate-100">
@@ -173,9 +204,9 @@ export default function BillingPage() {
<p className="mb-3 text-sm text-slate-600">{founding} founding church{founding === 1 ? "" : "es"}. Founding churches pay the founding price (35% less) on every tier for as long as they stay. Set billing up on the church&apos;s page: one invoice covers all its products.</p>
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Church</th><th className="p-3">Founding</th><th className="p-3">Products</th><th className="p-3">Billing</th><th className="p-3 text-right">Owing</th></tr></thead>
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><SortTh sort={accSort} k="church">Church</SortTh><SortTh sort={accSort} k="founding">Founding</SortTh><th className="p-3">Products</th><SortTh sort={accSort} k="billing">Billing</SortTh><SortTh sort={accSort} k="owing" right>Owing</SortTh></tr></thead>
<tbody>
{shownAccounts.map(a => (
{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">
@@ -267,7 +267,7 @@ export default function InstallPage() {
<span className="w-40 shrink-0 text-xs text-slate-500">{fmtDate(e.createdAt)}</span>
<Badge value={e.level} />
<span>{e.message}</span>
{e.level !== "info" && <span className="text-xs text-slate-400">{e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : "open"}</span>}
{e.level !== "info" && <span className="text-xs text-slate-400">{e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : e.clearedAt ? `cleared ${ago(e.clearedAt)}` : "open"}</span>}
</li>
))}
</ul>
@@ -9,6 +9,7 @@ import { CYCLE, EMAIL_KIND, METHOD, StateBadge, centsFrom, day, money, randInput
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. */
@@ -252,6 +253,23 @@ function NextInvoice({ customerId, version }: { customerId: string; version: str
);
}
// 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);
@@ -265,6 +283,8 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
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;
@@ -354,8 +374,8 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
</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><th className="py-2">Invoice</th><th className="py-2">Date</th><th className="py-2">Tier</th><th className="py-2 text-right">Total</th><th className="py-2 text-right">Balance</th><th className="py-2">State</th></tr></thead>
<tbody>{c.invoices.map(i => (
<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>
@@ -371,8 +391,11 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
<div className="grid gap-4 lg:grid-cols-2">
<div className="card text-sm">
<h3 className="mb-2 font-semibold">Payments</h3>
{c.payments.length === 0 ? <p className="text-slate-500">None yet.</p> : c.payments.map(p => (
<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>
+4 -2
View File
@@ -101,7 +101,9 @@ export function Pager({ page, pages, setPage, total, pageSize }: { page: number;
/** A row of tabs; the panel is whatever the page renders for the active one. */
export function Tabs<K extends string>({ tabs, active, onChange }: { tabs: { key: K; label: string }[]; active: K; onChange: (k: K) => void }) {
return (
<div role="tablist" className="mb-6 flex gap-1 overflow-x-auto border-b border-slate-200">
// The grey rule is an inset shadow, not a border, so the active tab's underline can sit on it without
// pulling out of the box (a -mb-px tab overflowed it by a pixel, and the browser drew a scrollbar).
<div role="tablist" className="mb-6 flex gap-1 overflow-x-auto overflow-y-hidden shadow-[inset_0_-1px_0_#e2e8f0] [scrollbar-width:thin]">
{tabs.map(t => (
<button
key={t.key}
@@ -111,7 +113,7 @@ export function Tabs<K extends string>({ tabs, active, onChange }: { tabs: { key
aria-selected={active === t.key}
aria-controls={`panel-${t.key}`}
onClick={() => onChange(t.key)}
className={`-mb-px whitespace-nowrap border-b-2 px-3 py-2 text-sm ${active === t.key ? "border-indigo-600 font-medium text-indigo-700" : "border-transparent text-slate-600 hover:text-slate-900"}`}
className={`whitespace-nowrap border-b-2 px-3 py-2 text-sm ${active === t.key ? "border-indigo-600 font-medium text-indigo-700" : "border-transparent text-slate-600 hover:text-slate-900"}`}
>
{t.label}
</button>
+74
View File
@@ -0,0 +1,74 @@
import React, { useEffect, useMemo, useState } from "react";
import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";
export type SortDir = "asc" | "desc";
type Value = string | number | boolean | null | undefined;
/** How to read one column's value, and which way it sorts when first picked (default: A–Z / smallest first). */
export type SortColumn<T> = { get: (row: T) => Value; first?: SortDir };
export type Sort<K extends string> = { key: K; dir: SortDir; toggle: (k: K) => void; set: (k: K, dir: SortDir) => void };
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
/** Empty values always go last, whichever way the column is sorted. */
function compare(a: Value, b: Value, dir: SortDir) {
const emptyA = a == null || a === "";
const emptyB = b == null || b === "";
if (emptyA || emptyB) return emptyA === emptyB ? 0 : emptyA ? 1 : -1;
const n = typeof a === "string" && typeof b === "string" ? collator.compare(a, b) : Number(a) - Number(b);
return dir === "asc" ? n : -n;
}
function remembered<K extends string>(storageKey: string | undefined, keys: K[]): { key: K; dir: SortDir } | null {
if (!storageKey) return null;
try {
const saved = JSON.parse(localStorage.getItem(`sort:${storageKey}`) || "null");
if (saved && keys.includes(saved.key) && (saved.dir === "asc" || saved.dir === "desc")) return saved;
} catch { /* private window or blocked storage: use the default */ }
return null;
}
/**
* A list sorted by the column the user picked (Hub 2.13.0). Clicking the same column again turns it
* round. With `storageKey` the choice is remembered in this browser.
*/
export function useSort<T, K extends string>(items: T[], columns: Record<K, SortColumn<T>>, initial: { key: NoInfer<K>; dir: SortDir }, storageKey?: string) {
const [state, setState] = useState(initial);
useEffect(() => {
const saved = remembered(storageKey, Object.keys(columns) as K[]);
if (saved) setState(saved);
// eslint-disable-next-line react-hooks/exhaustive-deps -- read once; `columns` is a fixed table
}, [storageKey]);
const set = (key: K, dir: SortDir) => {
setState({ key, dir });
if (storageKey) try { localStorage.setItem(`sort:${storageKey}`, JSON.stringify({ key, dir })); } catch { /* not remembered */ }
};
const toggle = (key: K) => set(key, key === state.key ? (state.dir === "asc" ? "desc" : "asc") : columns[key].first || "asc");
const column = columns[state.key];
// A stable sort, so rows that tie keep the server's order (newest first).
const rows = useMemo(() => [...items].sort((a, b) => compare(column.get(a), column.get(b), state.dir)), [items, column, state.dir]);
const sort: Sort<K> = { key: state.key, dir: state.dir, toggle, set };
return { rows, sort };
}
/** A table heading that sorts by its column when clicked. */
export function SortTh<K extends string>({ sort, k, children, className = "p-3", right }: { sort: Sort<K>; k: K; children: React.ReactNode; className?: string; right?: boolean }) {
const active = sort.key === k;
const Icon = !active ? ArrowUpDown : sort.dir === "asc" ? ArrowUp : ArrowDown;
return (
<th className={`${className} ${right ? "text-right" : ""}`} aria-sort={active ? (sort.dir === "asc" ? "ascending" : "descending") : undefined}>
<button type="button" onClick={() => sort.toggle(k)} className={`inline-flex items-center gap-1 whitespace-nowrap hover:text-slate-900 ${active ? "text-slate-700" : ""} ${right ? "flex-row-reverse" : ""}`}>
{children}
<Icon className={`h-3 w-3 ${active ? "" : "opacity-40"}`} aria-hidden="true" />
</button>
</th>
);
}
/** The same choice as a drop-down, for lists that aren't tables. `options` are [column, direction, label]. */
export function SortSelect<K extends string>({ sort, options, className = "" }: { sort: Sort<K>; options: [K, SortDir, string][]; className?: string }) {
return (
<select className={`input w-auto py-1 text-xs ${className}`} aria-label="Sort by" value={`${sort.key}:${sort.dir}`} onChange={e => { const [k, d] = e.target.value.split(":"); sort.set(k as K, d as SortDir); }}>
{options.map(([k, d, label]) => <option key={`${k}:${d}`} value={`${k}:${d}`}>{label}</option>)}
</select>
);
}
+1 -1
View File
@@ -76,7 +76,7 @@ export type Stats = {
linkedProducts?: number;
};
export type InstallEvent = { id: string; type: string; level: Problem["level"]; message: string; createdAt: string; resolvedAt: string | null; install?: { id: string; name: string; url: string } };
export type InstallEvent = { id: string; type: string; level: Problem["level"]; message: string; createdAt: string; resolvedAt: string | null; clearedAt?: string | null; install?: { id: string; name: string; url: string } };
// AI (Cross Events 2.0). Amounts are in cents (rand), with fractions.
export type AiStatus = { enabled: boolean; capReached: boolean; capCents: number; usedCents: number; usedPercent: number; renewsOn: string };