Devotionals can be written, edited and imported up to two years ahead (was 3 months), and a CSV holds two years in one file (800 rows, 8 MB). GET /api/v2/devotionals answers 2 weeks (from and the 13 days after it) instead of 3 months. Contracts 1.24.0 vendored. No migration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
265 lines
18 KiB
TypeScript
265 lines
18 KiB
TypeScript
"use client";
|
|
|
|
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
|
import { Download, Plus, Upload } from "lucide-react";
|
|
import { api, errorText } from "@/lib/api";
|
|
import { FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, Stat, useSubmit } from "@/components/ui";
|
|
|
|
type Msg = { type: "ok" | "err"; text: string } | null;
|
|
type Translation = { id: string; name: string; language: string; copyright: string; acknowledgement: string };
|
|
type Passage = { reference: string; translation: string; text: string; location: unknown };
|
|
type Devotional = { id: string; date: string; title: string; passage: Passage; body: string; prayer: string | null; author: string | null; updatedAt: string };
|
|
type Overview = {
|
|
today: string; latest: string; aheadMonths: number; ahead: string; appFetchDays: number; devotionals: Devotional[]; empty: string[];
|
|
translations: Translation[]; csv: { columns: string[]; template: string };
|
|
};
|
|
type CsvIssue = { column: string | null; message: string };
|
|
type CsvRow = { line: number; devotional: { date: string; title: string; passage: Passage } | null; errors: CsvIssue[]; warnings: CsvIssue[]; taken: boolean };
|
|
type CsvResult = { fileError: string | null; rows: CsvRow[] };
|
|
|
|
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
|
const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
|
|
const longDate = (d: string) => new Date(`${d}T12:00:00Z`).toLocaleDateString("en-ZA", { weekday: "short", day: "numeric", month: "long", year: "numeric", timeZone: "UTC" });
|
|
|
|
/** The months from today's to the last day's, each as its days (null before the 1st, Monday first). */
|
|
function months(from: string, to: string) {
|
|
const out: { label: string; days: (string | null)[] }[] = [];
|
|
let [y, m] = from.split("-").map(Number);
|
|
const [ty, tm] = to.split("-").map(Number);
|
|
while (y < ty || (y === ty && m <= tm)) {
|
|
const first = new Date(Date.UTC(y, m - 1, 1));
|
|
const count = new Date(Date.UTC(y, m, 0)).getUTCDate();
|
|
const pad = (first.getUTCDay() + 6) % 7;
|
|
const days: (string | null)[] = Array(pad).fill(null);
|
|
for (let d = 1; d <= count; d++) days.push(`${y}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`);
|
|
out.push({ label: `${MONTHS[m - 1]} ${y}`, days });
|
|
m++;
|
|
if (m > 12) { m = 1; y++; }
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** The days from today to two years ahead (2.26.1): filled ones open their devotional, empty ones a new one. */
|
|
function Calendar({ o, onOpen }: { o: Overview; onOpen: (date: string, d: Devotional | null) => void }) {
|
|
const byDate = useMemo(() => new Map(o.devotionals.map(d => [d.date, d])), [o]);
|
|
return (
|
|
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
|
{months(o.today, o.latest).map(month => (
|
|
<div key={month.label} className="card p-3">
|
|
<p className="mb-2 text-sm font-medium">{month.label}</p>
|
|
<div className="grid grid-cols-7 gap-1 text-center text-xs">
|
|
{DAYS.map(d => <span key={d} className="text-slate-400">{d}</span>)}
|
|
{month.days.map((day, i) => {
|
|
if (!day) return <span key={`pad-${i}`} />;
|
|
const inRange = day >= o.today && day <= o.latest;
|
|
const d = byDate.get(day) || null;
|
|
const label = `${longDate(day)}: ${d ? d.title : inRange ? "no devotional yet" : "outside the dates allowed"}`;
|
|
return (
|
|
<button key={day} type="button" disabled={!inRange} title={label} aria-label={label} onClick={() => onOpen(day, d)}
|
|
className={`rounded py-1 ${!inRange ? "text-slate-300" : d ? "bg-emerald-100 font-medium text-emerald-900 hover:bg-emerald-200" : "bg-amber-50 text-amber-900 ring-1 ring-inset ring-amber-200 hover:bg-amber-100"} ${day === o.today ? "outline outline-2 outline-indigo-500" : ""}`}>
|
|
{Number(day.slice(8))}
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
type Form = { date: string; title: string; reference: string; translation: string; passageText: string; body: string; prayer: string; author: string };
|
|
|
|
/** Write or edit one devotional. The passage is quoted as written, never by AI (BIBLE-PERMISSIONS.md). */
|
|
function DevotionalModal({ o, date, existing, onClose, onDone }: { o: Overview; date: string; existing: Devotional | null; onClose: () => void; onDone: (m: Msg) => void }) {
|
|
const first: Form = existing
|
|
? { date: existing.date, title: existing.title, reference: existing.passage.reference, translation: existing.passage.translation, passageText: existing.passage.text, body: existing.body, prayer: existing.prayer || "", author: existing.author || "" }
|
|
: { date, title: "", reference: "", translation: o.translations[0]?.id || "BSB", passageText: "", body: "", prayer: "", author: "Cross Code" };
|
|
const [form, setForm] = useState<Form>(first);
|
|
const { busy, error, run } = useSubmit();
|
|
const f = (k: keyof Form) => ({ value: form[k], onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => setForm({ ...form, [k]: e.target.value }) });
|
|
const translation = o.translations.find(t => t.id === form.translation);
|
|
const dirty = (Object.keys(first) as (keyof Form)[]).some(k => form[k] !== first[k]);
|
|
|
|
const save = (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
run(async () => {
|
|
const r = await api<{ devotional: Devotional; warnings: string[] }>(existing ? `/api/admin/devotionals/${existing.id}` : "/api/admin/devotionals", { method: existing ? "PUT" : "POST", body: form });
|
|
onDone({ type: "ok", text: `${existing ? "Saved" : "Added"}: ${r.devotional.title} on ${longDate(r.devotional.date)}.${r.warnings.length ? ` ${r.warnings.join(" ")}` : ""}` });
|
|
});
|
|
};
|
|
const remove = () => {
|
|
if (!existing || !window.confirm(`Delete "${existing.title}" (${longDate(existing.date)})? Apps drop it at their next nightly fetch.`)) return;
|
|
run(async () => {
|
|
await api(`/api/admin/devotionals/${existing.id}`, { method: "DELETE" });
|
|
onDone({ type: "ok", text: `Deleted: ${existing.title}.` });
|
|
});
|
|
};
|
|
|
|
return (
|
|
<Modal title={existing ? "Edit devotional" : "Write a devotional"} onClose={onClose} dirty={dirty} wide>
|
|
<form onSubmit={save} className="grid gap-3 md:grid-cols-2">
|
|
<div><label className="label" htmlFor="dv-date">Date</label><input id="dv-date" type="date" className="input" required min={existing ? undefined : o.today} max={o.latest} {...f("date")} /></div>
|
|
<div><label className="label" htmlFor="dv-title">Title</label><input id="dv-title" className="input" required maxLength={200} {...f("title")} /></div>
|
|
<div><label className="label" htmlFor="dv-ref">Passage</label><input id="dv-ref" className="input" required placeholder="1 Corinthians 13:4-7" maxLength={100} {...f("reference")} /><p className="mt-1 text-xs text-slate-500">The passage it's about, not whole chapters: more than 25 verses gets a warning.</p></div>
|
|
<div>
|
|
<label className="label" htmlFor="dv-tr">Translation</label>
|
|
<select id="dv-tr" className="input" {...f("translation")}>
|
|
{o.translations.map(t => <option key={t.id} value={t.id}>{t.name} ({t.id})</option>)}
|
|
</select>
|
|
<p className="mt-1 text-xs text-slate-500">Only the free translations until a publisher gives written permission.</p>
|
|
</div>
|
|
<div className="md:col-span-2">
|
|
<label className="label" htmlFor="dv-text">The passage's text</label>
|
|
<textarea id="dv-text" className="input min-h-24" required maxLength={10000} {...f("passageText")} />
|
|
{translation && <p className="mt-1 text-xs text-slate-500">Shown under it in the App, email and WhatsApp: {translation.copyright}</p>}
|
|
</div>
|
|
<div className="md:col-span-2"><label className="label" htmlFor="dv-body">Devotional</label><textarea id="dv-body" className="input min-h-40" required maxLength={20000} {...f("body")} /><p className="mt-1 text-xs text-slate-500">Markdown: a blank line between paragraphs, **bold**, *italic*.</p></div>
|
|
<div className="md:col-span-2"><label className="label" htmlFor="dv-prayer">Prayer (optional)</label><textarea id="dv-prayer" className="input min-h-16" maxLength={5000} {...f("prayer")} /></div>
|
|
<div><label className="label" htmlFor="dv-author">Author (optional)</label><input id="dv-author" className="input" maxLength={200} {...f("author")} /></div>
|
|
<div className="md:col-span-2"><FormError error={error} /></div>
|
|
<div className="flex flex-wrap items-center justify-between gap-2 md:col-span-2">
|
|
{existing ? <button type="button" className="btn-secondary text-red-700" disabled={busy} onClick={remove}>Delete</button> : <span />}
|
|
<ModalButtons busy={busy} onCancel={onClose} label={existing ? "Save" : "Add"} />
|
|
</div>
|
|
</form>
|
|
</Modal>
|
|
);
|
|
}
|
|
|
|
/** Import CSV: choose a file, see every row checked, then import the valid ones. */
|
|
function ImportModal({ o, onClose, onDone }: { o: Overview; onClose: () => void; onDone: (m: Msg) => void }) {
|
|
const [csv, setCsv] = useState<string | null>(null);
|
|
const [fileName, setFileName] = useState("");
|
|
const [result, setResult] = useState<CsvResult | null>(null);
|
|
const [replace, setReplace] = useState(false);
|
|
const { busy, error, run } = useSubmit();
|
|
|
|
const choose = async (file: File | undefined) => {
|
|
setResult(null);
|
|
if (!file) return;
|
|
const text = await file.text();
|
|
setCsv(text);
|
|
setFileName(file.name);
|
|
run(async () => setResult(await api<CsvResult>("/api/admin/devotionals/import/preview", { method: "POST", body: { csv: text } })));
|
|
};
|
|
const valid = result?.rows.filter(r => r.devotional) || [];
|
|
const taken = valid.filter(r => r.taken).length;
|
|
const importing = replace ? valid.length : valid.length - taken;
|
|
|
|
const submit = (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
run(async () => {
|
|
const r = await api<{ created: number; replaced: number; skipped: number; invalid: number }>("/api/admin/devotionals/import", { method: "POST", body: { csv, replace } });
|
|
onDone({ type: "ok", text: `Imported ${r.created} new${r.replaced ? `, replaced ${r.replaced}` : ""}${r.skipped ? `, skipped ${r.skipped} day${r.skipped === 1 ? "" : "s"} already filled` : ""}${r.invalid ? `; ${r.invalid} row${r.invalid === 1 ? "" : "s"} with errors left out` : ""}.` });
|
|
});
|
|
};
|
|
|
|
return (
|
|
<Modal title="Import devotionals from CSV" onClose={onClose} dirty={!!csv} wide>
|
|
<form onSubmit={submit} className="space-y-4">
|
|
<p className="text-sm text-slate-500">
|
|
Columns: {o.csv.columns.join(", ")} (prayer and author may be empty). Dates as YYYY-MM-DD, up to {longDate(o.latest)}; translations {o.translations.map(t => t.id).join(" or ")}. Nothing is saved until you import.
|
|
</p>
|
|
<div>
|
|
<label className="label" htmlFor="im-file">CSV file</label>
|
|
<input id="im-file" type="file" accept=".csv,text/csv" className="block text-sm" onChange={e => choose(e.target.files?.[0])} />
|
|
</div>
|
|
{busy && !result && <Loading />}
|
|
{result?.fileError && <FormError error={`${fileName}: ${result.fileError}`} />}
|
|
{result && !result.fileError && (
|
|
<>
|
|
<p className="text-sm">{valid.length} of {result.rows.length} rows can be imported{taken ? `; ${taken} are for days that already have one` : ""}.</p>
|
|
<div className="max-h-80 overflow-y-auto rounded-lg border border-slate-200">
|
|
<table className="w-full text-sm">
|
|
<thead className="sticky top-0 bg-white"><tr className="text-left text-xs text-slate-500"><th className="px-2 py-1">Line</th><th>Date</th><th>Title</th><th>Check</th></tr></thead>
|
|
<tbody>{result.rows.map(r => (
|
|
<tr key={r.line} className="border-t align-top">
|
|
<td className="px-2 py-1">{r.line}</td>
|
|
<td className="whitespace-nowrap pr-2">{r.devotional?.date || ""}</td>
|
|
<td className="pr-2">{r.devotional ? `${r.devotional.title} · ${r.devotional.passage.reference} (${r.devotional.passage.translation})` : ""}</td>
|
|
<td className="py-1 pr-2">
|
|
{r.errors.map((x, i) => <p key={`e${i}`} className="text-red-700">{x.message}</p>)}
|
|
{r.warnings.map((x, i) => <p key={`w${i}`} className="text-amber-800">{x.message}</p>)}
|
|
{r.devotional && r.taken && <p className="text-amber-800">That day already has one</p>}
|
|
{r.devotional && !r.taken && !r.warnings.length && <p className="text-emerald-700">OK</p>}
|
|
</td>
|
|
</tr>
|
|
))}</tbody>
|
|
</table>
|
|
</div>
|
|
{taken > 0 && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={replace} onChange={e => setReplace(e.target.checked)} /> Replace the {taken} day{taken === 1 ? "" : "s"} already filled (otherwise they're skipped)</label>}
|
|
</>
|
|
)}
|
|
<FormError error={error} />
|
|
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label={`Import ${importing} devotional${importing === 1 ? "" : "s"}`} disabled={!result || !!result.fileError || importing === 0} />
|
|
</form>
|
|
</Modal>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Hub 2.26.0 (APP-1.0-PLAN §6): Cross Code's devotionals, for every Church App set to "From Cross
|
|
* Code". Written or imported up to two years ahead (2.26.1; 3 months before), in the free
|
|
* translations (KJV, BSB). Apps fetch the next 2 weeks once a night, so a change here reaches them by the next morning.
|
|
*/
|
|
export default function DevotionalsPage() {
|
|
const [o, setO] = useState<Overview | null>(null);
|
|
const [msg, setMsg] = useState<Msg>(null);
|
|
const [popup, setPopup] = useState<{ kind: "edit"; date: string; d: Devotional | null } | { kind: "import" } | null>(null);
|
|
|
|
const load = useCallback(() => api<Overview>("/api/admin/devotionals").then(setO).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
|
|
useEffect(() => { load(); }, [load]);
|
|
const done = (m: Msg) => { setPopup(null); setMsg(m); load(); };
|
|
|
|
const downloadTemplate = () => {
|
|
if (!o) return;
|
|
const url = URL.createObjectURL(new Blob([o.csv.template], { type: "text/csv;charset=utf-8" }));
|
|
const a = Object.assign(document.createElement("a"), { href: url, download: "cross-code-devotionals-template.csv" });
|
|
a.click();
|
|
URL.revokeObjectURL(url);
|
|
};
|
|
|
|
const total = o ? o.devotionals.length + o.empty.length : 0;
|
|
return (
|
|
<div>
|
|
<PageTitle title="Devotionals" subtitle="Cross Code's devotionals for every Church App set to “From Cross Code”: up to two years ahead, in the King James Version or the Berean Standard Bible. Each App fetches the next 2 weeks every night, so fill the days well ahead."
|
|
actions={o && (
|
|
<div className="flex flex-wrap gap-2">
|
|
<button type="button" className="btn-secondary" onClick={downloadTemplate}><Download className="h-4 w-4" /> Template</button>
|
|
<button type="button" className="btn-secondary" onClick={() => setPopup({ kind: "import" })}><Upload className="h-4 w-4" /> Import CSV</button>
|
|
<button type="button" className="btn-primary" onClick={() => setPopup({ kind: "edit", date: o.empty[0] || o.today, d: null })}><Plus className="h-4 w-4" /> Write a devotional</button>
|
|
</div>
|
|
)} />
|
|
<PageMessage msg={msg} onClose={() => setMsg(null)} />
|
|
{!o ? (msg ? null : <Loading />) : (
|
|
<div className="space-y-6">
|
|
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
|
|
<Stat label="Filled" value={`${o.devotionals.length} of ${total} days`} tone={o.empty.length ? "amber" : undefined} />
|
|
<Stat label="Next empty day" small value={o.empty[0] ? longDate(o.empty[0]) : "None"} onClick={o.empty[0] ? () => setPopup({ kind: "edit", date: o.empty[0], d: null }) : undefined} />
|
|
<Stat label="Filled until" small value={(() => { const gap = o.empty[0]; const until = o.devotionals.filter(d => !gap || d.date < gap).at(-1); return until ? longDate(until.date) : "Not today yet"; })()} />
|
|
<Stat label="Up to" small value={longDate(o.latest)} sub={`${o.ahead} ahead`} />
|
|
</div>
|
|
<Calendar o={o} onOpen={(date, d) => setPopup({ kind: "edit", date, d })} />
|
|
<div className="card overflow-x-auto p-0">
|
|
<table className="w-full text-sm">
|
|
<thead><tr className="text-left text-xs text-slate-500"><th className="px-4 py-2">Date</th><th>Title</th><th>Passage</th><th>Author</th></tr></thead>
|
|
<tbody>{o.devotionals.map(d => (
|
|
<tr key={d.id} className="border-t">
|
|
<td className="whitespace-nowrap px-4 py-1.5">{longDate(d.date)}</td>
|
|
<td><button type="button" className="text-left text-indigo-700 hover:underline" onClick={() => setPopup({ kind: "edit", date: d.date, d })}>{d.title}</button></td>
|
|
<td className="whitespace-nowrap pr-2">{d.passage.reference} ({d.passage.translation})</td>
|
|
<td className="pr-4">{d.author || ""}</td>
|
|
</tr>
|
|
))}</tbody>
|
|
</table>
|
|
{!o.devotionals.length && <p className="px-4 py-3 text-sm text-slate-500">None yet. Write one, or import a CSV (download the template to start).</p>}
|
|
</div>
|
|
</div>
|
|
)}
|
|
{o && popup?.kind === "edit" && <DevotionalModal o={o} date={popup.date} existing={popup.d} onClose={() => setPopup(null)} onDone={done} />}
|
|
{o && popup?.kind === "import" && <ImportModal o={o} onClose={() => setPopup(null)} onDone={done} />}
|
|
</div>
|
|
);
|
|
}
|