Added Correspondence template

X-Lovable-Edit-ID: edt-e65e3e61-259f-445c-b133-d11bc2cec8fb
Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot]
2026-04-17 02:19:52 +00:00
co-authored by renee-png
2 changed files with 89 additions and 6 deletions
+63 -6
View File
@@ -21,7 +21,40 @@ export const Route = createFileRoute("/documents/templates/$templateId")({
interface FieldDef { key: string; label: string; type: "text" | "textarea" | "date" | "number" }
function mergeBody(body: string, values: Record<string, string>) {
return body.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (_, k) => values[k] ?? `{{${k}}}`);
// Replace tokens, treating unknown tokens as empty so optional fields don't leak
const merged = body.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (_, k) => values[k] ?? "");
// Collapse runs of 3+ blank lines down to 2 (one blank line of separation)
return merged.replace(/\n{3,}/g, "\n\n").replace(/[ \t]+\n/g, "\n");
}
function formatToday() {
return new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
}
interface FirmSettings {
company_name?: string | null;
address_line1?: string | null;
address_line2?: string | null;
city?: string | null;
state?: string | null;
postal_code?: string | null;
contact_phone?: string | null;
contact_email?: string | null;
website?: string | null;
}
function buildFirmHeader(f: FirmSettings | null): string {
if (!f) return "";
const lines: string[] = [];
if (f.company_name) lines.push(f.company_name);
if (f.address_line1) lines.push(f.address_line1);
if (f.address_line2) lines.push(f.address_line2);
const csz = [f.city, f.state, f.postal_code].filter(Boolean).join(", ").replace(/, (\d)/, " $1");
if (csz) lines.push(csz);
const contact = [f.contact_phone, f.contact_email].filter(Boolean).join(" • ");
if (contact) lines.push(contact);
if (f.website) lines.push(f.website);
return lines.join("\n");
}
function TemplateDetailPage() {
@@ -37,6 +70,7 @@ function TemplateDetailPage() {
const [docName, setDocName] = useState("Document");
const [saving, setSaving] = useState(false);
const [generating, setGenerating] = useState(false);
const [firm, setFirm] = useState<FirmSettings | null>(null);
useEffect(() => {
supabase.from("document_templates").select("*").eq("id", templateId).single().then(({ data }) => {
@@ -48,9 +82,21 @@ function TemplateDetailPage() {
setFields(Array.isArray(data.fields) ? (data.fields as unknown as FieldDef[]) : []);
setDocName(data.name);
});
supabase.from("firm_settings").select("*").maybeSingle().then(({ data }) => setFirm(data as FirmSettings | null));
}, [templateId]);
const merged = useMemo(() => mergeBody(body, values), [body, values]);
const autoValues = useMemo<Record<string, string>>(() => {
const v: Record<string, string> = {
today: formatToday(),
firm_header: buildFirmHeader(firm),
re_line: values.re?.trim() ? `Re: ${values.re.trim()}\n\n` : "",
certified_mail_line: values.certified_mail_no?.trim() ? `VIA CERTIFIED MAIL NO. ${values.certified_mail_no.trim()}\n` : "",
fedex_line: values.fedex_no?.trim() ? `VIA FEDEX TRACKING NO. ${values.fedex_no.trim()}\n` : "",
};
return v;
}, [firm, values.re, values.certified_mail_no, values.fedex_no]);
const merged = useMemo(() => mergeBody(body, { ...autoValues, ...values }), [body, values, autoValues]);
const saveTemplate = async () => {
setSaving(true);
@@ -69,19 +115,30 @@ function TemplateDetailPage() {
navigate({ to: "/documents/templates" });
};
const isLetter = tpl?.kind === "correspondence";
const fontFamily: string = tpl?.font_family || "Bookman Old Style";
const fontSizePt: number = tpl?.font_size_pt || 12;
const downloadOnly = async () => {
await downloadGeneric({ title: docName, body: merged }, docName || "Document");
await downloadGeneric(
{ title: isLetter ? undefined : docName, body: merged, fontFamily, fontSizePt },
docName || "Document",
);
};
const generateAndSave = async () => {
setGenerating(true);
try {
const { Document, Paragraph, TextRun, AlignmentType } = await import("docx");
const font = "Bookman Old Style", size = 24;
const font = fontFamily;
const size = fontSizePt * 2;
const mkP = (text: string, bold = false, center = false) =>
new Paragraph({ alignment: center ? AlignmentType.CENTER : undefined, children: [new TextRun({ text, bold, font, size })] });
const children: any[] = [];
if (docName) { children.push(mkP(docName, true, true)); children.push(new Paragraph({ children: [new TextRun({ text: "", font, size })] })); }
if (docName && !isLetter) {
children.push(mkP(docName, true, true));
children.push(new Paragraph({ children: [new TextRun({ text: "", font, size })] }));
}
merged.split("\n").forEach((line) => children.push(mkP(line)));
const doc = new Document({
styles: { default: { document: { run: { font, size } } } },
@@ -176,7 +233,7 @@ function TemplateDetailPage() {
<div>
<Label className="text-xs">Preview</Label>
<div className="mt-1 p-4 bg-white text-black rounded-md border min-h-[200px] whitespace-pre-line" style={{ fontFamily: '"Bookman Old Style", Georgia, serif', fontSize: 12 }}>
<div className="mt-1 p-4 bg-white text-black rounded-md border min-h-[200px] whitespace-pre-line" style={{ fontFamily: `"${fontFamily}", Georgia, serif`, fontSize: fontSizePt }}>
{merged || <span className="text-muted-foreground italic">Empty</span>}
</div>
</div>
@@ -0,0 +1,26 @@
INSERT INTO public.document_templates (name, description, kind, font_family, font_size_pt, fields, body)
VALUES (
'Correspondence',
'Firm letterhead correspondence with optional Re: and certified mail / FedEx tracking lines.',
'correspondence',
'Times New Roman',
12,
'[
{"key":"recipient_name","label":"Recipient name","type":"text"},
{"key":"recipient_title","label":"Recipient title","type":"text"},
{"key":"recipient_company","label":"Recipient company","type":"text"},
{"key":"recipient_address1","label":"Recipient address line 1","type":"text"},
{"key":"recipient_address2","label":"Recipient address line 2","type":"text"},
{"key":"recipient_city_state_zip","label":"Recipient city, state, ZIP","type":"text"},
{"key":"certified_mail_no","label":"Certified Mail No. (optional)","type":"text"},
{"key":"fedex_no","label":"FedEx Tracking No. (optional)","type":"text"},
{"key":"re","label":"Re: (optional)","type":"text"},
{"key":"salutation","label":"Salutation","type":"text"},
{"key":"body","label":"Letter body","type":"textarea"},
{"key":"closing","label":"Closing","type":"text"},
{"key":"sender_name","label":"Sender name","type":"text"},
{"key":"sender_title","label":"Sender title","type":"text"}
]'::jsonb,
E'{{firm_header}}\n\n{{today}}\n\n{{certified_mail_line}}{{fedex_line}}{{recipient_name}}\n{{recipient_title}}\n{{recipient_company}}\n{{recipient_address1}}\n{{recipient_address2}}\n{{recipient_city_state_zip}}\n\n{{re_line}}Dear {{salutation}}:\n\n{{body}}\n\n{{closing}},\n\n\n\n{{sender_name}}\n{{sender_title}}'
);