Merge branch 'refactor/popup-kit'

This commit is contained in:
2026-11-23 12:34:23 +02:00
29 changed files with 712 additions and 564 deletions
+17
View File
@@ -5,6 +5,23 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.16.0] - 2026-11-23
Frontend only: no migration, no API changes.
### Changed
- **Every add and edit on the list pages is a popup**, like the customer and install pages: Add
server, Add customer, New install, Link existing, New notice and Edit notice, Add release and Edit
release. Each asks before discarding what you have typed, shows its error by its button, and the
page keeps one message under its header.
- **Add server** shows the join command in the same popup; closing it before Copy asks first, since
the command is shown only once.
- **Release sources** shows the sources as a table, with Sync now and Use the defaults on the card;
Edit opens the sources and the access token in a popup, and saving syncs straight away.
- **One-off invoice on Billing is a popup**, with the church to choose (on the customer page it is
for that church). `/billing/invoices/new` opens it.
## [2.15.0] - 2026-11-23
Frontend only: no migration, no API changes.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "2.15.0",
"version": "2.16.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.15.0",
"version": "2.16.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.15.0",
"version": "2.16.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
+95
View File
@@ -0,0 +1,95 @@
# Popups everywhere plan
Status: Step 0 and Hub 2.16.0 done; 2.17.0 next · 2026-11-23
Hub 2.14.0 added `Modal` and made every add or edit on the customer page a popup; 2.15.0 did the same
for the install page. The rest of the Hub still opens forms inline: a form card above a list, a card
that turns into a form, or an editor that is always open. This plan moves those onto the same popup,
so every page shows read views and every change happens in a popup. Frontend only: no migration, no
API changes.
## Still inline
Paths are under `frontend/src/`.
### Add buttons and edits on list pages
| # | Where | Inline today |
|---|---|---|
| 1 | `app/(hub)/servers/page.tsx` | **Add server**: name/kind form, then the join command, in a card above the list |
| 2 | `app/(hub)/customers/page.tsx` | **Add customer**: form card |
| 3 | `app/(hub)/servers/installs/page.tsx` | **New install**: large form card with the server picker |
| 4 | `app/(hub)/servers/installs/page.tsx` | **Link existing**: form card |
| 5 | `app/(hub)/notices/page.tsx` | **New notice**: form card |
| 6 | `app/(hub)/notices/page.tsx` | **Edit** a notice: its card turns into the form |
| 7 | `app/(hub)/releases/page.tsx` | **Add release**: form card |
| 8 | `app/(hub)/releases/page.tsx` | **Edit** a release: its card turns into the form |
| 9 | `app/(hub)/releases/page.tsx` | **Release sources**: an always-editable form (rows and the access token) |
| 10 | `app/(hub)/billing/page.tsx` → `billing/invoices/[id]/page.tsx` (`NewInvoice`) | **One-off invoice** is a separate full page, while `components/billing/OneOffInvoice.tsx` is already the same form as a popup on the customer page |
### Editors on detail pages
| # | Where | Inline today |
|---|---|---|
| 11 | `app/(hub)/servers/[id]/page.tsx` (`ConfigEditor`) | The server's .env layer, always editable |
| 12 | `components/FrpConfig.tsx` | frp config textarea, two-factor code and Save, always open |
| 13 | `app/(hub)/servers/[id]/page.tsx` | **Update agent**: a version input in the Actions card |
| 14 | `app/(hub)/servers/settings/page.tsx` | Install defaults and port range, always editable |
| 15 | `app/(hub)/servers/settings/page.tsx` | **Mark as taken** (a port): inline form |
| 16 | `app/(hub)/installs/[id]/page.tsx` | **Clear public key**: two-factor form inside the card |
| 17 | `app/(hub)/billing/invoices/[id]/page.tsx` | A draft or approved invoice is always editable on the page, with a "Save your changes first" guard before Approve |
Optional: **Void** and **Refund** on the invoice page ask for a reason or note with `prompt()`. They are
small forms, but 2.15.0 left confirmations as they are.
### Left inline on purpose
Forms that are the page itself, not an action on it: the Settings page tabs (Hub, SMTP, password,
`BillingSettings`), the **Updates** planner (`servers/updates`), login, and the filter toggles.
## Step 0: the popup kit in one place (no visible change)
- `ReadCard`, `Field`, `Fields` and `ModalButtons` move from `components/customer/ReadCard.tsx` into
`components/ui.tsx`, next to `Modal`, `FormError` and `PageMessage`; every page uses them now.
- `useSubmit` (busy, the error shown by the popup's button, one submit at a time) moves from
`components/install/shared.ts` into `components/ui.tsx`.
- The customer and install components import them from `@/components/ui`; `customer/ReadCard.tsx` goes.
## Hub 2.16.0: list pages (1-10)
Each page that gets popups shows its result with `PageMessage` (the message stays in view and an ok
fades) instead of `Message`.
- **Add server** (`AddServerModal`): two steps in one popup, the form and then the join command with
Copy and Done. The list reloads however it is closed. Once the command is shown, Esc or a click
outside asks first, since the token works once.
- **Add customer** (`AddCustomerModal`): unsaved once any field is filled; still goes to the new
customer's page when saved.
- **New install** (`NewInstallModal`, wide) and **Link existing** (`LinkInstallModal`). Customers and
installs load when the popup opens; the `?warn=` redirect is unchanged.
- **Notices** (`NoticeModal`): one popup for new and edit around `NoticeForm`; the "Email … now?"
confirmation stays in it. `adding`/`editing` become one `open: null | "new" | id`.
- **Releases** (`ReleaseModal`): the same around `ReleaseForm`.
- **Release sources**: a read view (product, repository, tag prefix, notes file, whether a token is
saved) with **Sync now** on the card and an Edit popup (wide) for the rows and the token.
- **One-off invoice**: Billing opens `OneOffInvoice`; with no `customerId` it shows a church picker.
`/billing/invoices/new` redirects to `/billing?oneoff=1`, which opens the popup, and `NewInvoice` goes.
## Hub 2.17.0: server, settings and invoice pages (11-17)
- **Server configuration**: a read view (secrets as dots) with an Edit popup, as `EnvPanel` in 2.15.0.
- **frp config**: the path, Use this path and Read now stay on the card, the file shows read-only, and
**Edit** opens a popup with the textarea, Restart, the two-factor code and Save (its confirm stays).
- **Update agent**: a small popup from the Actions card. Remove server is unchanged.
- **Install defaults**: a read view with an Edit popup. **Mark as taken**: a button and a small popup.
- **Clear public key**: a danger button opening a popup with the explanation and the two-factor code
(`ModalButtons danger`).
- **Invoice**: always the read view (lines and totals), with **Edit** on drafts and approved invoices
opening a wide popup (dates, recipient, `LinesEditor`, notes). The dirty guard on Approve goes.
- Optional: **Void** and **Refund** as popups with a text field instead of `prompt()`.
## Checks for every popup
Esc, the close button and a click outside close it; unsaved changes ask first; the error shows by its
button; at phone width it fills the screen and the page has no horizontal scroll. `npx tsc --noEmit`
and `npx next build` in `frontend`. Each release gets its CHANGELOG entry and a `vX.Y.Z` tag.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.15.0",
"version": "2.16.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.15.0",
"version": "2.16.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.15.0",
"version": "2.16.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
@@ -8,59 +8,13 @@ import { api, errorText, openPdf } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { EMAIL_KIND, METHOD, StateBadge, day, money, todayYmd, type BillingEmail, type Invoice, type LicenceChange } from "@/lib/billing";
import { LinesEditor, editTotal, fromEdit, toEdit, type EditLine } from "@/components/billing/LinesEditor";
import { LinesEditor, fromEdit, toEdit, type EditLine } from "@/components/billing/LinesEditor";
import { RecordPayment } from "@/components/billing/RecordPayment";
import { PRODUCT_NAMES } from "@/lib/products";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = Invoice & { licenceChanges: LicenceChange[]; emails: BillingEmail[] };
/** A one-off invoice (standby support, set-up…), made as a draft. */
function NewInvoice() {
const router = useRouter();
const [customers, setCustomers] = useState<{ id: string; name: string }[]>([]);
const [form, setForm] = useState({ customerId: "", issueDate: todayYmd(), notes: "" });
const [lines, setLines] = useState<EditLine[]>([{ description: "", quantity: "1", unit: "" }]);
const [msg, setMsg] = useState<Msg>(null);
useEffect(() => {
api<{ id: string; name: string }[]>("/api/admin/billing/customers").then(setCustomers).catch(e => setMsg({ type: "err", text: errorText(e) }));
const c = new URLSearchParams(window.location.search).get("customer");
if (c) setForm(f => ({ ...f, customerId: c }));
}, []);
const save = async (e: React.FormEvent) => {
e.preventDefault();
try {
const inv = await api<Invoice>("/api/admin/billing/invoices", { method: "POST", body: { ...form, lines: fromEdit(lines) } });
router.replace(`/billing/invoices/${inv.id}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<>
<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="One-off invoice" subtitle="For anything outside the licence, like standby support for a big event. It's made as a draft for you to approve." />
<div className="mb-4"><Message msg={msg} /></div>
<form onSubmit={save} className="card max-w-3xl space-y-4">
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="new-customer">Church</label>
<select id="new-customer" className="input" value={form.customerId} onChange={e => setForm({ ...form, customerId: e.target.value })} required>
<option value="">Choose…</option>
{customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
<div><label className="label" htmlFor="new-date">Invoice date (it goes out on this day once approved)</label><input id="new-date" type="date" className="input" value={form.issueDate} onChange={e => setForm({ ...form, issueDate: e.target.value })} required /></div>
</div>
<LinesEditor lines={lines} onChange={setLines} />
<div><label className="label" htmlFor="new-notes">Notes (printed on the invoice)</label><textarea id="new-notes" className="input" rows={2} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} /></div>
<button className="btn-primary" disabled={editTotal(lines) === 0 && !fromEdit(lines).length}>Create draft</button>
</form>
</>
);
}
function InvoiceDetail({ id }: { id: string }) {
const [inv, setInv] = useState<Detail | null>(null);
const [form, setForm] = useState({ issueDate: "", dueDate: "", recipientEmail: "", notes: "" });
@@ -280,7 +234,14 @@ function InvoiceDetail({ id }: { id: string }) {
const Row = ({ k, v }: { k: string; v: React.ReactNode }) => <div className="flex justify-between gap-3"><span className="text-slate-500">{k}</span><span className="text-right">{v}</span></div>;
/** Hub 2.16.0: a one-off invoice is a popup on Billing; /billing/invoices/new still opens it. */
function NewInvoiceRedirect() {
const router = useRouter();
useEffect(() => { router.replace("/billing?oneoff=1"); }, [router]);
return <Loading />;
}
export default function InvoicePage() {
const { id } = useParams<{ id: string }>();
return id === "new" ? <NewInvoice /> : <InvoiceDetail id={id} />;
return id === "new" ? <NewInvoiceRedirect /> : <InvoiceDetail id={id} />;
}
+16 -4
View File
@@ -2,11 +2,13 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { FileText, Play, Plus, Star } from "lucide-react";
import { api, errorText, openPdf } from "@/lib/api";
import { matches, usePaged } from "@/lib/paging";
import { Loading, Message, PageTitle, Pager, SearchInput, Stat, Tabs } from "@/components/ui";
import { Loading, PageMessage, PageTitle, Pager, SearchInput, Stat, Tabs } from "@/components/ui";
import { CYCLE, METHOD, StateBadge, day, money, todayYmd, type BillingCycle, type Invoice, type Payment } from "@/lib/billing";
import { OneOffInvoice } from "@/components/billing/OneOffInvoice";
import { RecordPayment } from "@/components/billing/RecordPayment";
import { PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
import { SortTh, useSort, type SortColumn } from "@/lib/sort";
@@ -68,6 +70,9 @@ export default function BillingPage() {
const [msg, setMsg] = useState<Msg>(null);
const [running, setRunning] = useState(false);
const [paying, setPaying] = useState(false);
// Hub 2.16.0: One-off invoice is a popup here too (/billing/invoices/new opens it with ?oneoff=1).
const [oneOff, setOneOff] = useState(false);
const router = useRouter();
const loadOverview = useCallback(() => api<Overview>("/api/admin/billing/overview").then(setOverview).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
const loadInvoices = useCallback(() => api<Invoice[]>(`/api/admin/billing/invoices${filter ? `?status=${filter}` : ""}`).then(setInvoices).catch(e => setMsg({ type: "err", text: errorText(e) })), [filter]);
@@ -77,8 +82,14 @@ export default function BillingPage() {
useEffect(() => {
const fromHash = window.location.hash.slice(1);
if (TABS.some(t => t.key === fromHash)) setTab(fromHash as Tab);
const f = new URLSearchParams(window.location.search).get("status");
const params = new URLSearchParams(window.location.search);
const f = params.get("status");
if (f && FILTERS.some(([k]) => k === f)) setFilter(f);
if (params.has("oneoff")) {
setOneOff(true);
params.delete("oneoff");
window.history.replaceState(null, "", `${window.location.pathname}${params.size ? `?${params}` : ""}${window.location.hash}`);
}
loadOverview();
}, [loadOverview]);
useEffect(() => { if (tab === "invoices") loadInvoices(); }, [tab, loadInvoices]);
@@ -122,11 +133,12 @@ export default function BillingPage() {
subtitle="Invoices are drafted 14 days before their date and emailed to you to approve; approved ones go out on their date."
actions={<>
<button className="btn-secondary" onClick={run} disabled={running}><Play className="h-4 w-4" /> {running ? "Running…" : "Run billing now"}</button>
<Link className="btn-secondary" href="/billing/invoices/new"><Plus className="h-4 w-4" /> One-off invoice</Link>
<button className="btn-secondary" onClick={() => setOneOff(true)}><Plus className="h-4 w-4" /> One-off invoice</button>
<button className="btn-primary" onClick={() => setPaying(true)}><Plus className="h-4 w-4" /> Record payment</button>
</>}
/>
<div className="mb-4"><Message msg={msg} /></div>
<PageMessage msg={msg} onClose={() => setMsg(null)} />
{oneOff && <OneOffInvoice onClose={() => setOneOff(false)} onSaved={inv => router.push(`/billing/invoices/${inv.id}`)} />}
{overview && (
<div className="mb-6 grid grid-cols-2 gap-3 lg:grid-cols-5">
+32 -22
View File
@@ -9,14 +9,40 @@ import { ago } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import type { Customer } from "@/lib/types";
import { PRODUCT_NAMES, byProduct } from "@/lib/products";
import { Badge, Loading, Message, PageTitle, Pager, SearchInput } from "@/components/ui";
import { Badge, FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, Pager, SearchInput, useSubmit } from "@/components/ui";
import { EmailList } from "@/components/EmailList";
export default function CustomersPage() {
/** Hub 2.16.0: a new customer in a popup; saving opens their page. */
function AddCustomerModal({ onClose }: { onClose: () => void }) {
const router = useRouter();
const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "" });
const { busy, error, run } = useSubmit();
const add = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const c = await api<Customer>("/api/admin/customers", { method: "POST", body: form });
router.push(`/customers/${c.id}`);
});
};
return (
<Modal title="Add customer" onClose={onClose} dirty={Object.values(form).some(v => v.trim() !== "")}>
<form onSubmit={add} className="grid gap-3 sm:grid-cols-2">
<div className="sm:col-span-2"><label className="label" htmlFor="name">Name</label><input id="name" className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required placeholder="Hope Family Church" /></div>
<div><label className="label" htmlFor="contact">Contact person</label><input id="contact" className="input" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} /></div>
<div><label className="label" htmlFor="phone">Phone</label><input id="phone" className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
<div className="sm:col-span-2"><EmailList id="email" label="Email" value={form.email} onChange={email => setForm({ ...form, email })} placeholder="office@church.org" /></div>
<div className="space-y-3 sm:col-span-2">
<FormError error={error} />
<ModalButtons busy={busy} onCancel={onClose} label="Add customer" busyLabel="Adding…" />
</div>
</form>
</Modal>
);
}
export default function CustomersPage() {
const [list, setList] = useState<Customer[] | null>(null);
const [adding, setAdding] = useState(false);
const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "" });
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const [query, setQuery] = useState("");
@@ -31,27 +57,11 @@ export default function CustomersPage() {
}, [archived]);
useEffect(() => { load(); }, [load]);
const add = async (e: React.FormEvent) => {
e.preventDefault();
try {
const c = await api<Customer>("/api/admin/customers", { method: "POST", body: form });
router.push(`/customers/${c.id}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<>
<PageTitle title="Customers" subtitle="Churches and organisations with a licence." actions={!adding && <button className="btn-primary" onClick={() => setAdding(true)}><Plus className="h-4 w-4" /> Add customer</button>} />
{adding && (
<form onSubmit={add} className="card mb-6 grid gap-3 md:grid-cols-2">
<div className="md:col-span-2"><label className="label" htmlFor="name">Name</label><input id="name" className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required placeholder="Hope Family Church" /></div>
<div><label className="label" htmlFor="contact">Contact person</label><input id="contact" className="input" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} /></div>
<EmailList id="email" label="Email" value={form.email} onChange={email => setForm({ ...form, email })} placeholder="office@church.org" />
<div><label className="label" htmlFor="phone">Phone</label><input id="phone" className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
<div className="flex items-end gap-2"><button className="btn-primary">Save</button><button type="button" className="btn-secondary" onClick={() => setAdding(false)}>Cancel</button></div>
</form>
)}
<Message msg={msg} />
<PageTitle title="Customers" subtitle="Churches and organisations with a licence." actions={<button className="btn-primary" onClick={() => setAdding(true)}><Plus className="h-4 w-4" /> Add customer</button>} />
{adding && <AddCustomerModal onClose={() => setAdding(false)} />}
<PageMessage msg={msg} onClose={() => setMsg(null)} />
<div className="mb-3 flex flex-wrap items-center gap-3">
<div className="inline-flex rounded-lg border border-slate-200 p-0.5 text-sm" role="group" aria-label="Which customers">
<button type="button" aria-pressed={!archived} className={`rounded-md px-3 py-1 ${!archived ? "bg-indigo-50 font-medium text-indigo-700" : "text-slate-600"}`} onClick={() => setArchived(false)}>Active</button>
+90 -89
View File
@@ -1,12 +1,12 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Mail, Megaphone } from "lucide-react";
import { Mail, Megaphone, Pencil, Plus } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { matches } from "@/lib/paging";
import type { InstallSummary, Notice, NoticeLevel } from "@/lib/types";
import { Badge, Loading, Message, PageTitle, SearchInput } from "@/components/ui";
import { Badge, FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, SearchInput, useSubmit } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -66,51 +66,73 @@ function Audience({ installs, form, setForm }: { installs: InstallSummary[]; for
);
}
function NoticeForm({ initial, installs, editing, busy, onSave, onCancel }: { initial: Form; installs: InstallSummary[]; editing: boolean; busy: boolean; onSave: (f: Form) => void; onCancel: () => void }) {
const toForm = (n: Notice): Form => ({ title: n.title, message: n.message, level: n.level, allInstalls: n.allInstalls, installIds: n.installIds, showBanner: n.showBanner, sendEmail: false, startsAt: toInput(n.startsAt), endsAt: toInput(n.endsAt) });
/** Hub 2.16.0: a new notice, or changes to one, in a popup. */
function NoticeModal({ notice, installs, onClose, onSaved }: { notice: Notice | null; installs: InstallSummary[]; onClose: () => void; onSaved: (text: string) => void }) {
const initial = useMemo(() => (notice ? toForm(notice) : empty()), [notice]);
const [form, setForm] = useState(initial);
const { busy, error, run } = useSubmit();
const editing = !!notice;
const dirty = JSON.stringify(form) !== JSON.stringify(initial);
const save = (e: React.FormEvent) => {
e.preventDefault();
const f = form;
if (!editing && f.sendEmail && !confirm(`Email "${f.title}" to ${f.allInstalls ? "every church" : `${f.installIds.length} church${f.installIds.length === 1 ? "" : "es"}`} now?`)) return;
run(async () => {
const body = { title: f.title, message: f.message, level: f.level, allInstalls: f.allInstalls, installIds: f.allInstalls ? [] : f.installIds, showBanner: f.showBanner, startsAt: fromInput(f.startsAt), endsAt: fromInput(f.endsAt), ...(editing ? {} : { sendEmail: f.sendEmail }) };
const n = await api<Notice>(editing ? `/api/admin/notices/${notice.id}` : "/api/admin/notices", { method: editing ? "PUT" : "POST", body });
const parts = [editing ? "Saved." : "Created."];
if (!editing && f.sendEmail) parts.push(`Emailed ${n.emailedTo} address${n.emailedTo === 1 ? "" : "es"}.`);
if (n.showBanner) parts.push("Sites show the banner after their next heartbeat (within 15 minutes).");
onSaved(parts.join(" "));
});
};
return (
<form onSubmit={e => { e.preventDefault(); onSave(form); }} className="space-y-4">
<div className="grid gap-3 sm:grid-cols-3">
<div className="sm:col-span-2">
<label className="label" htmlFor="n_title">Title</label>
<input id="n_title" className="input" maxLength={120} placeholder="Planned maintenance on Saturday evening" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} required />
<Modal title={editing ? `Edit “${notice.title}”` : "New notice"} onClose={onClose} dirty={dirty} wide>
<form onSubmit={save} className="space-y-4">
<div className="grid gap-3 sm:grid-cols-3">
<div className="sm:col-span-2">
<label className="label" htmlFor="n_title">Title</label>
<input id="n_title" className="input" maxLength={120} placeholder="Planned maintenance on Saturday evening" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} required />
</div>
<div>
<label className="label" htmlFor="n_level">Kind</label>
<select id="n_level" className="input" value={form.level} onChange={e => setForm({ ...form, level: e.target.value as NoticeLevel })}>
{LEVELS.map(l => <option key={l.key} value={l.key}>{l.label} — {l.hint}</option>)}
</select>
</div>
</div>
<div>
<label className="label" htmlFor="n_level">Kind</label>
<select id="n_level" className="input" value={form.level} onChange={e => setForm({ ...form, level: e.target.value as NoticeLevel })}>
{LEVELS.map(l => <option key={l.key} value={l.key}>{l.label} — {l.hint}</option>)}
</select>
<label className="label" htmlFor="n_message">Message</label>
<textarea id="n_message" className="input min-h-28" maxLength={2000} value={form.message} onChange={e => setForm({ ...form, message: e.target.value })} required placeholder="The site will be unavailable for about 30 minutes while we update the server." />
</div>
</div>
<div>
<label className="label" htmlFor="n_message">Message</label>
<textarea id="n_message" className="input min-h-28" maxLength={2000} value={form.message} onChange={e => setForm({ ...form, message: e.target.value })} required placeholder="The site will be unavailable for about 30 minutes while we update the server." />
</div>
<Audience installs={installs} form={form} setForm={setForm} />
<fieldset className="space-y-2">
<legend className="label">How</legend>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.showBanner} onChange={e => setForm({ ...form, showBanner: e.target.checked })} /> <Megaphone className="h-4 w-4 text-slate-400" /> Banner on the site for site admins and supervisors</label>
{!editing && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.sendEmail} onChange={e => setForm({ ...form, sendEmail: e.target.checked })} /> <Mail className="h-4 w-4 text-slate-400" /> Email the church now (customer email and the site&apos;s admin contact)</label>}
</fieldset>
{form.showBanner && (
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="n_starts">Show from</label>
<input id="n_starts" type="datetime-local" className="input" value={form.startsAt} onChange={e => setForm({ ...form, startsAt: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">Blank: straight away (within 15 minutes, at the site&apos;s next heartbeat).</p>
<Audience installs={installs} form={form} setForm={setForm} />
<fieldset className="space-y-2">
<legend className="label">How</legend>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.showBanner} onChange={e => setForm({ ...form, showBanner: e.target.checked })} /> <Megaphone className="h-4 w-4 text-slate-400" /> Banner on the site for site admins and supervisors</label>
{!editing && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.sendEmail} onChange={e => setForm({ ...form, sendEmail: e.target.checked })} /> <Mail className="h-4 w-4 text-slate-400" /> Email the church now (customer email and the site&apos;s admin contact)</label>}
</fieldset>
{form.showBanner && (
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="n_starts">Show from</label>
<input id="n_starts" type="datetime-local" className="input" value={form.startsAt} onChange={e => setForm({ ...form, startsAt: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">Blank: straight away (within 15 minutes, at the site&apos;s next heartbeat).</p>
</div>
<div>
<label className="label" htmlFor="n_ends">Until</label>
<input id="n_ends" type="datetime-local" className="input" value={form.endsAt} onChange={e => setForm({ ...form, endsAt: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">Blank: until you end it.</p>
</div>
</div>
<div>
<label className="label" htmlFor="n_ends">Until</label>
<input id="n_ends" type="datetime-local" className="input" value={form.endsAt} onChange={e => setForm({ ...form, endsAt: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">Blank: until you end it.</p>
</div>
</div>
)}
<div className="flex flex-wrap gap-2">
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : editing ? "Save notice" : form.sendEmail ? "Create and email" : "Create notice"}</button>
<button type="button" className="btn-secondary" onClick={onCancel}>Cancel</button>
</div>
</form>
)}
<FormError error={error} />
<ModalButtons busy={busy} onCancel={onClose} label={editing ? "Save notice" : form.sendEmail ? "Create and email" : "Create notice"} />
</form>
</Modal>
);
}
@@ -119,9 +141,8 @@ export default function NoticesPage() {
const [notices, setNotices] = useState<Notice[] | null>(null);
const [installs, setInstalls] = useState<InstallSummary[]>([]);
const [msg, setMsg] = useState<Msg>(null);
const [adding, setAdding] = useState(false);
const [editing, setEditing] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
// Hub 2.16.0: the popup that's open: a new notice, or the id of the one being edited.
const [open, setOpen] = useState<"new" | string | null>(null);
const load = useCallback(() => api<Notice[]>("/api/admin/notices").then(setNotices).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
useEffect(() => {
@@ -131,23 +152,6 @@ export default function NoticesPage() {
const installName = (id: string) => { const i = installs.find(x => x.id === id); return i ? i.customer?.name || i.name : "(removed install)"; };
const save = async (f: Form, id?: string) => {
if (!id && f.sendEmail && !confirm(`Email "${f.title}" to ${f.allInstalls ? "every church" : `${f.installIds.length} church${f.installIds.length === 1 ? "" : "es"}`} now?`)) return;
setBusy(true);
setMsg(null);
try {
const body = { title: f.title, message: f.message, level: f.level, allInstalls: f.allInstalls, installIds: f.allInstalls ? [] : f.installIds, showBanner: f.showBanner, startsAt: fromInput(f.startsAt), endsAt: fromInput(f.endsAt), ...(id ? {} : { sendEmail: f.sendEmail }) };
const n = await api<Notice>(id ? `/api/admin/notices/${id}` : "/api/admin/notices", { method: id ? "PUT" : "POST", body });
const parts = [id ? "Saved." : "Created."];
if (!id && f.sendEmail) parts.push(`Emailed ${n.emailedTo} address${n.emailedTo === 1 ? "" : "es"}.`);
if (n.showBanner) parts.push("Sites show the banner after their next heartbeat (within 15 minutes).");
setMsg({ type: "ok", text: parts.join(" ") });
setAdding(false);
setEditing(null);
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
const endNow = async (n: Notice) => {
try {
await api(`/api/admin/notices/${n.id}`, { method: "PUT", body: { endsAt: new Date().toISOString() } });
@@ -160,19 +164,25 @@ export default function NoticesPage() {
if (!confirm(`Delete "${n.title}"?`)) return;
try {
await api(`/api/admin/notices/${n.id}`, { method: "DELETE" });
setMsg({ type: "ok", text: `Deleted "${n.title}".` });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const editing = open && open !== "new" ? notices?.find(n => n.id === open) || null : null;
return (
<>
<PageTitle
title="Notices"
subtitle="Tell churches about maintenance or anything else: a banner on their site for site admins and supervisors, an email, or both."
actions={!adding && <button className="btn-primary" onClick={() => { setAdding(true); setEditing(null); }}>New notice</button>}
actions={<button className="btn-primary" onClick={() => setOpen("new")}><Plus className="h-4 w-4" /> New notice</button>}
/>
{msg && <div className="mb-4"><Message msg={msg} /></div>}
{adding && <div className="card mb-6"><h2 className="mb-3 font-semibold">New notice</h2><NoticeForm initial={empty()} installs={installs} editing={false} busy={busy} onSave={f => save(f)} onCancel={() => setAdding(false)} /></div>}
<PageMessage msg={msg} onClose={() => setMsg(null)} />
{(open === "new" || editing) && (
<NoticeModal key={open} notice={editing} installs={installs} onClose={() => setOpen(null)}
onSaved={text => { setOpen(null); setMsg({ type: "ok", text }); load(); }} />
)}
{!notices ? <Loading /> : notices.length === 0 ? <p className="text-sm text-slate-500">No notices yet.</p> : (
<div className="space-y-4">
@@ -180,31 +190,22 @@ export default function NoticesPage() {
const st = state(n);
return (
<div key={n.id} className="card">
{editing === n.id ? (
<NoticeForm
initial={{ title: n.title, message: n.message, level: n.level, allInstalls: n.allInstalls, installIds: n.installIds, showBanner: n.showBanner, sendEmail: false, startsAt: toInput(n.startsAt), endsAt: toInput(n.endsAt) }}
installs={installs} editing busy={busy} onSave={f => save(f, n.id)} onCancel={() => setEditing(null)}
/>
) : (
<>
<div className="mb-1 flex flex-wrap items-center gap-2">
<h2 className="font-semibold">{n.title}</h2>
<Badge value={st.value} label={st.label} />
<span className="text-xs text-slate-500">{LEVEL_LABEL[n.level]}</span>
<span className="ml-auto flex gap-2">
{st.label === "Showing" || st.label === "Scheduled" ? <button className="btn-secondary px-2 py-1 text-xs" onClick={() => endNow(n)}>End now</button> : null}
<button className="btn-secondary px-2 py-1 text-xs" onClick={() => { setEditing(n.id); setAdding(false); }}>Edit</button>
<button className="btn-danger px-2 py-1 text-xs" onClick={() => remove(n)}>Delete</button>
</span>
</div>
<p className="whitespace-pre-line text-sm text-slate-700">{n.message}</p>
<div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-500">
<span>To: {n.allInstalls ? "every install" : n.installIds.map(installName).join(", ")}</span>
{n.showBanner && <span>Banner: {n.startsAt ? fmtDate(n.startsAt) : "from creation"} → {n.endsAt ? fmtDate(n.endsAt) : "until ended"}</span>}
{n.emailedAt && <span>Emailed {fmtDate(n.emailedAt)} to {n.emailedTo} address{n.emailedTo === 1 ? "" : "es"}</span>}
</div>
</>
)}
<div className="mb-1 flex flex-wrap items-center gap-2">
<h2 className="font-semibold">{n.title}</h2>
<Badge value={st.value} label={st.label} />
<span className="text-xs text-slate-500">{LEVEL_LABEL[n.level]}</span>
<span className="ml-auto flex gap-2">
{st.label === "Showing" || st.label === "Scheduled" ? <button className="btn-secondary px-2 py-1 text-xs" onClick={() => endNow(n)}>End now</button> : null}
<button className="btn-secondary px-2 py-1 text-xs" onClick={() => setOpen(n.id)}><Pencil className="h-3.5 w-3.5" /> Edit</button>
<button className="btn-danger px-2 py-1 text-xs" onClick={() => remove(n)}>Delete</button>
</span>
</div>
<p className="whitespace-pre-line text-sm text-slate-700">{n.message}</p>
<div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-500">
<span>To: {n.allInstalls ? "every install" : n.installIds.map(installName).join(", ")}</span>
{n.showBanner && <span>Banner: {n.startsAt ? fmtDate(n.startsAt) : "from creation"} → {n.endsAt ? fmtDate(n.endsAt) : "until ended"}</span>}
{n.emailedAt && <span>Emailed {fmtDate(n.emailedAt)} to {n.emailedTo} address{n.emailedTo === 1 ? "" : "es"}</span>}
</div>
</div>
);
})}
+164 -137
View File
@@ -1,56 +1,69 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { GitBranch, Link2, Plus, RefreshCw, ShieldAlert, Trash2 } from "lucide-react";
import { GitBranch, Link2, Pencil, Plus, RefreshCw, ShieldAlert, Trash2 } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { PRODUCTS, PRODUCT_NAMES, type Product } from "@/lib/products";
import type { Release, ReleaseSource } from "@/lib/types";
import { usePaged } from "@/lib/paging";
import { Badge, Loading, Message, PageTitle, Pager, ReleaseNotes } from "@/components/ui";
import { Badge, FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, Pager, ReadCard, ReleaseNotes, useSubmit } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
type Form = { product: Product; version: string; notes: string; urgent: boolean; releasedAt: string };
const today = () => new Date().toISOString().slice(0, 10);
const toBody = (f: Form) => ({ product: f.product, version: f.version, notes: f.notes, urgent: f.urgent, releasedAt: f.releasedAt ? `${f.releasedAt}T12:00:00+02:00` : null });
/** Add or edit one release (only for a product with no release source). */
function ReleaseForm({ initial, products, onSave, onCancel, busy }: { initial: Form; products: Product[] | null; onSave: (f: Form) => void; onCancel?: () => void; busy: boolean }) {
/**
* Add or edit one release (only for a product with no release source). Hub 2.16.0: in a popup.
* `products` lists what a new one can be for; an edit (`id`) keeps its product.
*/
function ReleaseModal({ id, initial, products, onClose, onSaved }: { id?: string; initial: Form; products: Product[] | null; onClose: () => void; onSaved: (text: string) => void }) {
const [form, setForm] = useState(initial);
const { busy, error, run } = useSubmit();
const save = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await api<{ latestVersion: string | null }>(id ? `/api/admin/releases/${id}` : "/api/admin/releases", { method: id ? "PUT" : "POST", body: toBody(form) });
onSaved(`Saved. The latest ${PRODUCT_NAMES[form.product]} version is ${r.latestVersion || "not set"}; its installs see it with their next heartbeat (within 15 minutes).`);
});
};
return (
<form onSubmit={e => { e.preventDefault(); onSave(form); }} className="space-y-3">
<div className="grid gap-3 sm:grid-cols-4">
{products && (
<Modal title={id ? `Edit ${PRODUCT_NAMES[initial.product]} ${initial.version}` : "New release"} onClose={onClose} dirty={JSON.stringify(form) !== JSON.stringify(initial)} wide>
<form onSubmit={save} className="space-y-3">
{!id && <p className="text-xs text-slate-500">Only for products with no release source.</p>}
<div className="grid gap-3 sm:grid-cols-3">
{products && (
<div>
<label className="label" htmlFor="rel_product">Product</label>
<select id="rel_product" className="input" value={form.product} onChange={e => setForm({ ...form, product: e.target.value as Product })}>
{products.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
</select>
</div>
)}
<div>
<label className="label" htmlFor="rel_product">Product</label>
<select id="rel_product" className="input" value={form.product} onChange={e => setForm({ ...form, product: e.target.value as Product })}>
{products.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
</select>
<label className="label" htmlFor="rel_version">Version</label>
<input id="rel_version" className="input" placeholder="1.47.0" value={form.version} onChange={e => setForm({ ...form, version: e.target.value })} required />
</div>
<div>
<label className="label" htmlFor="rel_date">Released</label>
<input id="rel_date" type="date" className="input" value={form.releasedAt} onChange={e => setForm({ ...form, releasedAt: e.target.value })} />
</div>
)}
<div>
<label className="label" htmlFor="rel_version">Version</label>
<input id="rel_version" className="input" placeholder="1.47.0" value={form.version} onChange={e => setForm({ ...form, version: e.target.value })} required />
</div>
<div>
<label className="label" htmlFor="rel_date">Released</label>
<input id="rel_date" type="date" className="input" value={form.releasedAt} onChange={e => setForm({ ...form, releasedAt: e.target.value })} />
</div>
<label className="flex items-center gap-2 self-end pb-2 text-sm">
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={form.urgent} onChange={e => setForm({ ...form, urgent: e.target.checked })} />
Urgent (security or serious bug fix)
</label>
</div>
<div>
<label className="label" htmlFor="rel_notes">What&apos;s new</label>
<textarea id="rel_notes" className="input min-h-40 font-mono" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder={"Written for the church, not for developers.\n- Volunteer rosters: plan who serves where\n- Fixed: kids tickets were offered publicly"} />
<p className="mt-1 text-xs text-slate-500">Lines starting with &quot;- &quot; show as a list. Churches see this on their Licence page before they ask for the update.{form.urgent && " Urgent releases can't be put off with \"Not now\"."}</p>
</div>
<div className="flex flex-wrap gap-2">
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Save release"}</button>
{onCancel && <button type="button" className="btn-secondary" onClick={onCancel}>Cancel</button>}
</div>
</form>
<div>
<label className="label" htmlFor="rel_notes">What&apos;s new</label>
<textarea id="rel_notes" className="input min-h-40 font-mono" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder={"Written for the church, not for developers.\n- Volunteer rosters: plan who serves where\n- Fixed: kids tickets were offered publicly"} />
<p className="mt-1 text-xs text-slate-500">Lines starting with &quot;- &quot; show as a list. Churches see this on their Licence page before they ask for the update.{form.urgent && " Urgent releases can't be put off with \"Not now\"."}</p>
</div>
<FormError error={error} />
<ModalButtons busy={busy} onCancel={onClose} label="Save release" />
</form>
</Modal>
);
}
@@ -60,81 +73,115 @@ type SyncResult = { sources: { source: string; tags: number }[]; added: number;
const latestText = (latest: Partial<Record<Product, string>>) =>
PRODUCTS.filter(p => latest[p]).map(p => `${PRODUCT_NAMES[p]} ${latest[p]}`).join(", ") || "none yet";
/**
* Where releases come from: per product, one or more git sources (a repository, a tag prefix and a
* notes file), synced every 15 minutes.
*/
function Sources({ sources, state, onSaved, setMsg }: { sources: ReleaseSource[]; state: SyncState; onSaved: () => void; setMsg: (m: Msg) => void }) {
/** Saves the list of sources (null: back to the defaults) and the access token. */
const saveSources = (list: ReleaseSource[] | null, token: { value: string; clear: boolean } = { value: "", clear: false }) =>
api("/api/admin/settings", { method: "PUT", body: { settings: { release_sources: list, release_repo_token: token.value, release_repo_token_clear: token.clear } } });
/** Hub 2.16.0: the sources and the access token, edited in a popup. */
function SourcesModal({ sources, tokenSet, onClose, onSaved }: { sources: ReleaseSource[]; tokenSet: boolean; onClose: () => void; onSaved: () => void }) {
const [rows, setRows] = useState<ReleaseSource[]>(sources);
const [token, setToken] = useState({ value: "", clear: false });
const { busy, error, run } = useSubmit();
const set = (i: number, patch: Partial<ReleaseSource>) => setRows(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
const dirty = JSON.stringify(rows) !== JSON.stringify(sources) || token.value !== "" || token.clear;
const save = (e: React.FormEvent) => {
e.preventDefault();
run(async () => { await saveSources(rows, token); onSaved(); });
};
return (
<Modal title="Release sources" onClose={onClose} dirty={dirty} wide>
<form onSubmit={save} className="space-y-4">
<div className="space-y-3">
{rows.map((r, i) => (
<div key={i} className="grid items-end gap-2 rounded-lg border border-slate-200 p-3 sm:grid-cols-[10rem_1fr_auto]">
<div>
<label className="label" htmlFor={`src_product_${i}`}>Product</label>
<select id={`src_product_${i}`} className="input" value={r.product} onChange={e => set(i, { product: e.target.value as Product })}>
{PRODUCTS.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
</select>
</div>
<div><label className="label" htmlFor={`src_repo_${i}`}>Repository</label><input id={`src_repo_${i}`} className="input" value={r.repo} onChange={e => set(i, { repo: e.target.value })} placeholder="https://c-git.crosscode.co.za/joshua/crosscode-platform" required /></div>
<button type="button" className="btn-secondary mb-0.5 px-2" aria-label={`Remove source ${i + 1}`} onClick={() => setRows(rows.filter((_, j) => j !== i))}><Trash2 className="h-4 w-4" /></button>
<div><label className="label" htmlFor={`src_prefix_${i}`}>Tag prefix</label><input id={`src_prefix_${i}`} className="input font-mono" value={r.tagPrefix} onChange={e => set(i, { tagPrefix: e.target.value })} placeholder="events@" /></div>
<div><label className="label" htmlFor={`src_notes_${i}`}>Notes file</label><input id={`src_notes_${i}`} className="input font-mono" value={r.notesPath} onChange={e => set(i, { notesPath: e.target.value })} placeholder="WHATS-NEW.md" /></div>
</div>
))}
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setRows([...rows, { product: "events", repo: rows[0]?.repo || "", tagPrefix: "", notesPath: "WHATS-NEW.md" }])}><Plus className="mr-1 inline h-3.5 w-3.5" /> Add a source</button>
</div>
<div>
<label className="label" htmlFor="repo_token">Access token (private repositories only; used for every source)</label>
<input id="repo_token" className="input" type="password" autoComplete="new-password" disabled={token.clear} placeholder={tokenSet ? "Saved — leave blank to keep it" : "Not needed for public repositories"} value={token.value} onChange={e => setToken({ ...token, value: e.target.value })} />
{tokenSet && <label className="mt-1 flex items-center gap-2 text-xs text-slate-600"><input type="checkbox" checked={token.clear} onChange={e => setToken({ value: "", clear: e.target.checked })} /> Remove the saved token</label>}
</div>
<p className="text-xs text-slate-500">Saving syncs straight away.</p>
<FormError error={error} />
<ModalButtons busy={busy} onCancel={onClose} label="Save sources" />
</form>
</Modal>
);
}
/**
* Where releases come from: per product, one or more git sources (a repository, a tag prefix and a
* notes file), synced every 15 minutes. Hub 2.16.0: a read view; Edit opens the popup.
*/
function Sources({ sources, state, onSaved, setMsg }: { sources: ReleaseSource[]; state: SyncState; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [busy, setBusy] = useState(false);
const [editing, setEditing] = useState(false);
const saved = !!state.release_sources?.trim();
const syncNow = async (prefix = "Synced") => {
setBusy(true);
try {
const r = await api<SyncResult>("/api/admin/releases/sync", { method: "POST" });
const tags = r.sources.reduce((n, s) => n + s.tags, 0);
setMsg({ type: r.problems.length ? "err" : "ok", text: `${prefix}: ${tags} version tags in ${r.sources.length} sources, ${r.added} new, ${r.updated} updated, ${r.removed} removed. Latest: ${latestText(r.latest)}.${r.problems.length ? ` Problems: ${r.problems.join(" ")}` : ""}` });
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
setBusy(false);
onSaved();
};
const save = async (list: ReleaseSource[] | null) => {
setBusy(true);
const useDefaults = async () => {
if (!confirm("Go back to the default sources? Your list is removed.")) return;
setMsg(null);
try {
await api("/api/admin/settings", { method: "PUT", body: { settings: { release_sources: list, release_repo_token: token.value, release_repo_token_clear: token.clear } } });
setToken({ value: "", clear: false });
await syncNow(list ? "Saved and synced" : "Back to the defaults and synced");
} catch (err) { setMsg({ type: "err", text: errorText(err) }); onSaved(); }
setBusy(false);
try { await saveSources(null); await syncNow("Back to the defaults and synced"); } catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const set = (i: number, patch: Partial<ReleaseSource>) => setRows(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
return (
<form onSubmit={e => { e.preventDefault(); save(rows); }} className="card mb-6 space-y-3">
<div className="flex flex-wrap items-center gap-2">
<GitBranch className="h-4 w-4 text-slate-400" />
<h2 className="font-semibold">Release sources</h2>
<span className="text-xs text-slate-500">{saved ? "Your list" : "The defaults"} · last synced {ago(state.release_synced_at || null)}</span>
<button type="button" className="btn-secondary ml-auto px-2 py-1 text-xs" disabled={busy} onClick={async () => { setBusy(true); setMsg(null); await syncNow(); setBusy(false); }}>
<RefreshCw className={`mr-1 inline h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} /> Sync now
</button>
</div>
<p className="text-sm text-slate-600">
Every tag <code>&lt;prefix&gt;1.2.3</code> in a source is a release of its product (e.g. <code>events@2.2.0</code>; the prefix <code>v</code> also takes a bare <code>1.2.3</code>), and a product&apos;s newest is its latest version.
The notes come from the notes file on the default branch, for tagged versions only: a <code>## 1.2.3</code> heading per version, with <code>urgent</code> or <code>security</code> in it for an urgent release
and <code>requires accounts 1.2.0</code> for a release that needs another product first. Checked every 15 minutes. A product with no source has its releases added by hand.
</p>
<div className="space-y-2">
{rows.map((r, i) => (
<div key={i} className="grid items-end gap-2 sm:grid-cols-[10rem_1fr_8rem_14rem_auto]">
<div>
<label className="label" htmlFor={`src_product_${i}`}>Product</label>
<select id={`src_product_${i}`} className="input" value={r.product} onChange={e => set(i, { product: e.target.value as Product })}>
{PRODUCTS.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
</select>
</div>
<div><label className="label" htmlFor={`src_repo_${i}`}>Repository</label><input id={`src_repo_${i}`} className="input" value={r.repo} onChange={e => set(i, { repo: e.target.value })} placeholder="https://c-git.crosscode.co.za/joshua/crosscode-platform" required /></div>
<div><label className="label" htmlFor={`src_prefix_${i}`}>Tag prefix</label><input id={`src_prefix_${i}`} className="input font-mono" value={r.tagPrefix} onChange={e => set(i, { tagPrefix: e.target.value })} placeholder="events@" /></div>
<div><label className="label" htmlFor={`src_notes_${i}`}>Notes file</label><input id={`src_notes_${i}`} className="input font-mono" value={r.notesPath} onChange={e => set(i, { notesPath: e.target.value })} placeholder="WHATS-NEW.md" /></div>
<button type="button" className="btn-secondary mb-0.5 px-2" aria-label={`Remove source ${i + 1}`} onClick={() => setRows(rows.filter((_, j) => j !== i))}><Trash2 className="h-4 w-4" /></button>
<div className="mb-6">
<ReadCard
title={<span className="inline-flex flex-wrap items-center gap-2"><GitBranch className="h-4 w-4 text-slate-400" /> Release sources <span className="text-xs font-normal text-slate-500">{saved ? "Your list" : "The defaults"} · last synced {ago(state.release_synced_at || null)}</span></span>}
onEdit={() => setEditing(true)}
actions={<>
<button type="button" className="btn-secondary px-2.5 py-1.5" disabled={busy} onClick={() => { setMsg(null); syncNow(); }}>
<RefreshCw className={`h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} /> Sync now
</button>
{saved && <button type="button" className="btn-secondary px-2.5 py-1.5" disabled={busy} onClick={useDefaults}>Use the defaults</button>}
</>}
>
<p className="text-sm text-slate-600">
Every tag <code>&lt;prefix&gt;1.2.3</code> in a source is a release of its product (e.g. <code>events@2.2.0</code>; the prefix <code>v</code> also takes a bare <code>1.2.3</code>), and a product&apos;s newest is its latest version.
The notes come from the notes file on the default branch, for tagged versions only: a <code>## 1.2.3</code> heading per version, with <code>urgent</code> or <code>security</code> in it for an urgent release
and <code>requires accounts 1.2.0</code> for a release that needs another product first. Checked every 15 minutes. A product with no source has its releases added by hand.
</p>
{sources.length ? (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="text-left text-xs text-slate-500"><tr><th className="py-1 pr-3">Product</th><th className="pr-3">Repository</th><th className="pr-3">Tag prefix</th><th>Notes file</th></tr></thead>
<tbody>{sources.map((r, i) => (
<tr key={i} className="border-t border-slate-100"><td className="py-1.5 pr-3">{PRODUCT_NAMES[r.product]}</td><td className="break-all pr-3">{r.repo}</td><td className="pr-3 font-mono">{r.tagPrefix || "—"}</td><td className="font-mono">{r.notesPath || "—"}</td></tr>
))}</tbody>
</table>
</div>
))}
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setRows([...rows, { product: "events", repo: rows[0]?.repo || "", tagPrefix: "", notesPath: "WHATS-NEW.md" }])}><Plus className="mr-1 inline h-3.5 w-3.5" /> Add a source</button>
</div>
<div>
<label className="label" htmlFor="repo_token">Access token (private repositories only; used for every source)</label>
<input id="repo_token" className="input" type="password" autoComplete="new-password" disabled={token.clear} placeholder={state.release_repo_token_set ? "Saved — leave blank to keep it" : "Not needed for public repositories"} value={token.value} onChange={e => setToken({ ...token, value: e.target.value })} />
{state.release_repo_token_set && <label className="mt-1 flex items-center gap-2 text-xs text-slate-600"><input type="checkbox" checked={token.clear} onChange={e => setToken({ value: "", clear: e.target.checked })} /> Remove the saved token</label>}
</div>
{state.release_sync_error && <p className="whitespace-pre-line rounded-lg bg-amber-50 p-3 text-sm text-amber-900">{state.release_sync_error}</p>}
<div className="flex flex-wrap gap-2">
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Save sources"}</button>
{saved && <button type="button" className="btn-secondary" disabled={busy} onClick={() => { if (confirm("Go back to the default sources? Your list is removed.")) save(null); }}>Use the defaults</button>}
</div>
</form>
) : <p className="text-sm text-slate-500">No sources: every product&apos;s releases are added by hand.</p>}
<p className="text-xs text-slate-500">Access token: {state.release_repo_token_set ? "saved" : "none (public repositories only)"}</p>
{state.release_sync_error && <p className="whitespace-pre-line rounded-lg bg-amber-50 p-3 text-sm text-amber-900">{state.release_sync_error}</p>}
</ReadCard>
{editing && (
<SourcesModal sources={sources} tokenSet={!!state.release_repo_token_set} onClose={() => setEditing(false)}
onSaved={() => { setEditing(false); setMsg(null); syncNow("Saved and synced"); }} />
)}
</div>
);
}
@@ -142,9 +189,8 @@ function Sources({ sources, state, onSaved, setMsg }: { sources: ReleaseSource[]
export default function ReleasesPage() {
const [releases, setReleases] = useState<Release[] | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [adding, setAdding] = useState(false);
const [editing, setEditing] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
// Hub 2.16.0: the popup that's open: a new release, or the id of the one being edited.
const [open, setOpen] = useState<"new" | string | null>(null);
const [filter, setFilter] = useState<Product | "all">("all");
const [state, setState] = useState<{ settings: SyncState; releaseSources: ReleaseSource[] } | null>(null);
@@ -159,20 +205,8 @@ export default function ReleasesPage() {
const shown = (releases || []).filter(r => filter === "all" || r.product === filter);
// Hub 2.6.0: a page at a time.
const paged = usePaged(shown, filter, 15);
const body = (f: Form) => ({ product: f.product, version: f.version, notes: f.notes, urgent: f.urgent, releasedAt: f.releasedAt ? `${f.releasedAt}T12:00:00+02:00` : null });
const save = async (f: Form, id?: string) => {
setBusy(true);
setMsg(null);
try {
const r = await api<{ latestVersion: string | null }>(id ? `/api/admin/releases/${id}` : "/api/admin/releases", { method: id ? "PUT" : "POST", body: body(f) });
setMsg({ type: "ok", text: `Saved. The latest ${PRODUCT_NAMES[f.product]} version is ${r.latestVersion || "not set"}; its installs see it with their next heartbeat (within 15 minutes).` });
setAdding(false);
setEditing(null);
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
const editing = open && open !== "new" ? releases?.find(r => r.id === open) || null : null;
const saved = (text: string) => { setOpen(null); setMsg({ type: "ok", text }); load(); };
const remove = async (r: Release) => {
if (!confirm(`Delete ${PRODUCT_NAMES[r.product]} ${r.version}? Its installs stop being offered it${r.latest ? ", and the version before it becomes the latest" : ""}.`)) return;
@@ -188,16 +222,15 @@ export default function ReleasesPage() {
<PageTitle
title="Releases"
subtitle="Each product's versions and what's new in them. A product's newest is its latest version: its installs on an older one see “Update available” with the notes for every version they'd get."
actions={!adding && state && manual.length > 0 && <button className="btn-primary" onClick={() => { setAdding(true); setEditing(null); }}>Add release</button>}
actions={state && manual.length > 0 && <button className="btn-primary" onClick={() => setOpen("new")}><Plus className="h-4 w-4" /> Add release</button>}
/>
{msg && <div className="mb-4"><Message msg={msg} /></div>}
{state && <Sources key={state.settings.release_synced_at + state.settings.release_sources} sources={state.releaseSources} state={state.settings} onSaved={load} setMsg={setMsg} />}
{adding && (
<div className="card mb-6">
<h2 className="mb-1 font-semibold">New release</h2>
<p className="mb-3 text-xs text-slate-500">Only for products with no release source.</p>
<ReleaseForm initial={{ product: manual[0], version: "", notes: "", urgent: false, releasedAt: today() }} products={manual} busy={busy} onSave={f => save(f)} onCancel={() => setAdding(false)} />
</div>
<PageMessage msg={msg} onClose={() => setMsg(null)} />
{state && <Sources sources={state.releaseSources} state={state.settings} onSaved={load} setMsg={setMsg} />}
{open === "new" && manual.length > 0 && (
<ReleaseModal initial={{ product: manual[0], version: "", notes: "", urgent: false, releasedAt: today() }} products={manual} onClose={() => setOpen(null)} onSaved={saved} />
)}
{editing && (
<ReleaseModal key={editing.id} id={editing.id} initial={{ product: editing.product, version: editing.version, notes: editing.notes, urgent: editing.urgent, releasedAt: editing.releasedAt.slice(0, 10) }} products={null} onClose={() => setOpen(null)} onSaved={saved} />
)}
<div className="mb-4 flex flex-wrap gap-2" role="group" aria-label="Show releases of">
@@ -212,30 +245,24 @@ export default function ReleasesPage() {
<div className="space-y-4">
{paged.rows.map(r => (
<div key={r.id} className="card">
{editing === r.id ? (
<ReleaseForm initial={{ product: r.product, version: r.version, notes: r.notes, urgent: r.urgent, releasedAt: r.releasedAt.slice(0, 10) }} products={null} busy={busy} onSave={f => save(f, r.id)} onCancel={() => setEditing(null)} />
) : (
<>
<div className="mb-2 flex flex-wrap items-center gap-2">
<h2 className="text-lg font-semibold"><span className="text-slate-500">{PRODUCT_NAMES[r.product]}</span> {r.version}</h2>
{r.latest && <Badge value="ok" label="Latest" />}
{r.urgent && <span className="inline-flex items-center gap-1 rounded-full bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 ring-1 ring-inset ring-red-200"><ShieldAlert className="h-3 w-3" /> Urgent</span>}
{r.requires.length > 0 && (
<span 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">
<Link2 className="h-3 w-3" /> Needs {r.requires.map(q => `${PRODUCT_NAMES[q.product]} ${q.version}`).join(" and ")}
</span>
)}
<span className="text-xs text-slate-500">{fmtDate(r.releasedAt, false)} · {r.installs} install{r.installs === 1 ? "" : "s"} on it</span>
{!fromGit.has(r.product) && (
<span className="ml-auto flex gap-2">
<button className="btn-secondary px-2 py-1 text-xs" onClick={() => { setEditing(r.id); setAdding(false); }}>Edit</button>
<button className="btn-danger px-2 py-1 text-xs" onClick={() => remove(r)}>Delete</button>
</span>
)}
</div>
<ReleaseNotes notes={r.notes} />
</>
)}
<div className="mb-2 flex flex-wrap items-center gap-2">
<h2 className="text-lg font-semibold"><span className="text-slate-500">{PRODUCT_NAMES[r.product]}</span> {r.version}</h2>
{r.latest && <Badge value="ok" label="Latest" />}
{r.urgent && <span className="inline-flex items-center gap-1 rounded-full bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 ring-1 ring-inset ring-red-200"><ShieldAlert className="h-3 w-3" /> Urgent</span>}
{r.requires.length > 0 && (
<span 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">
<Link2 className="h-3 w-3" /> Needs {r.requires.map(q => `${PRODUCT_NAMES[q.product]} ${q.version}`).join(" and ")}
</span>
)}
<span className="text-xs text-slate-500">{fmtDate(r.releasedAt, false)} · {r.installs} install{r.installs === 1 ? "" : "s"} on it</span>
{!fromGit.has(r.product) && (
<span className="ml-auto flex gap-2">
<button className="btn-secondary px-2 py-1 text-xs" onClick={() => setOpen(r.id)}><Pencil className="h-3.5 w-3.5" /> Edit</button>
<button className="btn-danger px-2 py-1 text-xs" onClick={() => remove(r)}>Delete</button>
</span>
)}
</div>
<ReleaseNotes notes={r.notes} />
</div>
))}
<div className="card p-0"><Pager {...paged} /></div>
+120 -108
View File
@@ -8,7 +8,7 @@ import { api, errorText } from "@/lib/api";
import { ago } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import { PRODUCT_NAMES } from "@/lib/products";
import { Loading, Message, PageTitle, Pager, SearchInput } from "@/components/ui";
import { FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, Pager, SearchInput, useSubmit } from "@/components/ui";
import { ServersNav, StatusPill, pct, shownStatus, type Deployment, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -17,40 +17,19 @@ type InstallRow = { id: string; name: string; url: string; customer: { id: strin
const emptyNew = { product: "events", customerId: "", serverId: "", shortName: "", domain: "", accountsDomain: "", timezone: "", adminName: "", adminEmail: "", version: "" };
const emptyLink = { installId: "", serverId: "", shortName: "", webPort: "", apiPort: "" };
const changedFrom = <T extends Record<string, string>>(form: T, empty: T) => (Object.keys(empty) as (keyof T)[]).some(k => form[k] !== empty[k]);
/** Installs on servers: New install (§7) and linking existing installs (§14). */
export default function InstallsPage() {
/** Hub 2.16.0: New install (§7) in a popup; starting it opens the install's page. */
function NewInstallModal({ servers, onClose }: { servers: ServerSummary[]; onClose: () => void }) {
const router = useRouter();
const [list, setList] = useState<Deployment[] | null>(null);
// Hub 2.6.0: which product each install is, a filter for it, a search, and a page at a time.
const [product, setProduct] = useState("");
const [query, setQuery] = useState("");
const shown = useMemo(() => (list || []).filter(d => (!product || d.product === product) && matches(query, d.customer?.name, d.shortName, d.domain, d.server?.name)), [list, product, query]);
const paged = usePaged(shown, `${product}|${query}`);
const [srv, setSrv] = useState<ServerSummary[]>([]);
const [customers, setCustomers] = useState<Customer[]>([]);
const [installs, setInstalls] = useState<InstallRow[]>([]);
const [mode, setMode] = useState<"none" | "new" | "link">("none");
const [form, setForm] = useState(emptyNew);
const [link, setLink] = useState(emptyLink);
const [msg, setMsg] = useState<Msg>(null);
const [busy, setBusy] = useState(false);
const { busy, error, run } = useSubmit();
useEffect(() => { api<Customer[]>("/api/admin/customers").then(setCustomers).catch(() => {}); }, []);
const load = useCallback(() => {
api<{ deployments: Deployment[] }>("/api/admin/deployments").then(r => setList(r.deployments)).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<{ servers: ServerSummary[] }>("/api/admin/servers").then(r => setSrv(r.servers.filter(s => s.mode === "church"))).catch(() => {});
}, []);
useEffect(() => { load(); }, [load]);
useEffect(() => {
if (mode === "new" && !customers.length) api<Customer[]>("/api/admin/customers").then(setCustomers).catch(() => {});
if (mode === "link" && !installs.length) api<InstallRow[]>("/api/admin/installs").then(setInstalls).catch(() => {});
}, [mode, customers.length, installs.length]);
const submitNew = async (e: React.FormEvent) => {
const submit = (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setMsg(null);
try {
run(async () => {
const r = await api<{ deployment: Deployment; warnings: string[]; checkingPorts?: boolean; alsoInstalling?: { product: string; domain: string; version: string } }>("/api/admin/deployments", { method: "POST", body: { ...form, version: form.version || undefined, accountsDomain: form.accountsDomain || undefined } });
// Hub 2.5.0: Cross Events 3.x for a church without Accounts installs Accounts first.
const notes = [
@@ -60,94 +39,127 @@ export default function InstallsPage() {
...r.warnings,
];
router.push(`/servers/installs/${r.deployment.id}${notes.length ? `?warn=${encodeURIComponent(notes.join(" "))}` : ""}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setBusy(false);
};
const submitLink = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setMsg(null);
try {
const r = await api<{ deployment: Deployment }>("/api/admin/deployments/link", { method: "POST", body: link });
router.push(`/servers/installs/${r.deployment.id}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setBusy(false);
});
};
const f = (k: keyof typeof emptyNew) => ({ value: form[k], onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setForm({ ...form, [k]: e.target.value }) });
return (
<Modal title="New install" onClose={onClose} dirty={changedFrom(form, emptyNew)} wide>
<form onSubmit={submit} className="grid gap-3 md:grid-cols-2">
<div className="md:col-span-2">
<label className="label" htmlFor="n-product">Product</label>
<select id="n-product" className="input" {...f("product")}>
<option value="events">Cross Events</option>
<option value="accounts">Accounts (the church&apos;s sign-in)</option>
</select>
<p className="mt-1 text-xs text-slate-500">
{form.product === "accounts"
? "Install Accounts before the Website, the App or Cross Events 3.0. Use the church's short name to add it next to its Events on the same server."
: "A church that already has a product here keeps its short name: the new one is added next to it on the same server."}
</p>
</div>
<div><label className="label" htmlFor="n-cust">Customer</label><select id="n-cust" className="input" required {...f("customerId")}><option value="">Choose…</option>{customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}</select></div>
<div><label className="label" htmlFor="n-short">Short name</label><input id="n-short" className="input" required pattern="[a-z][a-z0-9-]{1,30}" placeholder="hope" {...f("shortName")} /><p className="mt-1 text-xs text-slate-500">Folders, database and tunnels: a-z, 0-9 and -.</p></div>
<div><label className="label" htmlFor="n-domain">Domain</label><input id="n-domain" className="input" required placeholder={form.product === "accounts" ? "accounts.hope.co.za" : "events.hope.co.za"} {...f("domain")} /></div>
{form.product === "events" && (
<div><label className="label" htmlFor="n-acc">Accounts domain</label><input id="n-acc" className="input" placeholder={form.domain ? form.domain.replace(/^[^.]+./, "accounts.") : "accounts.hope.co.za"} {...f("accountsDomain")} /><p className="mt-1 text-xs text-slate-500">Cross Events 3 signs in through the church&apos;s Accounts: a church without it gets it installed first, here.</p></div>
)}
<div><label className="label" htmlFor="n-tz">Time zone</label><input id="n-tz" className="input" placeholder="Africa/Johannesburg" {...f("timezone")} /></div>
<div><label className="label" htmlFor="n-an">Site admin name</label><input id="n-an" className="input" {...f("adminName")} /></div>
<div><label className="label" htmlFor="n-ae">Site admin email</label><input id="n-ae" type="email" className="input" {...f("adminEmail")} /><p className="mt-1 text-xs text-slate-500">Gets the welcome email and update notices.</p></div>
<div className="md:col-span-2">
<span className="label">Server</span>
{!servers.length && <p className="text-sm text-slate-500">No church servers yet. Add one on the Servers page first.</p>}
<div className="grid gap-2 md:grid-cols-2">
{servers.map(s => {
const low = (s.ram?.availableBytes ?? 0) < 1.5 * 1024 ** 3;
return (
<label key={s.id} className={`flex cursor-pointer gap-2 rounded-lg border p-3 text-sm ${form.serverId === s.id ? "border-indigo-500 bg-indigo-50" : "border-slate-200"}`}>
<input type="radio" name="server" value={s.id} checked={form.serverId === s.id} onChange={() => setForm({ ...form, serverId: s.id })} disabled={!s.online} />
<span>
<span className="font-medium">{s.name}</span> <StatusPill status={s.busy ? "busy" : s.online ? "online" : "offline"} />
<span className="block text-xs text-slate-500">RAM free {s.ram ? `${(s.ram.availableBytes / 1024 ** 3).toFixed(1)} GB` : "?"} · CPU day avg {pct(s.lastDay?.cpuAvg)} · disk {pct(s.disk.reduce((m, d) => Math.max(m, d.totalBytes ? (d.usedBytes / d.totalBytes) * 100 : 0), 0))} · {s.deployments ?? 0} site(s)</span>
{low && <span className="block text-xs font-medium text-amber-800">Not recommended: under 1.5 GB RAM free</span>}
</span>
</label>
);
})}
</div>
</div>
<div><label className="label" htmlFor="n-ver">Release</label><input id="n-ver" className="input" placeholder="latest" {...f("version")} /></div>
<div className="space-y-3 md:col-span-2">
<p className="text-xs text-slate-500">The Hub makes the licence, picks two ports, and the agent installs within a minute. You get the report and the FastPanel steps by email.</p>
<FormError error={error} />
<ModalButtons busy={busy} onCancel={onClose} label="Install" busyLabel="Starting…" disabled={!form.serverId} />
</div>
</form>
</Modal>
);
}
/** Hub 2.16.0: link an install that's already on a server (§14), in a popup. */
function LinkInstallModal({ servers, onClose }: { servers: ServerSummary[]; onClose: () => void }) {
const router = useRouter();
const [installs, setInstalls] = useState<InstallRow[]>([]);
const [link, setLink] = useState(emptyLink);
const { busy, error, run } = useSubmit();
useEffect(() => { api<InstallRow[]>("/api/admin/installs").then(setInstalls).catch(() => {}); }, []);
const submit = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await api<{ deployment: Deployment }>("/api/admin/deployments/link", { method: "POST", body: link });
router.push(`/servers/installs/${r.deployment.id}`);
});
};
const l = (k: keyof typeof emptyLink) => ({ value: link[k], onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setLink({ ...link, [k]: e.target.value }) });
return (
<Modal title="Link an install that's already on a server" onClose={onClose} dirty={changedFrom(link, emptyLink)}>
<form onSubmit={submit} className="grid gap-3 sm:grid-cols-2">
<p className="text-sm text-slate-500 sm:col-span-2">For sites installed by hand or moved with <code>crosscode adopt</code>. Nothing on the server changes; the Hub records the server, folder name and ports (see the server&apos;s church.env and frpc.ini).</p>
<div className="sm:col-span-2"><label className="label" htmlFor="l-inst">Install</label><select id="l-inst" className="input" required {...l("installId")}><option value="">Choose…</option>{installs.map(i => <option key={i.id} value={i.id}>{i.customer?.name || i.name} ({i.url})</option>)}</select></div>
<div><label className="label" htmlFor="l-srv">Server</label><select id="l-srv" className="input" required {...l("serverId")}><option value="">Choose…</option>{servers.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}</select></div>
<div><label className="label" htmlFor="l-short">Short name</label><input id="l-short" className="input" required pattern="[a-z][a-z0-9-]{1,30}" placeholder="hope" {...l("shortName")} /></div>
<p className="-mt-1 text-xs text-slate-500 sm:col-span-2">Just the name, not a path: its folder is /var/www/sites/&lt;name&gt;. A site still in an old folder (/var/www/hope-events) gets that name when you move it onto the monorepo.</p>
<div><label className="label" htmlFor="l-web">Web port</label><input id="l-web" className="input" required inputMode="numeric" {...l("webPort")} /></div>
<div><label className="label" htmlFor="l-api">API port</label><input id="l-api" className="input" required inputMode="numeric" {...l("apiPort")} /></div>
<div className="space-y-3 sm:col-span-2">
<FormError error={error} />
<ModalButtons busy={busy} onCancel={onClose} label="Link" busyLabel="Linking…" />
</div>
</form>
</Modal>
);
}
/** Installs on servers: New install (§7) and linking existing installs (§14). */
export default function InstallsPage() {
const [list, setList] = useState<Deployment[] | null>(null);
// Hub 2.6.0: which product each install is, a filter for it, a search, and a page at a time.
const [product, setProduct] = useState("");
const [query, setQuery] = useState("");
const shown = useMemo(() => (list || []).filter(d => (!product || d.product === product) && matches(query, d.customer?.name, d.shortName, d.domain, d.server?.name)), [list, product, query]);
const paged = usePaged(shown, `${product}|${query}`);
const [srv, setSrv] = useState<ServerSummary[]>([]);
const [popup, setPopup] = useState<"new" | "link" | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback(() => {
api<{ deployments: Deployment[] }>("/api/admin/deployments").then(r => setList(r.deployments)).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<{ servers: ServerSummary[] }>("/api/admin/servers").then(r => setSrv(r.servers.filter(s => s.mode === "church"))).catch(() => {});
}, []);
useEffect(() => { load(); }, [load]);
return (
<div>
<PageTitle title="Installs on servers" subtitle="Sites the Hub installs, updates and uninstalls through each server's agent."
actions={<div className="flex gap-2"><button className="btn-secondary" onClick={() => setMode("link")}><Link2 className="h-4 w-4" /> Link existing</button><button className="btn-primary" onClick={() => setMode("new")}><Plus className="h-4 w-4" /> New install</button></div>} />
actions={<div className="flex gap-2"><button className="btn-secondary" onClick={() => setPopup("link")}><Link2 className="h-4 w-4" /> Link existing</button><button className="btn-primary" onClick={() => setPopup("new")}><Plus className="h-4 w-4" /> New install</button></div>} />
<ServersNav active="/servers/installs" />
<Message msg={msg} />
<PageMessage msg={msg} onClose={() => setMsg(null)} />
{mode === "new" && (
<form onSubmit={submitNew} className="card mb-6 grid gap-3 md:grid-cols-2">
<h2 className="font-medium md:col-span-2">New install</h2>
<div className="md:col-span-2">
<label className="label" htmlFor="n-product">Product</label>
<select id="n-product" className="input" {...f("product")}>
<option value="events">Cross Events</option>
<option value="accounts">Accounts (the church&apos;s sign-in)</option>
</select>
<p className="mt-1 text-xs text-slate-500">
{form.product === "accounts"
? "Install Accounts before the Website, the App or Cross Events 3.0. Use the church's short name to add it next to its Events on the same server."
: "A church that already has a product here keeps its short name: the new one is added next to it on the same server."}
</p>
</div>
<div><label className="label" htmlFor="n-cust">Customer</label><select id="n-cust" className="input" required {...f("customerId")}><option value="">Choose…</option>{customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}</select></div>
<div><label className="label" htmlFor="n-short">Short name</label><input id="n-short" className="input" required pattern="[a-z][a-z0-9-]{1,30}" placeholder="hope" {...f("shortName")} /><p className="mt-1 text-xs text-slate-500">Folders, database and tunnels: a-z, 0-9 and -.</p></div>
<div><label className="label" htmlFor="n-domain">Domain</label><input id="n-domain" className="input" required placeholder={form.product === "accounts" ? "accounts.hope.co.za" : "events.hope.co.za"} {...f("domain")} /></div>
{form.product === "events" && (
<div><label className="label" htmlFor="n-acc">Accounts domain</label><input id="n-acc" className="input" placeholder={form.domain ? form.domain.replace(/^[^.]+./, "accounts.") : "accounts.hope.co.za"} {...f("accountsDomain")} /><p className="mt-1 text-xs text-slate-500">Cross Events 3 signs in through the church&apos;s Accounts: a church without it gets it installed first, here.</p></div>
)}
<div><label className="label" htmlFor="n-tz">Time zone</label><input id="n-tz" className="input" placeholder="Africa/Johannesburg" {...f("timezone")} /></div>
<div><label className="label" htmlFor="n-an">Site admin name</label><input id="n-an" className="input" {...f("adminName")} /></div>
<div><label className="label" htmlFor="n-ae">Site admin email</label><input id="n-ae" type="email" className="input" {...f("adminEmail")} /><p className="mt-1 text-xs text-slate-500">Gets the welcome email and update notices.</p></div>
<div className="md:col-span-2">
<span className="label">Server</span>
<div className="grid gap-2 md:grid-cols-2">
{srv.map(s => {
const low = (s.ram?.availableBytes ?? 0) < 1.5 * 1024 ** 3;
return (
<label key={s.id} className={`flex cursor-pointer gap-2 rounded-lg border p-3 text-sm ${form.serverId === s.id ? "border-indigo-500 bg-indigo-50" : "border-slate-200"}`}>
<input type="radio" name="server" value={s.id} checked={form.serverId === s.id} onChange={() => setForm({ ...form, serverId: s.id })} disabled={!s.online} />
<span>
<span className="font-medium">{s.name}</span> <StatusPill status={s.busy ? "busy" : s.online ? "online" : "offline"} />
<span className="block text-xs text-slate-500">RAM free {s.ram ? `${(s.ram.availableBytes / 1024 ** 3).toFixed(1)} GB` : "?"} · CPU day avg {pct(s.lastDay?.cpuAvg)} · disk {pct(s.disk.reduce((m, d) => Math.max(m, d.totalBytes ? (d.usedBytes / d.totalBytes) * 100 : 0), 0))} · {s.deployments ?? 0} site(s)</span>
{low && <span className="block text-xs font-medium text-amber-800">Not recommended: under 1.5 GB RAM free</span>}
</span>
</label>
);
})}
</div>
</div>
<div><label className="label" htmlFor="n-ver">Release</label><input id="n-ver" className="input" placeholder="latest" {...f("version")} /></div>
<div className="flex items-end gap-2 md:col-span-2">
<button className="btn-primary" disabled={busy || !form.serverId}>{busy ? "Starting…" : "Install"}</button>
<button type="button" className="btn-secondary" onClick={() => setMode("none")}>Cancel</button>
<p className="text-xs text-slate-500">The Hub makes the licence, picks two ports, and the agent installs within a minute. You get the report and the FastPanel steps by email.</p>
</div>
</form>
)}
{mode === "link" && (
<form onSubmit={submitLink} className="card mb-6 grid gap-3 md:grid-cols-2">
<h2 className="font-medium md:col-span-2">Link an install that&apos;s already on a server</h2>
<p className="text-sm text-slate-500 md:col-span-2">For sites installed by hand or moved with <code>crosscode adopt</code>. Nothing on the server changes; the Hub records the server, folder name and ports (see the server&apos;s church.env and frpc.ini).</p>
<div><label className="label" htmlFor="l-inst">Install</label><select id="l-inst" className="input" required {...l("installId")}><option value="">Choose…</option>{installs.map(i => <option key={i.id} value={i.id}>{i.customer?.name || i.name} ({i.url})</option>)}</select></div>
<div><label className="label" htmlFor="l-srv">Server</label><select id="l-srv" className="input" required {...l("serverId")}><option value="">Choose…</option>{srv.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}</select></div>
<div><label className="label" htmlFor="l-short">Short name</label><input id="l-short" className="input" required pattern="[a-z][a-z0-9-]{1,30}" placeholder="hope" {...l("shortName")} /><p className="mt-1 text-xs text-slate-500">Just the name, not a path: its folder is /var/www/sites/&lt;name&gt;. A site still in an old folder (/var/www/hope-events) gets that name when you move it onto the monorepo.</p></div>
<div className="grid grid-cols-2 gap-2">
<div><label className="label" htmlFor="l-web">Web port</label><input id="l-web" className="input" required inputMode="numeric" {...l("webPort")} /></div>
<div><label className="label" htmlFor="l-api">API port</label><input id="l-api" className="input" required inputMode="numeric" {...l("apiPort")} /></div>
</div>
<div className="flex gap-2 md:col-span-2"><button className="btn-primary" disabled={busy}>Link</button><button type="button" className="btn-secondary" onClick={() => setMode("none")}>Cancel</button></div>
</form>
)}
{popup === "new" && <NewInstallModal servers={srv} onClose={() => setPopup(null)} />}
{popup === "link" && <LinkInstallModal servers={srv} onClose={() => setPopup(null)} />}
{!list ? <Loading /> : (
<div className="card overflow-x-auto p-0">
+52 -42
View File
@@ -6,66 +6,76 @@ import { Copy, Plus } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, bytes } from "@/lib/format";
import { usePaged } from "@/lib/paging";
import { Loading, Message, PageTitle, Pager } from "@/components/ui";
import { FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, Pager, useSubmit } from "@/components/ui";
import { ServersNav, StatusPill, pct, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
/**
* Hub 2.16.0: Add server in a popup. First the name and kind, then the join command to run on the
* new server. The token works once, so closing before copying it asks first.
*/
function AddServerModal({ onClose }: { onClose: () => void }) {
const [name, setName] = useState("");
const [mode, setMode] = useState<"church" | "central">("church");
const [joined, setJoined] = useState<{ command: string; expiresAt: string } | null>(null);
const [copied, setCopied] = useState(false);
const { busy, error, run } = useSubmit();
const add = (e: React.FormEvent) => {
e.preventDefault();
run(async () => setJoined(await api<{ command: string; expiresAt: string }>("/api/admin/servers/join-token", { method: "POST", body: { name, mode } })));
};
const copy = async () => {
if (!joined) return;
try { await navigator.clipboard.writeText(joined.command); setCopied(true); } catch { /* the command can still be selected by hand */ }
};
const dirty = joined ? (copied ? false : "Close without copying the join command? It's shown only once; you'd make a new one.") : name.trim() !== "";
return (
<Modal title={joined ? `Join ${name}` : "Add server"} onClose={onClose} dirty={dirty}>
{!joined ? (
<form onSubmit={add} className="space-y-3">
<div><label className="label" htmlFor="srv-name">Name</label><input id="srv-name" className="input" value={name} onChange={e => setName(e.target.value)} placeholder="church-server-2" required /></div>
<div><label className="label" htmlFor="srv-mode">Kind</label>
<select id="srv-mode" className="input" value={mode} onChange={e => setMode(e.target.value as "church" | "central")}>
<option value="church">Church server (runs sites)</option>
<option value="central">Central server (FastPanel, read-only checks)</option>
</select>
</div>
<FormError error={error} />
<ModalButtons busy={busy} onCancel={onClose} label="Make the join command" busyLabel="Making…" />
</form>
) : (
<div className="space-y-3">
<p className="text-sm">Run this on the new server as root. The token works once, until {new Date(joined.expiresAt).toLocaleTimeString()}:</p>
<pre className="overflow-x-auto whitespace-pre-wrap break-all rounded-lg bg-slate-900 p-3 text-xs text-slate-100">{joined.command}</pre>
<p className="text-xs text-slate-500">The server shows on this page within a minute of joining. Then set its configuration (database, TRUST_PROXY) on its page.</p>
<div className="flex flex-wrap gap-2 pt-1">
<button type="button" className="btn-secondary" onClick={copy}><Copy className="h-4 w-4" /> {copied ? "Copied" : "Copy"}</button>
<button type="button" className="btn-primary" onClick={onClose}>Done</button>
</div>
</div>
)}
</Modal>
);
}
/** Hub → Servers: every server with its agent, resources and sites; Add server (§3, §10). */
export default function ServersPage() {
const [list, setList] = useState<ServerSummary[] | null>(null);
const paged = usePaged(list || [], null, 20);
const [msg, setMsg] = useState<Msg>(null);
const [adding, setAdding] = useState(false);
const [name, setName] = useState("");
const [mode, setMode] = useState<"church" | "central">("church");
const [joined, setJoined] = useState<{ command: string; expiresAt: string } | null>(null);
const load = useCallback(() => api<{ servers: ServerSummary[] }>("/api/admin/servers").then(r => setList(r.servers)).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
useEffect(() => { load(); const t = setInterval(load, 30000); return () => clearInterval(t); }, [load]);
const add = async (e: React.FormEvent) => {
e.preventDefault();
setMsg(null);
try {
const r = await api<{ command: string; expiresAt: string }>("/api/admin/servers/join-token", { method: "POST", body: { name, mode } });
setJoined(r);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<div>
<PageTitle title="Servers" subtitle="Each server runs the Cross Code agent, which polls the Hub for jobs and reports its health every minute." actions={<button className="btn-primary" onClick={() => { setAdding(true); setJoined(null); setName(""); }}><Plus className="h-4 w-4" /> Add server</button>} />
<PageTitle title="Servers" subtitle="Each server runs the Cross Code agent, which polls the Hub for jobs and reports its health every minute." actions={<button className="btn-primary" onClick={() => setAdding(true)}><Plus className="h-4 w-4" /> Add server</button>} />
<ServersNav active="/servers" />
<Message msg={msg} />
<PageMessage msg={msg} onClose={() => setMsg(null)} />
{adding && (
<div className="card mb-6">
{!joined ? (
<form onSubmit={add} className="flex flex-wrap items-end gap-3">
<div className="min-w-[14rem] flex-1"><label className="label" htmlFor="srv-name">Name</label><input id="srv-name" className="input" value={name} onChange={e => setName(e.target.value)} placeholder="church-server-2" required /></div>
<div><label className="label" htmlFor="srv-mode">Kind</label>
<select id="srv-mode" className="input" value={mode} onChange={e => setMode(e.target.value as "church" | "central")}>
<option value="church">Church server (runs sites)</option>
<option value="central">Central server (FastPanel, read-only checks)</option>
</select>
</div>
<button className="btn-primary">Make the join command</button>
<button type="button" className="btn-secondary" onClick={() => setAdding(false)}>Cancel</button>
</form>
) : (
<div className="space-y-2">
<p className="text-sm">Run this on the new server as root. The token works once, until {new Date(joined.expiresAt).toLocaleTimeString()}:</p>
<pre className="overflow-x-auto rounded-lg bg-slate-900 p-3 text-xs text-slate-100">{joined.command}</pre>
<div className="flex gap-2">
<button className="btn-secondary" onClick={() => navigator.clipboard?.writeText(joined.command)}><Copy className="h-4 w-4" /> Copy</button>
<button className="btn-secondary" onClick={() => { setAdding(false); load(); }}>Done</button>
</div>
<p className="text-xs text-slate-500">The server shows here within a minute of joining. Then set its configuration (database, TRUST_PROXY) on its page.</p>
</div>
)}
</div>
)}
{adding && <AddServerModal onClose={() => { setAdding(false); load(); }} />}
{!list ? <Loading /> : list.length === 0 ? <p className="text-sm text-slate-500">No servers yet. Add one to install churches from the Hub.</p> : (
<div className="grid gap-4 md:grid-cols-2">
@@ -1,33 +1,46 @@
"use client";
import React, { useState } from "react";
import React, { useEffect, 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.
* Hub 2.14.0: a one-off invoice (standby support, set-up…), made as a draft, in a popup. On the
* customer page it's for that church; without `customerId` (Billing, 2.16.0) the church is chosen.
*/
export function OneOffInvoice({ customerId, onClose, onSaved }: { customerId: string; onClose: () => void; onSaved: (inv: Invoice) => void }) {
const [form, setForm] = useState({ issueDate: todayYmd(), notes: "" });
export function OneOffInvoice({ customerId, onClose, onSaved }: { customerId?: string; onClose: () => void; onSaved: (inv: Invoice) => void }) {
const [form, setForm] = useState({ customerId: customerId || "", issueDate: todayYmd(), notes: "" });
const [lines, setLines] = useState<EditLine[]>([{ description: "", quantity: "1", unit: "" }]);
const [customers, setCustomers] = useState<{ id: string; name: string }[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const dirty = !!form.notes || fromEdit(lines).length > 0;
const dirty = !!form.notes || fromEdit(lines).length > 0 || (!customerId && !!form.customerId);
useEffect(() => {
if (!customerId) api<{ id: string; name: string }[]>("/api/admin/billing/customers").then(setCustomers).catch(e => setError(errorText(e)));
}, [customerId]);
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) } }));
onSaved(await api<Invoice>("/api/admin/billing/invoices", { method: "POST", body: { ...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&apos;s made as a draft for you to approve.</p>
{!customerId && (
<div className="max-w-sm">
<label className="label" htmlFor="oo-customer">Church</label>
<select id="oo-customer" className="input" value={form.customerId} onChange={e => setForm({ ...form, customerId: e.target.value })} required>
<option value="">Choose…</option>
{customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
)}
<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>
@@ -4,8 +4,7 @@ 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 { FormError, Modal, ModalButtons } from "@/components/ui";
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. */
@@ -3,8 +3,7 @@
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 { Field, Fields, FormError, Modal, ModalButtons, ReadCard } from "@/components/ui";
import { ADDRESS_OPTIONS, changed, type AddressType, type CustomerBillingData, type Done } from "./shared";
/** Whether the included domain is due for renewal within 30 days. */
+1 -2
View File
@@ -4,8 +4,7 @@ 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 { Field, Fields, FormError, Modal, ModalButtons, ReadCard } from "@/components/ui";
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). */
@@ -6,8 +6,7 @@ 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 { Field, Fields, FormError, Modal, ModalButtons, ReadCard } from "@/components/ui";
import { changed, type CustomerBillingData, type Done } from "./shared";
/**
@@ -9,8 +9,7 @@ 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 { Badge, FormError, Menu, Modal, ModalButtons } from "@/components/ui";
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).";
@@ -1,47 +0,0 @@
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. `danger` for what can't be undone (Hub 2.15.0). */
export function ModalButtons({ busy, onCancel, label = "Save", busyLabel = "Saving…", danger, disabled }: {
busy: boolean; onCancel: () => void; label?: string; busyLabel?: string; danger?: boolean; disabled?: boolean;
}) {
return (
<div className="flex flex-wrap gap-2 pt-1">
<button className={danger ? "btn-danger" : "btn-primary"} disabled={busy || disabled} aria-busy={busy}>{busy ? busyLabel : label}</button>
<button type="button" className="btn-secondary" onClick={onCancel}>Cancel</button>
</div>
);
}
@@ -3,8 +3,7 @@
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 { Field, Fields, FormError, Modal, ModalButtons, ReadCard } from "@/components/ui";
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). */
@@ -3,7 +3,7 @@ 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";
import { ReadCard } from "@/components/ui";
/** The church's sites: where each product runs and when it last checked in. */
export function SitesCard({ c }: { c: Customer }) {
@@ -1,10 +1,9 @@
"use client";
import React, { useState } from "react";
import { FormError, Modal } from "@/components/ui";
import { FormError, Modal, ModalButtons, useSubmit } from "@/components/ui";
import { fromInput, toInput } from "@/components/servers";
import { ModalButtons } from "@/components/customer/ReadCard";
import { H, changed, post, useSubmit, withWarnings, type Done, type Install } from "./shared";
import { H, changed, post, withWarnings, type Done, type Install } from "./shared";
/** Move an old (2.1.x) Events install onto the monorepo: `crosscode adopt` at a planned time. */
export function AdoptModal({ x, onClose, onDone }: { x: Install; onClose: () => void; onDone: Done }) {
@@ -1,9 +1,8 @@
"use client";
import React, { useState } from "react";
import { FormError, Modal } from "@/components/ui";
import { ModalButtons } from "@/components/customer/ReadCard";
import { post, useSubmit, withWarnings, type Done, type Install } from "./shared";
import { FormError, Modal, ModalButtons, useSubmit } from "@/components/ui";
import { post, withWarnings, type Done, type Install } from "./shared";
const PROFILES = [
{ key: "small", label: "Small church: the essentials" },
@@ -3,9 +3,8 @@
import React, { useState } from "react";
import { api } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { FormError, Modal } from "@/components/ui";
import { ModalButtons } from "@/components/customer/ReadCard";
import { useSubmit, type Detail, type Install } from "./shared";
import { FormError, Modal, ModalButtons, useSubmit } from "@/components/ui";
import { type Detail, type Install } from "./shared";
export type RemoveKind = "record" | "forget";
@@ -2,10 +2,9 @@
import React, { useState } from "react";
import { fmtDate } from "@/lib/format";
import { FormError, Modal } from "@/components/ui";
import { FormError, Modal, ModalButtons, useSubmit } from "@/components/ui";
import { fromInput, toInput } from "@/components/servers";
import { ModalButtons } from "@/components/customer/ReadCard";
import { H, post, productName, useSubmit, withWarnings, type Done, type Install, type UninstallPlan } from "./shared";
import { H, post, productName, withWarnings, type Done, type Install, type UninstallPlan } from "./shared";
/**
* Plan an uninstall of one product (2.12.0): the church's data is exported first, then the site
@@ -3,10 +3,9 @@
import React, { useState } from "react";
import type { Release } from "@/lib/types";
import { PRODUCT_NAMES } from "@/lib/products";
import { FormError, Modal } from "@/components/ui";
import { FormError, Modal, ModalButtons, useSubmit } from "@/components/ui";
import { fromInput, toInput } from "@/components/servers";
import { ModalButtons } from "@/components/customer/ReadCard";
import { H, changed, post, productName, useSubmit, withWarnings, type Done, type Install } from "./shared";
import { H, changed, post, productName, withWarnings, type Done, type Install } from "./shared";
/**
* Schedule an update of one install: at a time at least 4 hours away (the church gets notice), or
+1 -20
View File
@@ -1,7 +1,6 @@
"use client";
import { useRef, useState } from "react";
import { api, ApiError, errorText } from "@/lib/api";
import { api, ApiError } from "@/lib/api";
import { PRODUCT_NAMES } from "@/lib/products";
import type { Deployment, Job, ServerSummary } from "@/components/servers";
@@ -52,24 +51,6 @@ export async function post<T = { warnings?: string[] }>(path: string, body: Reco
/** A success message with the Hub's warnings after it. */
export const withWarnings = (ok: string, r?: { warnings?: string[] } | null) => `${ok}${r?.warnings?.length ? ` Note: ${r.warnings.join(" ")}` : ""}`;
/**
* 2.7.1: one click is one job: `run` does nothing while the last one hasn't answered. A thrown
* error lands in `error`, for the popup to show by its button.
*/
export function useSubmit() {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const inFlight = useRef(false);
const run = async (fn: () => Promise<void>) => {
if (inFlight.current) return;
inFlight.current = true;
setBusy(true);
setError(null);
try { await fn(); } catch (e) { setError(errorText(e)); } finally { inFlight.current = false; setBusy(false); }
};
return { busy, error, run };
}
/** 2.12.0: what an uninstall of this install takes with it, and what stops it. */
export function uninstallPlan(d: Detail) {
const x = d.deployment;
+73 -6
View File
@@ -3,7 +3,8 @@
import React from "react";
import { createPortal } from "react-dom";
import { ChevronLeft, ChevronRight, MoreHorizontal, Search, X } from "lucide-react";
import { ChevronLeft, ChevronRight, MoreHorizontal, Pencil, Search, X } from "lucide-react";
import { errorText } from "@/lib/api";
import type { LicenceStatus, Problem } from "@/lib/types";
const STATUS_TONE: Record<string, string> = {
@@ -83,12 +84,12 @@ const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), selec
/**
* 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.
* `dirty` it asks first (2.16.0: a string `dirty` is the question to ask). 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;
title: React.ReactNode; onClose: () => void; dirty?: boolean | string; wide?: boolean; children: React.ReactNode;
}) {
const panel = React.useRef<HTMLDivElement>(null);
const titleId = React.useId();
@@ -96,7 +97,8 @@ export function Modal({ title, onClose, dirty = false, wide = false, children }:
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;
const { dirty } = state.current;
if (dirty && !confirm(typeof dirty === "string" ? dirty : "Close without saving your changes?")) return;
state.current.onClose();
}, []);
@@ -169,6 +171,71 @@ export function FormError({ error }: { error: string | null }) {
return error ? <p role="alert" className="text-sm text-red-700">{error}</p> : null;
}
/**
* One click is one job (2.7.1; shared since 2.16.0): `run` does nothing while the last one hasn't
* answered. A thrown error lands in `error`, for the popup to show by its button.
*/
export function useSubmit() {
const [busy, setBusy] = React.useState(false);
const [error, setError] = React.useState<string | null>(null);
const inFlight = React.useRef(false);
const run = async (fn: () => Promise<void>) => {
if (inFlight.current) return;
inFlight.current = true;
setBusy(true);
setError(null);
try { await fn(); } catch (e) { setError(errorText(e)); } finally { inFlight.current = false; setBusy(false); }
};
return { busy, error, run };
}
// Hub 2.14.0 (shared from 2.16.0): read views with an Edit that opens their popup.
/** 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. `danger` for what can't be undone (Hub 2.15.0). */
export function ModalButtons({ busy, onCancel, label = "Save", busyLabel = "Saving…", danger, disabled }: {
busy: boolean; onCancel: () => void; label?: string; busyLabel?: string; danger?: boolean; disabled?: boolean;
}) {
return (
<div className="flex flex-wrap gap-2 pt-1">
<button className={danger ? "btn-danger" : "btn-primary"} disabled={busy || disabled} aria-busy={busy}>{busy ? busyLabel : label}</button>
<button type="button" className="btn-secondary" onClick={onCancel}>Cancel</button>
</div>
);
}
/** 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);