Changes
Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
co-authored by
renee-png
parent
2236a45d91
commit
3483e065ec
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user