WORKFLOW-APP/components/DirectorAppointmentTab.tsx
Ysterbaard 1fecf02214 Add pre-send validation gate + idempotent sign-back to appointment flow
PB: 3 new fields on ysterbaard_director_appointments
  - proceed_anyway (bool) — true if user proceeded with missing emails
  - missing_emails (text) — comma-separated keys
  - missing_emails_detail (text) — JSON per-recipient validation

App:
  - POST /api/appointments: builds recipient report (initial +
    distro); returns 422 + report if proceed_anyway is missing
    and any recipient is missing/invalid. preview=1 returns the
    report without sending.
  - PATCH /api/appointments/[id]: tightened idempotency guard to
    also short-circuit on signature_received (not just
    mail_sent_to_all). Prevents double-send on double-click.
  - DirectorAppointmentTab: two-step modal — "Validate recipients"
    surfaces the report (status dots + per-recipient email),
    then Send / Proceed anyway / Fix records first. New
    "company_email" gap surfaced before any email leaves.
  - lib/format.ts: isValidEmail() shared helper.

End-to-end tested: 422 enforces server-side, preview returns
the report, double-PATCH signs only once.
2026-08-18 21:29:08 +02:00

521 lines
22 KiB
TypeScript

"use client";
// components/DirectorAppointmentTab.tsx
// Table of all director appointments + "Acceptance Letter" modal
// with a pre-send validation gate (per SJ 2026-08-18): the modal shows
// the resolved recipient list (new director + linked directors + company
// email) and flags any missing/invalid emails BEFORE sending. The user
// can Cancel, Edit (jump to the edit screen), or Proceed anyway.
import { useEffect, useState, useCallback } from "react";
import type { YsterbaardDirectorAppointment } from "@/lib/types";
type Status = YsterbaardDirectorAppointment["status"];
const STATUS_LABELS: Record<Status, string> = {
pending: "Pending",
mail_sent: "Mail sent",
signature_received: "Signature received",
mail_sent_to_all: "Mail sent to all",
};
const STATUS_VARIANTS: Record<Status, "muted" | "warn" | "success" | "info"> = {
pending: "muted",
mail_sent: "warn",
signature_received: "success",
mail_sent_to_all: "info",
};
interface DirectorOption { id: string; label: string; email?: string; telephone?: string; }
interface CompanyOption { id: string; label: string; }
interface Appointment extends YsterbaardDirectorAppointment {
_director_name?: string;
_company_name?: string;
}
type RecipientStatus = "valid" | "missing" | "invalid";
interface Recipient {
key: string;
label: string;
email: string;
role: string;
status: RecipientStatus;
}
interface ValidationReport {
preview: boolean;
initial: Recipient[];
distro: Recipient[];
problems: number;
}
function StatusBadge({ variant, children }: { variant: string; children: React.ReactNode }) {
const classes: Record<string, string> = {
muted: "bg-slate-100 text-slate-600",
warn: "bg-amber-100 text-amber-700",
success: "bg-green-100 text-green-700",
info: "bg-teal-100 text-teal-700",
};
return (
<span className={`inline-flex px-2 py-0.5 rounded text-xs font-semibold ${classes[variant] || "bg-slate-100 text-slate-600"}`}>
{children}
</span>
);
}
function StatusDot({ status }: { status: RecipientStatus }) {
if (status === "valid") {
return (
<span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-green-100 text-green-700 text-xs font-bold flex-shrink-0" title="Valid email">✓</span>
);
}
if (status === "missing") {
return (
<span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-amber-100 text-amber-700 text-xs font-bold flex-shrink-0" title="Missing email">!</span>
);
}
return (
<span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-red-100 text-red-700 text-xs font-bold flex-shrink-0" title="Invalid format">x</span>
);
}
export default function DirectorAppointmentTab() {
const [appointments, setAppointments] = useState<Appointment[]>([]);
const [loading, setLoading] = useState(true);
const [showModal, setShowModal] = useState(false);
const [sending, setSending] = useState(false);
const [sendError, setSendError] = useState<string | null>(null);
// Modal form state
const [directors, setDirectors] = useState<DirectorOption[]>([]);
const [companies, setCompanies] = useState<CompanyOption[]>([]);
const [selectedDirector, setSelectedDirector] = useState("");
const [selectedCompany, setSelectedCompany] = useState("");
// Validation gate
const [report, setReport] = useState<ValidationReport | null>(null);
const [previewing, setPreviewing] = useState(false);
const loadAppointments = useCallback(async () => {
try {
const res = await fetch("/api/appointments");
if (!res.ok) throw new Error();
const data = await res.json();
const items: Appointment[] = (data.items || []).map((item: YsterbaardDirectorAppointment) => ({
...item,
_director_name: item.expand?.director
? [item.expand.director.first_names, item.expand.director.surname].filter(Boolean).join(" ")
: item.expand?.director?.first_names || "—",
_company_name: item.expand?.company?.enterprise_name || "—",
}));
setAppointments(items);
} catch {
// silently fail
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
loadAppointments();
}, [loadAppointments]);
const openModal = async () => {
setShowModal(true);
setSendError(null);
setSelectedDirector("");
setSelectedCompany("");
setReport(null);
// Load directors
try {
const res = await fetch("/api/directors/list");
if (res.ok) {
const data = await res.json();
setDirectors(
(data.items || []).map((d: { id: string; first_names?: string; surname?: string; email?: string; telephone?: string }) => ({
id: d.id,
label: [d.first_names, d.surname].filter(Boolean).join(" ") || d.id,
email: d.email,
telephone: d.telephone,
}))
);
}
} catch { /* ignore */ }
// Load companies
try {
const res = await fetch("/api/companies/list");
if (res.ok) {
const data = await res.json();
setCompanies(
(data.items || []).map((c: { id: string; enterprise_name?: string }) => ({
id: c.id,
label: c.enterprise_name || c.id,
}))
);
}
} catch { /* ignore */ }
};
// Fetch the full company record so we can show the company email in the
// validation panel.
const fetchCompanyDetails = async (id: string) => {
try {
const res = await fetch(`/api/pb/records/get?collection=ysterbaard_companies&id=${id}&fields=id,enterprise_name,company_email`);
if (res.ok) return res.json();
} catch { /* ignore */ }
return null;
};
const fetchDirectorDetails = async (id: string) => {
try {
const res = await fetch(`/api/pb/records/get?collection=ysterbaard_directors&id=${id}&fields=id,first_names,surname,email`);
if (res.ok) return res.json();
} catch { /* ignore */ }
return null;
};
const handlePreview = async () => {
if (!selectedDirector || !selectedCompany) {
setSendError("Please select a company and a director first.");
return;
}
setPreviewing(true);
setSendError(null);
setReport(null);
try {
// Build the local validation report — same shape the server would
// return, but computed client-side so we don't round-trip to the
// server just to render the gate. The server re-validates on POST.
const director = directors.find((d) => d.id === selectedDirector);
const company = companies.find((c) => c.id === selectedCompany);
const dirDetails = await fetchDirectorDetails(selectedDirector);
const coDetails = await fetchCompanyDetails(selectedCompany);
const emailRx = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
const classify = (e: string | undefined | null): RecipientStatus => {
const v = (e ?? "").trim();
if (!v) return "missing";
return emailRx.test(v) ? "valid" : "invalid";
};
// Fetch linked directors for the company
let linkedDirectors: Array<{ id: string; first_names?: string; surname?: string; email?: string }> = [];
try {
const res = await fetch("/api/pb/records/list?collection=ysterbaard_company_directors&perPage=200&filter=" + encodeURIComponent(`company = '${selectedCompany}'`) + "&expand=director&fields=expand.director.id,expand.director.first_names,expand.director.surname,expand.director.email");
if (res.ok) {
const data = await res.json();
linkedDirectors = (data.items || [])
.map((j: { expand?: { director?: { id: string; first_names?: string; surname?: string; email?: string } } }) => j.expand?.director)
.filter(Boolean);
}
} catch { /* ignore — junction may not exist */ }
const initial: Recipient[] = [{
key: "new_director",
label: `New director: ${director?.label ?? "?"}`,
email: dirDetails?.email ?? director?.email ?? "",
role: "to",
status: classify(dirDetails?.email ?? director?.email),
}];
const distro: Recipient[] = [
...linkedDirectors.map((d) => ({
key: `director:${d.id}`,
label: `Director: ${[d.first_names, d.surname].filter(Boolean).join(" ") || d.id}`,
email: d.email ?? "",
role: "to",
status: classify(d.email),
})),
{
key: "company_email",
label: `Company: ${coDetails?.enterprise_name ?? company?.label ?? "?"}`,
email: coDetails?.company_email ?? "",
role: "to",
status: classify(coDetails?.company_email),
},
];
const all = [...initial, ...distro];
const problems = all.filter((r) => r.status !== "valid").length;
setReport({ preview: true, initial, distro, problems });
} catch (err: unknown) {
setSendError(err instanceof Error ? err.message : "Validation failed.");
} finally {
setPreviewing(false);
}
};
const handleSend = async (proceedAnyway: boolean) => {
if (!selectedDirector || !selectedCompany) return;
setSending(true);
setSendError(null);
const director = directors.find((d) => d.id === selectedDirector);
const company = companies.find((c) => c.id === selectedCompany);
try {
const res = await fetch("/api/appointments", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
director_id: selectedDirector,
company_id: selectedCompany,
director_email: director?.email || "SJ@Dyfins.com",
director_cell: director?.telephone || "",
director_name: director?.label.split(" ")[0] || "",
director_surname: director?.label.split(" ").slice(1).join(" ") || "",
company_name: company?.label || "",
proceed_anyway: proceedAnyway,
}),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
// 422 is the validation failure — surface the report so the user can fix
if (res.status === 422 && data.initial && data.distro) {
setReport({
preview: false,
initial: data.initial,
distro: data.distro,
problems: (data.initial.length + data.distro.length),
});
throw new Error(data.error || "Server-side validation failed.");
}
throw new Error(data.error || `HTTP ${res.status}`);
}
setShowModal(false);
setReport(null);
loadAppointments();
} catch (err: unknown) {
setSendError(err instanceof Error ? err.message : "Failed to send letter");
} finally {
setSending(false);
}
};
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<p className="text-sm font-semibold text-fg">
{loading ? "Loading..." : `${appointments.length} appointment${appointments.length !== 1 ? "s" : ""}`}
</p>
<button
onClick={openModal}
className="px-4 py-2 bg-accent text-accent-on rounded font-semibold text-sm hover:opacity-90 transition-opacity"
>
Acceptance Letter
</button>
</div>
{/* Table */}
{loading ? (
<div className="text-center py-12 text-muted text-sm">Loading...</div>
) : appointments.length === 0 ? (
<div className="bg-surface border border-border rounded-lg p-12 text-center text-muted text-sm">
No director consents yet. Click &ldquo;Acceptance Letter&rdquo; to send the first one.
</div>
) : (
<div className="bg-surface border border-border rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border bg-surface-warm">
<th className="text-left px-5 py-3 text-xs font-semibold text-muted uppercase tracking-wide">Director</th>
<th className="text-left px-5 py-3 text-xs font-semibold text-muted uppercase tracking-wide hidden md:table-cell">Company</th>
<th className="text-left px-5 py-3 text-xs font-semibold text-muted uppercase tracking-wide">Status</th>
<th className="text-left px-5 py-3 text-xs font-semibold text-muted uppercase tracking-wide hidden sm:table-cell">Sent to</th>
<th className="text-left px-5 py-3 text-xs font-semibold text-muted uppercase tracking-wide hidden lg:table-cell">Date</th>
</tr>
</thead>
<tbody className="divide-y divide-border-soft">
{appointments.map((appt) => (
<tr key={appt.id} className="hover:bg-surface-warm transition-colors">
<td className="px-5 py-4 font-semibold text-fg">{appt._director_name}</td>
<td className="px-5 py-4 hidden md:table-cell text-fg-2">{appt._company_name}</td>
<td className="px-5 py-4">
<StatusBadge variant={STATUS_VARIANTS[appt.status]}>
{STATUS_LABELS[appt.status]}
</StatusBadge>
</td>
<td className="px-5 py-4 hidden sm:table-cell text-muted text-xs">{appt.sent_to || "—"}</td>
<td className="px-5 py-4 hidden lg:table-cell text-muted tabular-nums text-xs">
{appt.sent_at ? new Date(appt.sent_at).toLocaleDateString("en-ZA") : "—"}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{/* Modal */}
{showModal && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4"
onClick={(e) => { if (e.target === e.currentTarget) { setShowModal(false); setReport(null); } }}
>
<div className="bg-surface border border-border rounded-xl shadow-2xl w-full max-w-md flex flex-col max-h-[90vh]">
<div className="border-b border-border px-6 py-4 flex-shrink-0">
<h2 className="text-lg font-semibold text-fg">Send Consent to Act as Director</h2>
<p className="text-sm text-muted mt-0.5">
{report ? "Review the recipient list before sending." : "Select a company and director to send the consent letter for signature."}
</p>
</div>
<div className="p-6 space-y-4 overflow-y-auto flex-1">
{/* Always show the picker so the user can change selection */}
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm font-semibold text-fg mb-1.5">Company</label>
<select
value={selectedCompany}
onChange={(e) => { setSelectedCompany(e.target.value); setReport(null); }}
className="w-full bg-surface border border-border rounded px-3 py-2.5 text-sm text-fg focus:outline-none focus:border-accent"
>
<option value="">— Select company —</option>
{companies.map((c) => (
<option key={c.id} value={c.id}>{c.label}</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-semibold text-fg mb-1.5">Director</label>
<select
value={selectedDirector}
onChange={(e) => { setSelectedDirector(e.target.value); setReport(null); }}
className="w-full bg-surface border border-border rounded px-3 py-2.5 text-sm text-fg focus:outline-none focus:border-accent"
>
<option value="">— Select director —</option>
{directors.map((d) => (
<option key={d.id} value={d.id}>{d.label}</option>
))}
</select>
</div>
</div>
{/* Validation panel */}
{report && (
<div className="border border-border rounded-lg overflow-hidden">
<div className={`px-4 py-2.5 text-sm font-semibold flex items-center justify-between ${
report.problems === 0
? "bg-green-50 text-green-800 border-b border-green-200"
: "bg-amber-50 text-amber-900 border-b border-amber-200"
}`}>
<span>
{report.problems === 0
? "All recipients look good"
: `${report.problems} recipient${report.problems !== 1 ? "s" : ""} need attention`}
</span>
</div>
<div className="p-3 space-y-3 text-sm">
<div>
<p className="text-xs font-semibold text-muted uppercase tracking-wide mb-1.5">Initial send</p>
<div className="space-y-1.5">
{report.initial.map((r) => (
<div key={r.key} className="flex items-center gap-2">
<StatusDot status={r.status} />
<span className="text-fg-2 text-xs flex-1">{r.label}</span>
<span className={r.status === "valid" ? "text-fg-2 text-xs font-mono" : "text-amber-800 text-xs font-mono"}>
{r.status === "missing" ? "(missing)" : r.status === "invalid" ? r.email : r.email}
</span>
</div>
))}
</div>
</div>
<div>
<p className="text-xs font-semibold text-muted uppercase tracking-wide mb-1.5">
After director signs (sent to all)
</p>
<div className="space-y-1.5">
{report.distro.map((r) => (
<div key={r.key} className="flex items-center gap-2">
<StatusDot status={r.status} />
<span className="text-fg-2 text-xs flex-1">{r.label}</span>
<span className={r.status === "valid" ? "text-fg-2 text-xs font-mono" : "text-amber-800 text-xs font-mono"}>
{r.status === "missing" ? "(missing)" : r.status === "invalid" ? r.email : r.email}
</span>
</div>
))}
</div>
</div>
{report.problems > 0 && (
<p className="text-xs text-amber-900 bg-amber-100 border border-amber-200 rounded px-3 py-2">
<strong>Heads up:</strong> recipients flagged above will be skipped when the signed letter is distributed.
You can fix the records first, or proceed anyway and email them manually.
</p>
)}
</div>
</div>
)}
{sendError && (
<div className="bg-red-500/10 border border-red-500/30 rounded-lg px-4 py-3 text-sm text-red-400">
{sendError}
</div>
)}
</div>
<div className="border-t border-border px-6 py-4 flex justify-between gap-3 flex-shrink-0">
{/* Left side: Cancel / Edit records */}
<div className="flex gap-2">
<button
onClick={() => { setShowModal(false); setReport(null); }}
className="px-4 py-2 text-sm font-semibold text-muted hover:text-fg transition-colors"
>
Cancel
</button>
{report && report.problems > 0 && (
<a
href={selectedCompany ? `/companies/${selectedCompany}` : "/companies"}
target="_blank"
rel="noopener"
className="px-4 py-2 text-sm font-semibold text-accent hover:text-accent-hover transition-colors"
>
Fix records first →
</a>
)}
</div>
{/* Right side: Validate / Send / Proceed anyway */}
{!report ? (
<button
onClick={handlePreview}
disabled={!selectedDirector || !selectedCompany || previewing}
className="px-4 py-2 bg-accent text-accent-on rounded font-semibold text-sm disabled:opacity-40 hover:opacity-90 transition-opacity"
>
{previewing ? "Validating..." : "Validate recipients"}
</button>
) : report.problems === 0 ? (
<button
onClick={() => handleSend(false)}
disabled={sending}
className="px-4 py-2 bg-accent text-accent-on rounded font-semibold text-sm disabled:opacity-40 hover:opacity-90 transition-opacity"
>
{sending ? "Sending..." : "Send letter"}
</button>
) : (
<button
onClick={() => handleSend(true)}
disabled={sending}
className="px-4 py-2 bg-amber-600 text-white rounded font-semibold text-sm disabled:opacity-40 hover:bg-amber-700 transition-colors"
title="Send anyway — the flagged recipients will be skipped when the signed letter is distributed"
>
{sending ? "Sending..." : "Proceed anyway"}
</button>
)}
</div>
</div>
</div>
)}
</div>
);
}