From be27b4f5f0b9ead658c75ee9c250a78415ceb60e Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Mon, 23 Nov 2026 10:20:23 +0200 Subject: [PATCH] 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 --- CHANGELOG.md | 21 ++++++ backend/package-lock.json | 4 +- backend/package.json | 2 +- .../migration.sql | 2 + backend/prisma/schema.prisma | 3 + backend/src/routes/admin.js | 24 +++++- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- frontend/src/app/(hub)/alerts/page.tsx | 32 +++++++- frontend/src/app/(hub)/billing/page.tsx | 47 ++++++++++-- frontend/src/app/(hub)/installs/[id]/page.tsx | 2 +- .../components/billing/CustomerBilling.tsx | 31 +++++++- frontend/src/components/ui.tsx | 6 +- frontend/src/lib/sort.tsx | 74 +++++++++++++++++++ frontend/src/lib/types.ts | 2 +- 15 files changed, 229 insertions(+), 27 deletions(-) create mode 100644 backend/prisma/migrations/20261123120000_alert_cleared/migration.sql create mode 100644 frontend/src/lib/sort.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 46bd77b..bedec55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/backend/package-lock.json b/backend/package-lock.json index 8410baa..9238cb6 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -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", diff --git a/backend/package.json b/backend/package.json index debb170..c88dab1 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/prisma/migrations/20261123120000_alert_cleared/migration.sql b/backend/prisma/migrations/20261123120000_alert_cleared/migration.sql new file mode 100644 index 0000000..df76d78 --- /dev/null +++ b/backend/prisma/migrations/20261123120000_alert_cleared/migration.sql @@ -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); diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 4b2ab79..e284b37 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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]) diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js index 065dca2..9bf5258 100644 --- a/backend/src/routes/admin.js +++ b/backend/src/routes/admin.js @@ -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: [ diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 648372b..562a116 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -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", diff --git a/frontend/package.json b/frontend/package.json index 446b34a..e24ccaa 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "2.12.0", + "version": "2.13.0", "private": true, "scripts": { "dev": "next dev -p 3200", diff --git a/frontend/src/app/(hub)/alerts/page.tsx b/frontend/src/app/(hub)/alerts/page.tsx index f682950..a30f896 100644 --- a/frontend/src/app/(hub)/alerts/page.tsx +++ b/frontend/src/app/(hub)/alerts/page.tsx @@ -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("/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 ( <> - +
+ {openOnly && !q && paged.total > 1 && }
+ {msg &&
} {error &&

{error}

} {!events ? : events.length === 0 && !q ?

{openOnly ? "No open alerts. 🎉" : "Nothing yet."}

: (
@@ -37,7 +59,11 @@ export default function AlertsPage() { {fmtDate(e.createdAt)} {e.install ? {e.install.name} : "—"} {e.message} - {e.level === "info" ? "" : e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : "open"} + + {isOpen(e) + ? open + : e.level === "info" ? "" : e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : `cleared ${ago(e.clearedAt)}`} + ))} diff --git a/frontend/src/app/(hub)/billing/page.tsx b/frontend/src/app/(hub)/billing/page.tsx index 223c8ff..f90d063 100644 --- a/frontend/src/app/(hub)/billing/page.tsx +++ b/frontend/src/app/(hub)/billing/page.tsx @@ -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>; +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>; +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>; + /** Billing: invoices (drafted automatically, approved here), payments and receipts, churches and founding status. */ export default function BillingPage() { const [tab, setTab] = useState("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 ? : (
- + InvoiceChurchDateDueTotalBalanceState {invPaged.rows.map(i => ( - + + ))} - {shownInvoices.length === 0 && } + {shownInvoices.length === 0 && }
InvoiceChurchDateTotalBalanceState
{i.number}{i.planChanges.map(pc =>
{pc.product && pc.product !== "events" ? `${PRODUCT_NAMES[pc.product]}: ` : ""}{pc.from} → {pc.to}
)}{i.warnings.length > 0 && i.status === "draft" &&
Check {i.warnings.length === 1 ? "1 note" : `${i.warnings.length} notes`}
}
{i.customer?.name}{i.customer?.founding && }
{i.plan || "One-off"}
{day(i.issueDate)}
due {day(i.dueDate)}
{day(i.issueDate)}{day(i.dueDate)} {money(i.totalCents)} {i.status === "sent" ? money(i.balanceCents) : "—"}
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"}.
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"}.
@@ -148,7 +179,7 @@ export default function BillingPage() { {tab === "payments" && (!payments ? : (
- + ReceiptChurchReceivedForAmountReceipt sent {payPaged.rows.map(p => ( @@ -173,9 +204,9 @@ export default function BillingPage() {

{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's page: one invoice covers all its products.

ReceiptChurchReceivedForAmountReceipt sent
- + ChurchFoundingBillingOwing - {shownAccounts.map(a => ( + {accSorted.rows.map(a => (
ChurchFoundingProductsBillingOwing
Products
{a.name}
{a.billingEmail || ""}
diff --git a/frontend/src/app/(hub)/installs/[id]/page.tsx b/frontend/src/app/(hub)/installs/[id]/page.tsx index 53052d5..bb01e16 100644 --- a/frontend/src/app/(hub)/installs/[id]/page.tsx +++ b/frontend/src/app/(hub)/installs/[id]/page.tsx @@ -267,7 +267,7 @@ export default function InstallPage() { {fmtDate(e.createdAt)} {e.message} - {e.level !== "info" && {e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : "open"}} + {e.level !== "info" && {e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : e.clearedAt ? `cleared ${ago(e.clearedAt)}` : "open"}} ))} diff --git a/frontend/src/components/billing/CustomerBilling.tsx b/frontend/src/components/billing/CustomerBilling.tsx index 037ed30..3813bcd 100644 --- a/frontend/src/components/billing/CustomerBilling.tsx +++ b/frontend/src/components/billing/CustomerBilling.tsx @@ -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>; +const CUSTOMER_PAYMENT_SORT = { + received: { get: p => p.paidOn }, + amount: { get: p => p.amountCents }, + receipt: { get: p => p.receiptNumber }, +} satisfies Record>; +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(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 ?
{msg.text}
: null; @@ -354,8 +374,8 @@ export function CustomerBilling({ customerId }: { customerId: string }) { {c.invoices.length === 0 ?

No invoices yet.

: ( - - {c.invoices.map(i => ( + InvoiceDateTierTotalBalanceState + {invoices.rows.map(i => ( @@ -371,8 +391,11 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
-

Payments

- {c.payments.length === 0 ?

None yet.

: c.payments.map(p => ( +
+

Payments

+ {c.payments.length > 1 && } +
+ {c.payments.length === 0 ?

None yet.

: payments.rows.map(p => (
{p.receiptNumber} · {day(p.paidOn)}
{METHOD[p.method] || p.method}{p.invoice ? ` · ${p.invoice.number}` : " · on account"}{p.reference && p.reference !== p.invoice?.number ? ` · ${p.reference}` : ""}
{money(p.amountCents)}
diff --git a/frontend/src/components/ui.tsx b/frontend/src/components/ui.tsx index c9715f0..17c2870 100644 --- a/frontend/src/components/ui.tsx +++ b/frontend/src/components/ui.tsx @@ -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({ tabs, active, onChange }: { tabs: { key: K; label: string }[]; active: K; onChange: (k: K) => void }) { return ( -
+ // 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). +
{tabs.map(t => ( diff --git a/frontend/src/lib/sort.tsx b/frontend/src/lib/sort.tsx new file mode 100644 index 0000000..abd2bf8 --- /dev/null +++ b/frontend/src/lib/sort.tsx @@ -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 = { get: (row: T) => Value; first?: SortDir }; +export type Sort = { 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(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(items: T[], columns: Record>, initial: { key: NoInfer; 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 = { key: state.key, dir: state.dir, toggle, set }; + return { rows, sort }; +} + +/** A table heading that sorts by its column when clicked. */ +export function SortTh({ sort, k, children, className = "p-3", right }: { sort: Sort; k: K; children: React.ReactNode; className?: string; right?: boolean }) { + const active = sort.key === k; + const Icon = !active ? ArrowUpDown : sort.dir === "asc" ? ArrowUp : ArrowDown; + return ( +
+ ); +} + +/** The same choice as a drop-down, for lists that aren't tables. `options` are [column, direction, label]. */ +export function SortSelect({ sort, options, className = "" }: { sort: Sort; options: [K, SortDir, string][]; className?: string }) { + return ( + + ); +} diff --git a/frontend/src/lib/types.ts b/frontend/src/lib/types.ts index 2c29693..d2d0d37 100644 --- a/frontend/src/lib/types.ts +++ b/frontend/src/lib/types.ts @@ -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 };
InvoiceDateTierTotalBalanceState
{i.number} {day(i.issueDate)} + +