Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot]
2026-04-18 21:37:55 +00:00
co-authored by renee-png
parent a1461d399a
commit a7865d6b23
+38 -6
View File
@@ -47,10 +47,11 @@ async function loadLogoDataUrl(path: string | null | undefined): Promise<string
}
export function LetterGenerator() {
const [client, setClient] = useState<ClientLite | null>(null);
const [homeowner, setHomeowner] = useState<HomeownerLite | null>(null);
const [clientId, setClientId] = useState("");
const [homeownerId, setHomeownerId] = useState("");
const [cases, setCases] = useState<CaseLite[]>([]);
const [caseId, setCaseId] = useState("");
const [contacts, setContacts] = useState<ContactLite[]>([]);
const [caseContactIds, setCaseContactIds] = useState<Set<string>>(new Set());
const [recipientId, setRecipientId] = useState("");
const [firm, setFirm] = useState<FirmInfo | null>(null);
const [logoDataUrl, setLogoDataUrl] = useState<string | null>(null);
const [attorneyName, setAttorneyName] = useState("");
@@ -60,15 +61,31 @@ export function LetterGenerator() {
const [certifiedMailNumber, setCertifiedMailNumber] = useState("");
const [template, setTemplate] = useState<FormTemplateConfig | null>(null);
const recipient = useMemo(
() => contacts.find((c) => c.id === recipientId) ?? null,
[contacts, recipientId],
);
// Sort: case-linked contacts first, then everything else.
const sortedContacts = useMemo(() => {
const linked: ContactLite[] = [];
const others: ContactLite[] = [];
for (const c of contacts) {
(caseContactIds.has(c.id) ? linked : others).push(c);
}
return { linked, others };
}, [contacts, caseContactIds]);
useEffect(() => {
fetchFirm().then(async (f) => {
setFirm(f);
const url = await loadLogoDataUrl((f as any)?.logo_storage_path);
setLogoDataUrl(url);
});
fetchAccessibleCases().then(setCases);
fetchContacts().then(setContacts);
loadFormTemplate("letter").then((t) => {
setTemplate(t);
// Seed the editable body with the template default on first load.
setBody((prev) => prev || t.body || "");
});
supabase.auth.getUser().then(async ({ data }) => {
@@ -86,9 +103,24 @@ export function LetterGenerator() {
});
}, []);
// When case changes, fetch its linked contacts to surface them at the top.
useEffect(() => {
if (!caseId) {
setCaseContactIds(new Set());
return;
}
supabase
.from("case_contacts")
.select("contact_id")
.eq("case_id", caseId)
.then(({ data }) => {
setCaseContactIds(new Set((data ?? []).map((r: any) => r.contact_id)));
});
}, [caseId]);
const handleExport = () => {
if (!template) return;
const ctx = { client, homeowner, firmName: firm?.company_name ?? "" };
const ctx = { client: null, homeowner: null, firmName: firm?.company_name ?? "" };
const renderedBody = applyVariables(body, ctx);
const renderedSubject = applyVariables(subject, ctx);