Files
crosscode-platform/apps/events/frontend/src/components/admin/AccountsMessaging.tsx
T
joshuaandClaude Opus 5.5 cc18b7b514 Events 3.1.0, Accounts 1.2.0, contracts 1.9.0: the move needs Accounts' email
A church moved sign-in to Accounts without email set up there: codes and
password links couldn't be sent, sign-in failed with a 500, nobody could
get in.

- contracts 1.9.0: messaging.status/test/set (SMTP, WAWP; secrets sealed);
  people.ensure answers emailSent.
- Accounts 1.2.0: SendError instead of a 500; WhatsApp codes fall back to
  email; forgot password says email isn't set up; setup only offers
  methods that work; messaging.* (test, save only what worked); test
  WhatsApp in admin; WAWP from .env.
- Events 3.1.0: Settings -> Sign-in shows what Accounts can send and
  copies this site's SMTP/WAWP into it (secrets stay on the server), test
  then save; Move disabled and refused (EMAIL_NOT_READY) without email.
Tests: Accounts 54, contracts 218, Events 774, test:accounts 16 (also on
Postgres).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:41:31 +02:00

146 lines
10 KiB
TypeScript

"use client";
import React, { useEffect, useState } from "react";
import { Mail, MessageCircle } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiV2, type V2Result } from "@/lib/apiV2";
import { errorMessage } from "@/lib/utils";
type Overview = V2Result<"/settings/sign-in/messaging", "get">["data"];
type Answer = V2Result<"/settings/sign-in/messaging", "post">["data"];
type Result = { ok: boolean; error: string | null; saved: boolean } | null;
/**
* Email and WhatsApp for the church's Accounts (3.1.0): Accounts sends its own sign-in codes and
* password links, with its own settings, so they're set up before sign-in moves there. This site's
* own settings are offered to copy (its password and WAWP token stay on the server: leave the field
* blank to use them), tested through Accounts, and saved there only once the test worked.
*/
export function AccountsMessaging({ onReady }: { onReady: (ready: { email: boolean; whatsapp: boolean }) => void }) {
const { token, user } = useAuth();
const [data, setData] = useState<Overview | null>(null);
const [err, setErr] = useState<string | null>(null);
const [email, setEmail] = useState({ host: "", port: "587", secure: false, user: "", from: "", pass: "", to: "" });
const [wa, setWa] = useState({ instanceId: "", accessToken: "", to: "" });
const [emailResult, setEmailResult] = useState<Result>(null);
const [waResult, setWaResult] = useState<Result>(null);
const [testedEmail, setTestedEmail] = useState<string | null>(null);
const [testedWa, setTestedWa] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const load = () => {
if (!token) return;
apiV2("get", "/settings/sign-in/messaging", { authToken: token })
.then(({ data: d }) => {
setData(d);
if (d.accounts) onReady({ email: d.accounts.email.ready, whatsapp: d.accounts.whatsapp.ready });
const e = d.events.email;
if (e) setEmail((x) => (x.host ? x : { ...x, host: e.host, port: String(e.port), secure: e.secure, user: e.user, from: e.from }));
if (d.events.whatsapp) setWa((x) => (x.instanceId ? x : { ...x, instanceId: d.events.whatsapp!.instanceId }));
})
.catch((e) => setErr(errorMessage(e) || "Could not load the email settings."));
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- once per sign-in
useEffect(load, [token]);
useEffect(() => {
setEmail((x) => (x.to ? x : { ...x, to: user?.email || "" }));
setWa((x) => (x.to ? x : { ...x, to: user?.phoneNumber || "" }));
}, [user]);
if (!token) return null;
if (!data) return err ? <p className="text-sm text-red-700">{err}</p> : <p className="text-sm text-gray-500">Loading email settings…</p>;
const emailKey = JSON.stringify({ ...email, to: undefined });
const waKey = JSON.stringify({ ...wa, to: undefined });
const emailBody = () => ({ email: { host: email.host, port: parseInt(email.port, 10) || 587, secure: email.secure, user: email.user, from: email.from, pass: email.pass || null, to: email.to } });
const waBody = () => ({ whatsapp: { instanceId: wa.instanceId, accessToken: wa.accessToken || null, to: wa.to } });
const run = async (key: string, save: boolean, body: object, after: (a: Answer) => void) => {
setBusy(key);
setErr(null);
try {
const { data: a } = save
? await apiV2("post", "/settings/sign-in/messaging", { authToken: token, body: body as never })
: await apiV2("post", "/settings/sign-in/messaging/test", { authToken: token, body: body as never });
after(a);
setData((d) => (d ? { ...d, accounts: { email: a.status.email, whatsapp: a.status.whatsapp }, accountsError: null } : d));
onReady({ email: a.status.email.ready, whatsapp: a.status.whatsapp.ready });
} catch (e) {
setErr(errorMessage(e) || "That didn't work.");
}
setBusy(null);
};
const acc = data.accounts;
const input = "w-full rounded-lg border px-3 py-2 text-sm";
const line = (r: Result, what: string) => r && (
<p className={`text-sm ${r.ok ? "text-green-800" : "text-red-800"}`} role="status">
{r.ok ? (r.saved ? `Saved in Accounts: ${what} works there now.` : `The test ${what} went. Check it arrived, then save.`) : `The test didn't work: ${r.error}`}
</p>
);
return (
<section className="border rounded-xl p-4 space-y-4">
<div>
<h3 className="font-medium">Email and WhatsApp for the church&apos;s sign-in</h3>
<p className="text-sm text-gray-600">Accounts sends sign-in codes and password links itself, with its own settings. Without email there, nobody can sign in after the move.</p>
</div>
{data.accountsError ? (
<p className="text-sm text-red-700">Accounts can&apos;t be reached: {data.accountsError}</p>
) : acc && (
<ul className="text-sm space-y-1">
<li className="flex items-center gap-2"><Mail className="h-4 w-4" aria-hidden /> Email: {acc.email.ready ? <span className="text-green-800">works{acc.email.from ? ` (from ${acc.email.from})` : ""}</span> : <span className="font-medium text-red-800">not set up</span>}</li>
<li className="flex items-center gap-2"><MessageCircle className="h-4 w-4" aria-hidden /> WhatsApp: {acc.whatsapp.ready ? <span className="text-green-800">works</span> : <span className="text-amber-800">not set up (WhatsApp codes then go by email)</span>}</li>
</ul>
)}
{err && <p className="text-sm text-red-800">{err}</p>}
<details open={!!acc && !acc.email.ready} className="rounded-lg border p-3">
<summary className="cursor-pointer text-sm font-medium">{acc?.email.ready ? "Change Accounts' email" : "Set up Accounts' email"}{data.events.email ? " (copied from this site)" : ""}</summary>
<div className="mt-3 grid gap-3 md:grid-cols-2">
<label className="text-sm">SMTP server<input className={input} value={email.host} onChange={(e) => setEmail({ ...email, host: e.target.value })} /></label>
<label className="text-sm">Port<input className={input} inputMode="numeric" value={email.port} onChange={(e) => setEmail({ ...email, port: e.target.value })} /></label>
<label className="text-sm">User name<input className={input} value={email.user} onChange={(e) => setEmail({ ...email, user: e.target.value })} autoComplete="off" /></label>
<label className="text-sm">Password<input className={input} type="password" value={email.pass} onChange={(e) => setEmail({ ...email, pass: e.target.value })} autoComplete="new-password" placeholder={data.events.email?.hasPass ? "Leave blank to use this site's password" : ""} /></label>
<label className="text-sm">Send from<input className={input} value={email.from} onChange={(e) => setEmail({ ...email, from: e.target.value })} /></label>
<label className="flex items-center gap-2 text-sm md:mt-6"><input type="checkbox" checked={email.secure} onChange={(e) => setEmail({ ...email, secure: e.target.checked })} /> TLS from the start (port 465)</label>
<label className="text-sm md:col-span-2">Send the test email to<input className={input} type="email" value={email.to} onChange={(e) => setEmail({ ...email, to: e.target.value })} /></label>
</div>
<div className="mt-3 flex flex-wrap gap-2">
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy || !email.host || !email.to}
onClick={() => run("email-test", false, emailBody(), (a) => { setEmailResult(a.email); if (a.email?.ok) setTestedEmail(emailKey); })}>
{busy === "email-test" ? "Sending…" : "Send a test email"}
</button>
<button type="button" className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm disabled:opacity-50" disabled={!!busy || testedEmail !== emailKey}
title={testedEmail !== emailKey ? "Send a test with these settings first" : undefined}
onClick={() => run("email-save", true, emailBody(), (a) => setEmailResult(a.email))}>
{busy === "email-save" ? "Saving…" : "Save in Accounts"}
</button>
</div>
<div className="mt-2">{line(emailResult, "email")}</div>
</details>
<details className="rounded-lg border p-3">
<summary className="cursor-pointer text-sm font-medium">{acc?.whatsapp.ready ? "Change Accounts' WhatsApp (WAWP)" : "Set up Accounts' WhatsApp (WAWP), optional"}{data.events.whatsapp ? " (copied from this site)" : ""}</summary>
<div className="mt-3 grid gap-3 md:grid-cols-2">
<label className="text-sm">WAWP instance id<input className={input} value={wa.instanceId} onChange={(e) => setWa({ ...wa, instanceId: e.target.value })} /></label>
<label className="text-sm">WAWP access token<input className={input} type="password" value={wa.accessToken} onChange={(e) => setWa({ ...wa, accessToken: e.target.value })} autoComplete="new-password" placeholder={data.events.whatsapp?.hasToken ? "Leave blank to use this site's token" : ""} /></label>
<label className="text-sm md:col-span-2">Send the test message to<input className={input} type="tel" value={wa.to} onChange={(e) => setWa({ ...wa, to: e.target.value })} placeholder="082 123 4567" /></label>
</div>
<div className="mt-3 flex flex-wrap gap-2">
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy || !wa.instanceId || !wa.to}
onClick={() => run("wa-test", false, waBody(), (a) => { setWaResult(a.whatsapp); if (a.whatsapp?.ok) setTestedWa(waKey); })}>
{busy === "wa-test" ? "Sending…" : "Send a test WhatsApp"}
</button>
<button type="button" className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm disabled:opacity-50" disabled={!!busy || testedWa !== waKey}
title={testedWa !== waKey ? "Send a test with these settings first" : undefined}
onClick={() => run("wa-save", true, waBody(), (a) => setWaResult(a.whatsapp))}>
{busy === "wa-save" ? "Saving…" : "Save in Accounts"}
</button>
</div>
<div className="mt-2">{line(waResult, "WhatsApp")}</div>
</details>
</section>
);
}