Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot]
2026-04-17 01:45:54 +00:00
co-authored by renee-png
parent 2236a45d91
commit 3483e065ec
7 changed files with 869 additions and 0 deletions
+143
View File
@@ -0,0 +1,143 @@
import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { ProtectedLayout } from "@/components/protected-layout";
import { PageContainer, PageHeader } from "@/components/app-shell";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { supabase } from "@/integrations/supabase/client";
import { formatDate } from "@/lib/format";
import { FilePlus2, FileText, Gavel, LayoutTemplate, Plus, Download, Trash2 } from "lucide-react";
import { toast } from "sonner";
export const Route = createFileRoute("/documents/")({
component: DocumentsIndex,
});
function DocumentsIndex() {
const [generated, setGenerated] = useState<any[]>([]);
const [templates, setTemplates] = useState<any[]>([]);
const load = async () => {
const [g, t] = await Promise.all([
supabase.from("generated_documents").select("*").order("created_at", { ascending: false }).limit(20),
supabase.from("document_templates").select("*").order("name"),
]);
setGenerated(g.data ?? []);
setTemplates(t.data ?? []);
};
useEffect(() => { load(); }, []);
const removeGenerated = async (row: any) => {
if (!confirm(`Delete ${row.name}?`)) return;
if (row.storage_path) await supabase.storage.from("generated-documents").remove([row.storage_path]);
const { error } = await supabase.from("generated_documents").delete().eq("id", row.id);
if (error) toast.error(error.message); else { toast.success("Deleted"); load(); }
};
const downloadGenerated = async (row: any) => {
if (!row.storage_path) { toast.error("No file stored for this document"); return; }
const { data, error } = await supabase.storage.from("generated-documents").createSignedUrl(row.storage_path, 60);
if (error) { toast.error(error.message); return; }
window.open(data.signedUrl, "_blank");
};
return (
<ProtectedLayout>
<PageContainer>
<PageHeader
title="Documents"
description="Create pleadings and reusable document templates."
actions={
<>
<Button asChild variant="outline">
<Link to="/documents/templates">
<LayoutTemplate className="h-4 w-4 mr-2" /> Templates
</Link>
</Button>
<Button asChild>
<Link to="/documents/pleading/new">
<Gavel className="h-4 w-4 mr-2" /> New Pleading
</Link>
</Button>
</>
}
/>
<div className="grid md:grid-cols-3 gap-4 mb-8">
<Link to="/documents/pleading/new">
<Card className="hover:border-primary/40 transition-colors cursor-pointer h-full">
<CardContent className="p-5 flex items-start gap-3">
<div className="h-10 w-10 rounded-md bg-primary/10 text-primary flex items-center justify-center"><Gavel className="h-5 w-5" /></div>
<div>
<div className="font-medium">Florida Pleading</div>
<div className="text-xs text-muted-foreground mt-1">Court caption header in Bookman Old Style 12pt.</div>
</div>
</CardContent>
</Card>
</Link>
<Link to="/documents/templates/new">
<Card className="hover:border-primary/40 transition-colors cursor-pointer h-full">
<CardContent className="p-5 flex items-start gap-3">
<div className="h-10 w-10 rounded-md bg-primary/10 text-primary flex items-center justify-center"><FilePlus2 className="h-5 w-5" /></div>
<div>
<div className="font-medium">New template</div>
<div className="text-xs text-muted-foreground mt-1">Define custom merge fields and reuse them.</div>
</div>
</CardContent>
</Card>
</Link>
<Link to="/documents/templates">
<Card className="hover:border-primary/40 transition-colors cursor-pointer h-full">
<CardContent className="p-5 flex items-start gap-3">
<div className="h-10 w-10 rounded-md bg-primary/10 text-primary flex items-center justify-center"><LayoutTemplate className="h-5 w-5" /></div>
<div>
<div className="font-medium">Template library</div>
<div className="text-xs text-muted-foreground mt-1">{templates.length} template{templates.length === 1 ? "" : "s"} available.</div>
</div>
</CardContent>
</Card>
</Link>
</div>
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="text-base">Recent documents</CardTitle>
</CardHeader>
<CardContent className="p-0">
{generated.length === 0 ? (
<div className="text-center py-12 text-muted-foreground text-sm">No documents yet. Create a pleading or use a template.</div>
) : (
<table className="w-full text-sm">
<thead className="bg-muted/40 text-xs uppercase tracking-wider text-muted-foreground">
<tr>
<th className="text-left px-4 py-3 font-medium">Name</th>
<th className="text-left px-4 py-3 font-medium">Type</th>
<th className="text-left px-4 py-3 font-medium">Created</th>
<th className="text-right px-4 py-3 font-medium">Actions</th>
</tr>
</thead>
<tbody>
{generated.map((d) => (
<tr key={d.id} className="border-t hover:bg-muted/30">
<td className="px-4 py-3"><div className="flex items-center gap-2"><FileText className="h-4 w-4 text-muted-foreground" /><span className="font-medium">{d.name}</span></div></td>
<td className="px-4 py-3"><Badge variant="outline" className="capitalize">{d.kind}</Badge></td>
<td className="px-4 py-3 text-muted-foreground">{formatDate(d.created_at)}</td>
<td className="px-4 py-3 text-right">
{d.storage_path && (
<Button variant="ghost" size="icon" onClick={() => downloadGenerated(d)}><Download className="h-4 w-4" /></Button>
)}
<Button variant="ghost" size="icon" onClick={() => removeGenerated(d)}><Trash2 className="h-4 w-4 text-destructive" /></Button>
</td>
</tr>
))}
</tbody>
</table>
)}
</CardContent>
</Card>
</PageContainer>
</ProtectedLayout>
);
}
+220
View File
@@ -0,0 +1,220 @@
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { 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 {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { FL_CIRCUITS } from "@/lib/florida";
import { Packer } from "docx";
import { buildPleadingDoc, downloadPleading } from "@/lib/docx-pleading";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/auth";
import { toast } from "sonner";
import { Download, Save, Loader2 } from "lucide-react";
export const Route = createFileRoute("/documents/pleading/new")({
component: PleadingNewPage,
});
function PleadingNewPage() {
const { user } = useAuth();
const navigate = useNavigate();
const [courtType, setCourtType] = useState<"CIRCUIT" | "COUNTY">("CIRCUIT");
const [circuit, setCircuit] = useState<string>("ELEVENTH");
const [county, setCounty] = useState<string>("Miami-Dade");
const [plaintiffs, setPlaintiffs] = useState("");
const [defendants, setDefendants] = useState("");
const [caseNumber, setCaseNumber] = useState("");
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const [docName, setDocName] = useState("Pleading");
const [saving, setSaving] = useState(false);
const counties = useMemo(() => {
const c = FL_CIRCUITS.find((x) => x.value === circuit);
return c?.counties ?? [];
}, [circuit]);
// Reset county when circuit changes if current county isn't valid
const handleCircuitChange = (v: string) => {
setCircuit(v);
const c = FL_CIRCUITS.find((x) => x.value === v);
if (c && !c.counties.includes(county)) setCounty(c.counties[0]);
};
const input = {
courtType, circuit, county,
plaintiffs, defendants, caseNumber,
title, body,
};
const headerLine1 = `IN THE ${courtType} COURT OF THE ${circuit} JUDICIAL CIRCUIT,`;
const headerLine2 = `IN AND FOR ${county.toUpperCase()} COUNTY, FLORIDA`;
const onDownload = async () => {
await downloadPleading(input, docName || "Pleading");
};
const onSave = async () => {
setSaving(true);
try {
const doc = buildPleadingDoc(input);
const blob = await Packer.toBlob(doc);
const safe = (docName || "Pleading").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 || "Pleading",
kind: "pleading",
payload: input,
storage_path: path,
created_by: user?.id,
});
if (insErr) throw insErr;
toast.success("Pleading saved");
navigate({ to: "/documents" });
} catch (e: any) {
toast.error(e.message ?? "Save failed");
} finally {
setSaving(false);
}
};
return (
<ProtectedLayout>
<PageContainer>
<PageHeader
title="New Pleading"
description="Florida court caption · Bookman Old Style, 12pt"
actions={
<>
<Button variant="outline" onClick={onDownload}><Download className="h-4 w-4 mr-2" /> Download .docx</Button>
<Button onClick={onSave} disabled={saving}>
{saving ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Save className="h-4 w-4 mr-2" />}
Save & download
</Button>
</>
}
/>
<div className="grid lg:grid-cols-2 gap-6">
{/* Form */}
<Card>
<CardContent className="p-5 space-y-5">
<div className="space-y-1.5">
<Label>Document name</Label>
<Input value={docName} onChange={(e) => setDocName(e.target.value)} placeholder="e.g. Complaint - Smith v. Jones" />
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div className="space-y-1.5">
<Label>Court</Label>
<Select value={courtType} onValueChange={(v) => setCourtType(v as any)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="CIRCUIT">CIRCUIT</SelectItem>
<SelectItem value="COUNTY">COUNTY</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label>Judicial circuit</Label>
<Select value={circuit} onValueChange={handleCircuitChange}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent className="max-h-72">
{FL_CIRCUITS.map((c) => (
<SelectItem key={c.value} value={c.value}>{c.label} ({c.value})</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label>County</Label>
<Select value={county} onValueChange={setCounty}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent className="max-h-72">
{counties.map((co) => (
<SelectItem key={co} value={co}>{co}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label>Plaintiff(s)</Label>
<Textarea rows={3} value={plaintiffs} onChange={(e) => setPlaintiffs(e.target.value)} placeholder="One name per line" />
</div>
<div className="space-y-1.5">
<Label>Defendant(s)</Label>
<Textarea rows={3} value={defendants} onChange={(e) => setDefendants(e.target.value)} placeholder="One name per line" />
</div>
</div>
<div className="space-y-1.5">
<Label>Case No.</Label>
<Input value={caseNumber} onChange={(e) => setCaseNumber(e.target.value)} placeholder="e.g. 2025-CA-001234" />
</div>
<div className="space-y-1.5">
<Label>Pleading title (optional)</Label>
<Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. COMPLAINT FOR DAMAGES" />
</div>
<div className="space-y-1.5">
<Label>Body (optional)</Label>
<Textarea rows={10} value={body} onChange={(e) => setBody(e.target.value)} placeholder="Type the body of the pleading..." />
</div>
</CardContent>
</Card>
{/* Preview */}
<Card>
<CardContent className="p-0">
<div className="bg-muted/30 px-4 py-2 border-b text-xs uppercase tracking-wider text-muted-foreground">Preview</div>
<div
className="p-10 bg-white text-black min-h-[600px]"
style={{ fontFamily: '"Bookman Old Style", "URW Bookman", Georgia, serif', fontSize: 12 }}
>
<div className="text-center font-bold leading-snug">
<div>{headerLine1}</div>
<div>{headerLine2}</div>
</div>
<div className="mt-6 flex">
<div className="flex-1 pr-4 border-r border-black">
<div className="whitespace-pre-line min-h-[1.5em]">{plaintiffs || " "}</div>
<div className="mt-3">Plaintiff(s),</div>
<div className="mt-3">v.</div>
<div className="mt-3 whitespace-pre-line min-h-[1.5em]">{defendants || " "}</div>
<div className="mt-3">Defendant(s).</div>
</div>
<div className="w-[40%] pl-4">
<div className="font-bold">CASE NO.: {caseNumber}</div>
</div>
</div>
{title && (
<div className="text-center font-bold mt-8">{title.toUpperCase()}</div>
)}
{body && (
<div className="mt-4 whitespace-pre-line">{body}</div>
)}
</div>
</CardContent>
</Card>
</div>
</PageContainer>
</ProtectedLayout>
);
}
@@ -0,0 +1,197 @@
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>) {
return body.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (_, k) => values[k] ?? `{{${k}}}`);
}
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);
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 : []);
setDocName(data.name);
});
}, [templateId]);
const merged = useMemo(() => mergeBody(body, values), [body, values]);
const saveTemplate = async () => {
setSaving(true);
const { error } = await supabase.from("document_templates").update({
name: name.trim(), description: description.trim() || null, body, fields,
}).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 downloadOnly = async () => {
await downloadGeneric({ title: docName, body: merged }, docName || "Document");
};
const generateAndSave = async () => {
setGenerating(true);
try {
const { Document, Paragraph, TextRun, AlignmentType } = await import("docx");
const font = "Bookman Old Style", size = 24;
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 })] })); }
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: '"Bookman Old Style", Georgia, serif', fontSize: 12 }}>
{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>
);
}
+65
View File
@@ -0,0 +1,65 @@
import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, 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 { Badge } from "@/components/ui/badge";
import { supabase } from "@/integrations/supabase/client";
import { Plus, FileText, ChevronRight, Gavel } from "lucide-react";
import { formatDate } from "@/lib/format";
export const Route = createFileRoute("/documents/templates/")({
component: TemplatesIndex,
});
function TemplatesIndex() {
const [rows, setRows] = useState<any[]>([]);
useEffect(() => {
supabase.from("document_templates").select("*").order("name").then(({ data }) => setRows(data ?? []));
}, []);
return (
<ProtectedLayout>
<PageContainer>
<PageHeader
title="Templates"
description="Reusable document templates with custom merge fields."
actions={
<Button asChild><Link to="/documents/templates/new"><Plus className="h-4 w-4 mr-2" /> New template</Link></Button>
}
/>
<Card>
<CardContent className="p-0">
{rows.length === 0 ? (
<div className="text-center py-12 text-muted-foreground text-sm">No templates yet.</div>
) : (
<ul className="divide-y">
{rows.map((t) => (
<li key={t.id}>
<Link to="/documents/templates/$templateId" params={{ templateId: t.id }} className="flex items-center gap-3 px-4 py-3 hover:bg-muted/40">
<div className="h-9 w-9 rounded-md bg-muted flex items-center justify-center">
{t.kind === "pleading" ? <Gavel className="h-4 w-4" /> : <FileText className="h-4 w-4" />}
</div>
<div className="min-w-0 flex-1">
<div className="font-medium truncate">{t.name}</div>
<div className="text-xs text-muted-foreground truncate">
{t.description || "No description"} · {Array.isArray(t.fields) ? t.fields.length : 0} field{(t.fields?.length ?? 0) === 1 ? "" : "s"}
</div>
</div>
<Badge variant="outline" className="capitalize">{t.kind}</Badge>
<span className="text-xs text-muted-foreground hidden sm:inline">{formatDate(t.updated_at)}</span>
<ChevronRight className="h-4 w-4 text-muted-foreground" />
</Link>
</li>
))}
</ul>
)}
</CardContent>
</Card>
</PageContainer>
</ProtectedLayout>
);
}
+127
View File
@@ -0,0 +1,127 @@
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { 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 { Loader2, Plus, Save, Trash2 } from "lucide-react";
export const Route = createFileRoute("/documents/templates/new")({
component: NewTemplatePage,
});
interface FieldDef { key: string; label: string; type: "text" | "textarea" | "date" | "number" }
function NewTemplatePage() {
const { user } = useAuth();
const navigate = useNavigate();
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [fields, setFields] = useState<FieldDef[]>([]);
const [body, setBody] = useState("Dear {{client_name}},\n\n");
const [saving, setSaving] = useState(false);
const addField = () => setFields((f) => [...f, { key: `field_${f.length + 1}`, label: `Field ${f.length + 1}`, type: "text" }]);
const removeField = (i: number) => setFields((f) => f.filter((_, idx) => idx !== i));
const updateField = (i: number, patch: Partial<FieldDef>) =>
setFields((f) => f.map((x, idx) => (idx === i ? { ...x, ...patch } : x)));
const insertToken = (key: string) => setBody((b) => b + `{{${key}}}`);
const onSave = async () => {
if (!name.trim()) { toast.error("Name is required"); return; }
setSaving(true);
const { data, error } = await supabase.from("document_templates").insert({
name: name.trim(),
description: description.trim() || null,
kind: "general",
body,
fields,
created_by: user?.id,
}).select().single();
setSaving(false);
if (error) { toast.error(error.message); return; }
toast.success("Template created");
navigate({ to: "/documents/templates/$templateId", params: { templateId: data.id } });
};
return (
<ProtectedLayout>
<PageContainer>
<PageHeader
title="New template"
description="Define merge fields and a body. Use {{field_key}} where you want each value inserted."
actions={
<Button onClick={onSave} 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">
<Card>
<CardContent className="p-5 space-y-4">
<div className="space-y-1.5">
<Label>Name</Label>
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Demand Letter" />
</div>
<div className="space-y-1.5">
<Label>Description</Label>
<Input value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Optional" />
</div>
<div>
<div className="flex items-center justify-between mb-2">
<Label>Custom fields</Label>
<Button variant="outline" size="sm" onClick={addField}><Plus className="h-3.5 w-3.5 mr-1" /> Add field</Button>
</div>
{fields.length === 0 && <div className="text-xs text-muted-foreground">No fields yet. Add fields like client_name, amount_due, due_date.</div>}
<div className="space-y-2">
{fields.map((f, i) => (
<div key={i} className="grid grid-cols-12 gap-2 items-center">
<Input className="col-span-4" value={f.key} onChange={(e) => updateField(i, { key: e.target.value.replace(/[^a-zA-Z0-9_]/g, "_") })} placeholder="key" />
<Input className="col-span-4" value={f.label} onChange={(e) => updateField(i, { label: e.target.value })} placeholder="Label" />
<select
className="col-span-3 h-9 rounded-md border border-input bg-transparent px-2 text-sm"
value={f.type}
onChange={(e) => updateField(i, { type: e.target.value as any })}
>
<option value="text">Text</option>
<option value="textarea">Long text</option>
<option value="date">Date</option>
<option value="number">Number</option>
</select>
<Button variant="ghost" size="icon" className="col-span-1" onClick={() => removeField(i)}><Trash2 className="h-4 w-4 text-destructive" /></Button>
<div className="col-span-12 -mt-1">
<button type="button" onClick={() => insertToken(f.key)} className="text-[11px] text-primary hover:underline">
Insert {"{{"}{f.key}{"}}"} into body
</button>
</div>
</div>
))}
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-5 space-y-2">
<Label>Body</Label>
<Textarea rows={20} value={body} onChange={(e) => setBody(e.target.value)} className="font-mono text-sm" />
<p className="text-xs text-muted-foreground">
Use double curly braces around field keys, e.g. <code>{"{{client_name}}"}</code>. They&apos;ll be replaced when generating a document.
</p>
</CardContent>
</Card>
</div>
</PageContainer>
</ProtectedLayout>
);
}