Files
mylegal-stage-law/src/routes/documents.templates.$templateId.tsx
T
2026-04-17 02:19:27 +00:00

255 lines
11 KiB
TypeScript

import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect, useMemo, useState } from "react";
import { ProtectedLayout } from "@/components/protected-layout";
import { PageContainer, PageHeader } from "@/components/app-shell";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/auth";
import { toast } from "sonner";
import { Download, Loader2, Save, Trash2 } from "lucide-react";
import { downloadGeneric } from "@/lib/docx-pleading";
import { Packer } from "docx";
export const Route = createFileRoute("/documents/templates/$templateId")({
component: TemplateDetailPage,
});
interface FieldDef { key: string; label: string; type: "text" | "textarea" | "date" | "number" }
function mergeBody(body: string, values: Record<string, string>) {
// 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() {
const { templateId } = Route.useParams();
const { user } = useAuth();
const navigate = useNavigate();
const [tpl, setTpl] = useState<any>(null);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [body, setBody] = useState("");
const [fields, setFields] = useState<FieldDef[]>([]);
const [values, setValues] = useState<Record<string, string>>({});
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 }) => {
if (!data) return;
setTpl(data);
setName(data.name);
setDescription(data.description ?? "");
setBody(data.body ?? "");
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 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);
const { error } = await supabase.from("document_templates").update({
name: name.trim(), description: description.trim() || null, body, fields: fields as any,
}).eq("id", templateId);
setSaving(false);
if (error) toast.error(error.message); else toast.success("Saved");
};
const deleteTemplate = async () => {
if (!confirm(`Delete template "${name}"?`)) return;
const { error } = await supabase.from("document_templates").delete().eq("id", templateId);
if (error) { toast.error(error.message); return; }
toast.success("Deleted");
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: 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 = 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 && !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 } } } },
sections: [{ properties: { page: { size: { width: 12240, height: 15840 }, margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 } } }, children }],
});
const blob = await Packer.toBlob(doc);
const safe = (docName || "Document").replace(/[^a-zA-Z0-9._-]/g, "_");
const path = `${user?.id}/${Date.now()}-${safe}.docx`;
const { error: upErr } = await supabase.storage.from("generated-documents").upload(path, blob, {
contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
if (upErr) throw upErr;
const { error: insErr } = await supabase.from("generated_documents").insert({
name: docName, kind: "general", template_id: templateId, payload: { values }, body: merged, storage_path: path, created_by: user?.id,
});
if (insErr) throw insErr;
toast.success("Document generated");
await downloadOnly();
} catch (e: any) {
toast.error(e.message ?? "Generate failed");
} finally { setGenerating(false); }
};
if (!tpl) return <ProtectedLayout><PageContainer><div className="text-sm text-muted-foreground">Loading...</div></PageContainer></ProtectedLayout>;
return (
<ProtectedLayout>
<PageContainer>
<PageHeader
title={tpl.name}
description="Edit template or fill in values to generate a document."
actions={
<>
<Button variant="outline" onClick={deleteTemplate}><Trash2 className="h-4 w-4 mr-2" /> Delete</Button>
<Button variant="outline" onClick={saveTemplate} disabled={saving}>
{saving ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Save className="h-4 w-4 mr-2" />}
Save template
</Button>
</>
}
/>
<div className="grid lg:grid-cols-2 gap-6">
{/* Left: Template editor */}
<Card>
<CardContent className="p-5 space-y-4">
<div className="text-xs uppercase tracking-wider text-muted-foreground font-medium">Template</div>
<div className="space-y-1.5">
<Label>Name</Label>
<Input value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>Description</Label>
<Input value={description} onChange={(e) => setDescription(e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>Body</Label>
<Textarea rows={14} value={body} onChange={(e) => setBody(e.target.value)} className="font-mono text-sm" />
</div>
<div className="text-xs text-muted-foreground">
Fields: {fields.length === 0 ? "none" : fields.map((f) => `{{${f.key}}}`).join(", ")}
</div>
</CardContent>
</Card>
{/* Right: Fill & generate */}
<Card>
<CardContent className="p-5 space-y-4">
<div className="text-xs uppercase tracking-wider text-muted-foreground font-medium">Generate document</div>
<div className="space-y-1.5">
<Label>Document name</Label>
<Input value={docName} onChange={(e) => setDocName(e.target.value)} />
</div>
{fields.length === 0 ? (
<div className="text-xs text-muted-foreground">This template has no custom fields. The body will be used as-is.</div>
) : (
<div className="space-y-3">
{fields.map((f) => (
<div key={f.key} className="space-y-1.5">
<Label className="text-xs">{f.label} <span className="text-muted-foreground font-mono">{`{{${f.key}}}`}</span></Label>
{f.type === "textarea" ? (
<Textarea rows={3} value={values[f.key] ?? ""} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })} />
) : (
<Input type={f.type === "number" ? "number" : f.type === "date" ? "date" : "text"} value={values[f.key] ?? ""} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })} />
)}
</div>
))}
</div>
)}
<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: `"${fontFamily}", Georgia, serif`, fontSize: fontSizePt }}>
{merged || <span className="text-muted-foreground italic">Empty</span>}
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={downloadOnly}><Download className="h-4 w-4 mr-2" /> Download .docx</Button>
<Button onClick={generateAndSave} disabled={generating}>
{generating ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Save className="h-4 w-4 mr-2" />}
Save & download
</Button>
</div>
</CardContent>
</Card>
</div>
</PageContainer>
</ProtectedLayout>
);
}