The cap and markup move from the licence to the customer (migrated), use is counted over all the church's installs under one lock per church, and the licence token carries the church's cap. Settings → AI shows product. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
215 lines
13 KiB
TypeScript
215 lines
13 KiB
TypeScript
"use client";
|
|
|
|
import React, { useCallback, useEffect, useState } from "react";
|
|
import Link from "next/link";
|
|
import { useParams } from "next/navigation";
|
|
import { ArrowLeft } from "lucide-react";
|
|
import { api, errorText } from "@/lib/api";
|
|
import { ago, bytes, fmtDate, rand, randFine } from "@/lib/format";
|
|
import { usePaged } from "@/lib/paging";
|
|
import { tierForBand, tierPrice } from "@/lib/tiers";
|
|
import { PRODUCT_NAMES } from "@/lib/products";
|
|
import type { AiHelperUse, AiMonth, AiStatus, Health, InstallEvent, InstallSummary, Licence, Stats, UnmetRequirement } from "@/lib/types";
|
|
import { Badge, Loading, Message, PageTitle, Pager } from "@/components/ui";
|
|
|
|
type Detail = {
|
|
id: string; name: string; url: string; version: string | null; protocolVersion: number; timezone: string | null; notes: string | null;
|
|
adminContact: { name?: string; email?: string } | null; server: { node?: string; postgres?: string; os?: string } | null;
|
|
features: Record<string, unknown> | null; registeredAt: string; lastHeartbeatAt: string | null; releasedAt: string | null;
|
|
health: Health | null; stats: Stats | null;
|
|
customer: { id: string; name: string; aiMonthlyCapCents: number; aiMarkupPercent: number | null };
|
|
licence: (Licence & { tokenPreview: { status: string; validUntil: string; licenceExpiresAt: string | null } }) | null;
|
|
summary: InstallSummary;
|
|
events: InstallEvent[];
|
|
heartbeats: { receivedAt: string; version: string | null; stats: Stats | null }[];
|
|
ai: { status: AiStatus; months: AiMonth[]; helpers: AiHelperUse[] };
|
|
update: { latestVersion: string | null; behind: boolean; unmetRequirements: UnmetRequirement[] };
|
|
};
|
|
|
|
const NO_EVENTS: InstallEvent[] = [];
|
|
|
|
const Row =({ k, v }: { k: string; v: React.ReactNode }) => (
|
|
<div className="flex justify-between gap-4 border-b border-slate-100 py-1.5 text-sm last:border-0"><span className="text-slate-500">{k}</span><span className="text-right">{v}</span></div>
|
|
);
|
|
|
|
/** One install: health, usage, licence, history. */
|
|
export default function InstallPage() {
|
|
const { id } = useParams<{ id: string }>();
|
|
const [d, setD] = useState<Detail | null>(null);
|
|
const [notes, setNotes] = useState("");
|
|
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
|
|
|
|
const load = useCallback(() => api<Detail>(`/api/admin/installs/${id}`).then(x => { setD(x); setNotes(x.notes || ""); }).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
|
|
useEffect(() => { load(); }, [load]);
|
|
const history = usePaged(d?.events || NO_EVENTS, id, 20);
|
|
|
|
if (!d) return msg ? <Message msg={msg} /> : <Loading />;
|
|
const h = d.health || {};
|
|
const s = d.stats || {};
|
|
const tier = tierForBand(s.income?.eventIncome12m);
|
|
const diskPct = h.disk && h.disk.totalBytes ? Math.round((h.disk.freeBytes / h.disk.totalBytes) * 100) : null;
|
|
// One point per day for the last 30 days: registrations in the last 30 days, as reported.
|
|
const daily = new Map<string, number>();
|
|
for (const b of d.heartbeats) daily.set(b.receivedAt.slice(0, 10), b.stats?.registrations?.last30d ?? 0);
|
|
const points = [...daily.entries()];
|
|
const max = Math.max(1, ...points.map(([, v]) => v));
|
|
|
|
const saveNotes = async () => {
|
|
try {
|
|
await api(`/api/admin/installs/${id}`, { method: "PUT", body: { notes } });
|
|
setMsg({ type: "ok", text: "Notes saved." });
|
|
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<Link href="/" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Installs</Link>
|
|
<PageTitle
|
|
title={`${d.customer.name}: ${PRODUCT_NAMES[d.summary.product]}`}
|
|
subtitle={<a href={d.url} target="_blank" rel="noopener noreferrer" className="text-indigo-600 hover:underline">{d.url}</a>}
|
|
actions={<Badge value={d.summary.status} />}
|
|
/>
|
|
{d.releasedAt && <div className="mb-4"><Message msg={{ type: "err", text: `Licence released ${fmtDate(d.releasedAt)} — this install's heartbeats are refused.` }} /></div>}
|
|
{d.summary.problems.length > 0 && (
|
|
<div className="card mb-6 space-y-1">
|
|
{d.summary.problems.map(p => <div key={p.type} className="flex items-center gap-2 text-sm"><Badge value={p.level} /> {p.message}</div>)}
|
|
</div>
|
|
)}
|
|
{d.update.unmetRequirements.length > 0 && (
|
|
<div className="card mb-6 border-amber-200 bg-amber-50 text-sm text-amber-900">
|
|
<p className="font-medium">Updating to {d.update.latestVersion} needs the church's other products first, so Request update is refused until then:</p>
|
|
<ul className="mt-1 list-disc pl-5">
|
|
{d.update.unmetRequirements.map(u => (
|
|
<li key={u.product}>{PRODUCT_NAMES[u.product]} {u.version} or later{u.current ? ` (it runs ${u.current})` : " (not installed)"}</li>
|
|
))}
|
|
</ul>
|
|
</div>
|
|
)}
|
|
|
|
<div className="grid gap-6 md:grid-cols-2">
|
|
<div className="card">
|
|
<h2 className="mb-2 font-semibold">Health</h2>
|
|
<Row k="Last heartbeat" v={`${ago(d.lastHeartbeatAt)} (${fmtDate(d.lastHeartbeatAt)})`} />
|
|
<Row k="Version" v={`${d.version || "—"}${d.summary.behind ? ` (latest ${d.update.latestVersion})` : ""}`} />
|
|
<Row k="Database" v={h.db === false ? "Not OK" : h.db ? "OK" : "—"} />
|
|
<Row k="Background jobs" v={h.jobs ? `${h.jobs.mode || "?"}, ${h.jobs.failedLast24h ?? 0} failed (24 h)` : "—"} />
|
|
<Row k="Last backup" v={h.lastBackupAt ? `${ago(h.lastBackupAt)}` : "none reported"} />
|
|
<Row k="Disk free" v={h.disk ? `${bytes(h.disk.freeBytes)} of ${bytes(h.disk.totalBytes)} (${diskPct}%)` : "—"} />
|
|
<Row k="Errors (24 h)" v={h.errorsLast24h ?? "—"} />
|
|
<Row k="Pending migrations" v={h.pendingMigrations ?? "—"} />
|
|
<Row k="Uptime" v={h.uptimeSeconds != null ? `${Math.round(h.uptimeSeconds / 3600)} h` : "—"} />
|
|
</div>
|
|
|
|
<div className="card">
|
|
<h2 className="mb-2 font-semibold">Usage</h2>
|
|
<Row k="Users" v={s.users ?? "—"} />
|
|
<Row k="Events (active / upcoming / total)" v={s.events ? `${s.events.active ?? 0} / ${s.events.upcoming ?? 0} / ${s.events.total ?? 0}` : "—"} />
|
|
<Row k="Registrations (30 days / total)" v={s.registrations ? `${s.registrations.last30d ?? 0} / ${s.registrations.total ?? 0}` : "—"} />
|
|
<Row k="Tickets (30 days / total)" v={s.tickets ? `${s.tickets.last30d ?? 0} / ${s.tickets.total ?? 0}` : "—"} />
|
|
<Row k="Check-ins (30 days)" v={s.checkIns?.last30d ?? "—"} />
|
|
<Row k="Messages (30 days)" v={s.messages ? `${s.messages.email30d ?? 0} email, ${s.messages.whatsapp30d ?? 0} WhatsApp` : "—"} />
|
|
<Row k="Income (30 days / all time, with donations)" v={s.income ? `${s.income.last30d || "—"} / ${s.income.allTime || "—"}` : "—"} />
|
|
<Row k="Payment providers" v={s.paymentProviders?.join(", ") || "—"} />
|
|
<Row k="Campuses" v={s.campuses == null ? "—" : s.campuses ? `On${s.campusCount != null ? ` — ${s.campusCount} active` : ""}` : "Off"} />
|
|
{points.length > 1 && (
|
|
<div className="mt-3">
|
|
<div className="mb-1 text-xs text-slate-500">Registrations in the last 30 days, per day reported</div>
|
|
<div className="flex h-16 items-end gap-0.5">
|
|
{points.map(([day, v]) => <div key={day} title={`${day}: ${v}`} className="flex-1 rounded-t bg-indigo-300" style={{ height: `${(v / max) * 100}%` }} />)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="card">
|
|
<h2 className="mb-2 font-semibold">Licence</h2>
|
|
{d.licence ? (
|
|
<>
|
|
<Row k="Key" v={<code className="text-xs">{d.licence.key}</code>} />
|
|
<Row k="Status" v={<Badge value={d.licence.status} />} />
|
|
<Row k="Expires" v={d.licence.expiresAt ? fmtDate(d.licence.expiresAt, false) : "no end date"} />
|
|
<Row k="Grace" v={`${d.licence.graceDays} days`} />
|
|
<Row k="Plan" v={d.licence.plan || "—"} />
|
|
<Row k="Event income (12 months)" v={s.income?.eventIncome12m || "not sent (Cross Events before 2.0.2)"} />
|
|
{tier && (
|
|
<Row
|
|
k="Tier for that income"
|
|
v={<>{tier.name} · {tierPrice(tier)}{d.licence.plan !== tier.name && d.licence.plan !== "Trial" && <span className="ml-1 text-amber-700">(plan is {d.licence.plan})</span>}</>}
|
|
/>
|
|
)}
|
|
<Row k="AI cap (church)" v={d.customer.aiMonthlyCapCents ? `${rand(d.customer.aiMonthlyCapCents)} / month` : "off"} />
|
|
<Row k="AI markup" v={d.customer.aiMarkupPercent == null ? "default" : `${d.customer.aiMarkupPercent}%`} />
|
|
<Link href={`/customers/${d.customer.id}`} className="mt-3 inline-block text-sm text-indigo-600 hover:underline">Change the licence →</Link>
|
|
</>
|
|
) : <p className="text-sm text-slate-500">No licence (released).</p>}
|
|
</div>
|
|
|
|
<div className="card">
|
|
<h2 className="mb-2 font-semibold">About</h2>
|
|
<Row k="Admin contact" v={d.adminContact ? `${d.adminContact.name || ""} ${d.adminContact.email ? `<${d.adminContact.email}>` : ""}` : "—"} />
|
|
<Row k="Server" v={d.server ? `Node ${d.server.node || "?"}, Postgres ${d.server.postgres || "?"}, ${d.server.os || "?"}` : "—"} />
|
|
<Row k="Time zone" v={d.timezone || "—"} />
|
|
<Row k="Registered" v={fmtDate(d.registeredAt)} />
|
|
<Row k="Protocol" v={d.protocolVersion} />
|
|
<label className="label mt-3" htmlFor="notes">Notes</label>
|
|
<textarea id="notes" className="input" rows={3} value={notes} onChange={e => setNotes(e.target.value)} />
|
|
<button className="btn-secondary mt-2" onClick={saveNotes}>Save notes</button>
|
|
</div>
|
|
</div>
|
|
|
|
{msg && <div className="mt-4"><Message msg={msg} /></div>}
|
|
|
|
<div className="card mt-6">
|
|
<h2 className="mb-2 font-semibold">AI</h2>
|
|
{!d.ai.status.enabled && d.ai.months.length === 0 ? (
|
|
<p className="text-sm text-slate-500">Off for this site{d.customer.aiMonthlyCapCents ? " (AI isn't set up in Settings → AI, or the licence isn't active)" : " (cap R0)"}.</p>
|
|
) : (
|
|
<>
|
|
<Row k="This month (charged)" v={`${randFine(d.ai.status.usedCents)} of ${rand(d.ai.status.capCents)} (${d.ai.status.usedPercent}%)${d.ai.status.capReached ? " — used up" : ""}`} />
|
|
<Row k="Renews" v={fmtDate(d.ai.status.renewsOn, false)} />
|
|
{d.ai.helpers.length > 0 && <Row k="By helper this month" v={d.ai.helpers.map(h => `${h.helper.replace(/_/g, " ")}: ${h.calls} (${randFine(h.chargedCents)})`).join(" · ")} />}
|
|
{d.ai.months.length > 0 && (
|
|
<div className="mt-3 overflow-x-auto">
|
|
<table className="w-full text-sm">
|
|
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Month</th><th>Uses</th><th>Tokens in / out</th><th className="text-right">Real cost</th><th className="text-right">Charged</th><th className="text-right">Profit</th></tr></thead>
|
|
<tbody>
|
|
{d.ai.months.map(m => (
|
|
<tr key={m.month} className="border-t border-slate-100">
|
|
<td className="py-1">{m.month}</td>
|
|
<td>{m.calls}</td>
|
|
<td>{m.inputTokens.toLocaleString("en-ZA")} / {m.outputTokens.toLocaleString("en-ZA")}</td>
|
|
<td className="text-right">{randFine(m.realCents)}</td>
|
|
<td className="text-right">{randFine(m.chargedCents)}</td>
|
|
<td className="text-right">{randFine(m.profitCents)}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
|
|
<div className="card mt-6">
|
|
<h2 className="mb-3 font-semibold">History</h2>
|
|
{d.events.length === 0 ? <p className="text-sm text-slate-500">Nothing yet.</p> : (
|
|
<>
|
|
<ul className="space-y-2 text-sm">
|
|
{history.rows.map(e => (
|
|
<li key={e.id} className="flex flex-wrap items-center gap-2">
|
|
<span className="w-40 shrink-0 text-xs text-slate-500">{fmtDate(e.createdAt)}</span>
|
|
<Badge value={e.level} />
|
|
<span>{e.message}</span>
|
|
{e.level !== "info" && <span className="text-xs text-slate-400">{e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : "open"}</span>}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
<div className="-mx-5 -mb-5 mt-3"><Pager {...history} /></div>
|
|
</>
|
|
)}
|
|
</div>
|
|
</>
|
|
);
|
|
}
|