- Add server, Add customer, New install and Link existing open in popups (Modal from 2.14.0): ask before discarding, error by the button; saving still opens the new page. - Add server: the join command in the same popup; closing before Copy asks first (Modal's `dirty` can now be the question to ask). - Notices and Releases: one popup for new and edit (NoticeModal, ReleaseModal); the cards are read views. Release sources: a table with Sync now and Use the defaults; Edit opens the rows and the access token in a popup and saving syncs. - One-off invoice on Billing is the OneOffInvoice popup with a church picker; NewInvoice goes and /billing/invoices/new opens the popup (/billing?oneoff=1). - These pages use PageMessage. Frontend only: no migration, no API changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
217 lines
13 KiB
TypeScript
217 lines
13 KiB
TypeScript
"use client";
|
|
|
|
import React, { useCallback, useEffect, useMemo, useState } from "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, FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, SearchInput, useSubmit } from "@/components/ui";
|
|
|
|
type Msg = { type: "ok" | "err"; text: string } | null;
|
|
|
|
const LEVELS: { key: NoticeLevel; label: string; hint: string }[] = [
|
|
{ key: "info", label: "Information", hint: "Blue banner" },
|
|
{ key: "maintenance", label: "Planned maintenance", hint: "Amber banner" },
|
|
{ key: "warning", label: "Important", hint: "Red banner" },
|
|
];
|
|
const LEVEL_LABEL = Object.fromEntries(LEVELS.map(l => [l.key, l.label])) as Record<NoticeLevel, string>;
|
|
|
|
// <input type="datetime-local"> works in the browser's time; the API takes ISO.
|
|
const toInput = (d: string | null) => {
|
|
if (!d) return "";
|
|
const x = new Date(d);
|
|
return new Date(x.getTime() - x.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
|
|
};
|
|
const fromInput = (v: string) => (v ? new Date(v).toISOString() : null);
|
|
|
|
type Form = { title: string; message: string; level: NoticeLevel; allInstalls: boolean; installIds: string[]; showBanner: boolean; sendEmail: boolean; startsAt: string; endsAt: string };
|
|
const empty = (): Form => ({ title: "", message: "", level: "info", allInstalls: true, installIds: [], showBanner: true, sendEmail: false, startsAt: "", endsAt: "" });
|
|
|
|
function state(n: Notice, now = Date.now()) {
|
|
if (!n.showBanner) return { label: "Email only", value: "info" as const };
|
|
if (n.endsAt && new Date(n.endsAt).getTime() <= now) return { label: "Ended", value: "info" as const };
|
|
if (n.startsAt && new Date(n.startsAt).getTime() > now) return { label: "Scheduled", value: "warning" as const };
|
|
return { label: "Showing", value: "ok" as const };
|
|
}
|
|
|
|
/** Pick every install or some of them. */
|
|
function Audience({ installs, form, setForm }: { installs: InstallSummary[]; form: Form; setForm: (f: Form) => void }) {
|
|
const [query, setQuery] = useState("");
|
|
const shown = useMemo(() => installs.filter(i => matches(query, i.name, i.url, i.customer?.name)), [installs, query]);
|
|
const toggle = (id: string) => setForm({ ...form, installIds: form.installIds.includes(id) ? form.installIds.filter(x => x !== id) : [...form.installIds, id] });
|
|
return (
|
|
<fieldset className="space-y-2">
|
|
<legend className="label">Who gets it</legend>
|
|
<div className="flex flex-wrap gap-4 text-sm">
|
|
<label className="flex items-center gap-2"><input type="radio" checked={form.allInstalls} onChange={() => setForm({ ...form, allInstalls: true })} /> Every install</label>
|
|
<label className="flex items-center gap-2"><input type="radio" checked={!form.allInstalls} onChange={() => setForm({ ...form, allInstalls: false })} /> Chosen installs ({form.installIds.length})</label>
|
|
</div>
|
|
{!form.allInstalls && (
|
|
<div className="rounded-lg border border-slate-200 p-3">
|
|
<SearchInput className="mb-2" value={query} onChange={setQuery} placeholder="Search installs" />
|
|
<div className="max-h-56 space-y-1 overflow-y-auto">
|
|
{shown.length === 0 && <p className="text-sm text-slate-500">No installs match.</p>}
|
|
{shown.map(i => (
|
|
<label key={i.id} className="flex items-center gap-2 text-sm">
|
|
<input type="checkbox" checked={form.installIds.includes(i.id)} onChange={() => toggle(i.id)} />
|
|
<span className="font-medium">{i.customer?.name || i.name}</span>
|
|
<span className="truncate text-xs text-slate-500">{i.url}</span>
|
|
</label>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</fieldset>
|
|
);
|
|
}
|
|
|
|
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 (
|
|
<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_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'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'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>
|
|
)}
|
|
<FormError error={error} />
|
|
<ModalButtons busy={busy} onCancel={onClose} label={editing ? "Save notice" : form.sendEmail ? "Create and email" : "Create notice"} />
|
|
</form>
|
|
</Modal>
|
|
);
|
|
}
|
|
|
|
/** Messages to churches: a banner on their site and/or an email. */
|
|
export default function NoticesPage() {
|
|
const [notices, setNotices] = useState<Notice[] | null>(null);
|
|
const [installs, setInstalls] = useState<InstallSummary[]>([]);
|
|
const [msg, setMsg] = useState<Msg>(null);
|
|
// 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(() => {
|
|
load();
|
|
api<InstallSummary[]>("/api/admin/installs").then(rows => setInstalls(rows.filter(i => !i.releasedAt))).catch(() => {});
|
|
}, [load]);
|
|
|
|
const installName = (id: string) => { const i = installs.find(x => x.id === id); return i ? i.customer?.name || i.name : "(removed install)"; };
|
|
|
|
const endNow = async (n: Notice) => {
|
|
try {
|
|
await api(`/api/admin/notices/${n.id}`, { method: "PUT", body: { endsAt: new Date().toISOString() } });
|
|
setMsg({ type: "ok", text: "Ended. Sites take the banner down after their next heartbeat (within 15 minutes)." });
|
|
load();
|
|
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
|
|
};
|
|
|
|
const remove = async (n: Notice) => {
|
|
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={<button className="btn-primary" onClick={() => setOpen("new")}><Plus className="h-4 w-4" /> New notice</button>}
|
|
/>
|
|
<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">
|
|
{notices.map(n => {
|
|
const st = state(n);
|
|
return (
|
|
<div key={n.id} className="card">
|
|
<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>
|
|
);
|
|
})}
|
|
</div>
|
|
)}
|
|
</>
|
|
);
|
|
}
|