Added documents module
X-Lovable-Edit-ID: edt-2e456861-6517-4a6b-8838-4fbe92685fc5 Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
@@ -46,11 +46,14 @@
|
||||
"@tanstack/react-router": "^1.168.0",
|
||||
"@tanstack/react-start": "^1.167.14",
|
||||
"@tanstack/router-plugin": "^1.167.10",
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"docx": "^9.6.1",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"file-saver": "^2.0.5",
|
||||
"input-otp": "^1.4.2",
|
||||
"lucide-react": "^0.575.0",
|
||||
"react": "^19.2.0",
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
LayoutDashboard,
|
||||
Settings,
|
||||
Wallet,
|
||||
FileSignature,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ReactNode } from "react";
|
||||
@@ -30,6 +31,7 @@ const NAV: NavItem[] = [
|
||||
{ to: "/clients", label: "Clients", icon: Users },
|
||||
{ to: "/cases", label: "Cases", icon: Briefcase },
|
||||
{ to: "/collections", label: "Collections", icon: Wallet },
|
||||
{ to: "/documents", label: "Documents", icon: FileSignature },
|
||||
{ to: "/invoices", label: "Invoices", icon: Receipt },
|
||||
{ to: "/admin/users", label: "Users", icon: ShieldCheck, adminOnly: true },
|
||||
{ to: "/settings", label: "Settings", icon: Settings, adminOnly: true },
|
||||
|
||||
@@ -446,6 +446,48 @@ export type Database = {
|
||||
},
|
||||
]
|
||||
}
|
||||
document_templates: {
|
||||
Row: {
|
||||
body: string
|
||||
created_at: string
|
||||
created_by: string | null
|
||||
description: string | null
|
||||
fields: Json
|
||||
font_family: string
|
||||
font_size_pt: number
|
||||
id: string
|
||||
kind: string
|
||||
name: string
|
||||
updated_at: string
|
||||
}
|
||||
Insert: {
|
||||
body?: string
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
description?: string | null
|
||||
fields?: Json
|
||||
font_family?: string
|
||||
font_size_pt?: number
|
||||
id?: string
|
||||
kind?: string
|
||||
name: string
|
||||
updated_at?: string
|
||||
}
|
||||
Update: {
|
||||
body?: string
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
description?: string | null
|
||||
fields?: Json
|
||||
font_family?: string
|
||||
font_size_pt?: number
|
||||
id?: string
|
||||
kind?: string
|
||||
name?: string
|
||||
updated_at?: string
|
||||
}
|
||||
Relationships: []
|
||||
}
|
||||
documents: {
|
||||
Row: {
|
||||
case_id: string
|
||||
@@ -652,6 +694,53 @@ export type Database = {
|
||||
}
|
||||
Relationships: []
|
||||
}
|
||||
generated_documents: {
|
||||
Row: {
|
||||
body: string | null
|
||||
created_at: string
|
||||
created_by: string | null
|
||||
id: string
|
||||
kind: string
|
||||
name: string
|
||||
payload: Json
|
||||
storage_path: string | null
|
||||
template_id: string | null
|
||||
updated_at: string
|
||||
}
|
||||
Insert: {
|
||||
body?: string | null
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
id?: string
|
||||
kind?: string
|
||||
name: string
|
||||
payload?: Json
|
||||
storage_path?: string | null
|
||||
template_id?: string | null
|
||||
updated_at?: string
|
||||
}
|
||||
Update: {
|
||||
body?: string | null
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
id?: string
|
||||
kind?: string
|
||||
name?: string
|
||||
payload?: Json
|
||||
storage_path?: string | null
|
||||
template_id?: string | null
|
||||
updated_at?: string
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: "generated_documents_template_id_fkey"
|
||||
columns: ["template_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "document_templates"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
homeowners: {
|
||||
Row: {
|
||||
address: string | null
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import {
|
||||
AlignmentType,
|
||||
Document,
|
||||
HeightRule,
|
||||
Packer,
|
||||
PageOrientation,
|
||||
Paragraph,
|
||||
Table,
|
||||
TableCell,
|
||||
TableRow,
|
||||
TextRun,
|
||||
WidthType,
|
||||
BorderStyle,
|
||||
} from "docx";
|
||||
import { saveAs } from "file-saver";
|
||||
|
||||
export interface PleadingInput {
|
||||
courtType: "CIRCUIT" | "COUNTY";
|
||||
circuit: string; // e.g. "ELEVENTH"
|
||||
county: string; // e.g. "Miami-Dade"
|
||||
plaintiffs: string; // multi-line
|
||||
defendants: string; // multi-line
|
||||
caseNumber: string;
|
||||
title?: string;
|
||||
body?: string;
|
||||
}
|
||||
|
||||
const FONT = "Bookman Old Style";
|
||||
const SIZE = 24; // 12pt (docx uses half-points)
|
||||
|
||||
const noBorder = {
|
||||
top: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
|
||||
bottom: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
|
||||
left: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
|
||||
right: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
|
||||
insideHorizontal: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
|
||||
insideVertical: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
|
||||
};
|
||||
|
||||
const verticalLine = {
|
||||
top: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
|
||||
bottom: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
|
||||
left: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
|
||||
right: { style: BorderStyle.SINGLE, size: 8, color: "000000" },
|
||||
};
|
||||
|
||||
function run(text: string, opts: { bold?: boolean } = {}) {
|
||||
return new TextRun({ text, bold: opts.bold, font: FONT, size: SIZE });
|
||||
}
|
||||
|
||||
function p(text: string, opts: { bold?: boolean; align?: (typeof AlignmentType)[keyof typeof AlignmentType] } = {}) {
|
||||
return new Paragraph({
|
||||
alignment: opts.align,
|
||||
children: [run(text, { bold: opts.bold })],
|
||||
});
|
||||
}
|
||||
|
||||
function emptyP() {
|
||||
return new Paragraph({ children: [run("")] });
|
||||
}
|
||||
|
||||
export function buildPleadingDoc(input: PleadingInput): Document {
|
||||
const headerLine1 = `IN THE ${input.courtType} COURT OF THE ${input.circuit} JUDICIAL CIRCUIT,`;
|
||||
const headerLine2 = `IN AND FOR ${input.county.toUpperCase()} COUNTY, FLORIDA`;
|
||||
|
||||
const plaintiffLines = (input.plaintiffs || "").split("\n").filter((l) => l.trim().length > 0);
|
||||
const defendantLines = (input.defendants || "").split("\n").filter((l) => l.trim().length > 0);
|
||||
|
||||
// Left side of caption
|
||||
const leftCells: Paragraph[] = [];
|
||||
plaintiffLines.forEach((l) => leftCells.push(p(l)));
|
||||
if (plaintiffLines.length === 0) leftCells.push(p(""));
|
||||
leftCells.push(emptyP());
|
||||
leftCells.push(p("Plaintiff(s),"));
|
||||
leftCells.push(emptyP());
|
||||
leftCells.push(p("v."));
|
||||
leftCells.push(emptyP());
|
||||
defendantLines.forEach((l) => leftCells.push(p(l)));
|
||||
if (defendantLines.length === 0) leftCells.push(p(""));
|
||||
leftCells.push(emptyP());
|
||||
leftCells.push(p("Defendant(s)."));
|
||||
|
||||
const rightCells: Paragraph[] = [
|
||||
p(`CASE NO.: ${input.caseNumber || ""}`, { bold: true }),
|
||||
];
|
||||
|
||||
const captionTable = new Table({
|
||||
width: { size: 9360, type: WidthType.DXA },
|
||||
columnWidths: [5400, 3960],
|
||||
rows: [
|
||||
new TableRow({
|
||||
height: { value: 400, rule: HeightRule.AUTO },
|
||||
children: [
|
||||
new TableCell({
|
||||
width: { size: 5400, type: WidthType.DXA },
|
||||
borders: verticalLine,
|
||||
margins: { top: 80, bottom: 80, left: 0, right: 200 },
|
||||
children: leftCells,
|
||||
}),
|
||||
new TableCell({
|
||||
width: { size: 3960, type: WidthType.DXA },
|
||||
borders: noBorder,
|
||||
margins: { top: 80, bottom: 80, left: 200, right: 0 },
|
||||
children: rightCells,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const bodyParagraphs: Paragraph[] = [];
|
||||
if (input.title) {
|
||||
bodyParagraphs.push(emptyP());
|
||||
bodyParagraphs.push(p(input.title.toUpperCase(), { bold: true, align: AlignmentType.CENTER }));
|
||||
bodyParagraphs.push(emptyP());
|
||||
}
|
||||
if (input.body) {
|
||||
input.body.split("\n").forEach((line) => bodyParagraphs.push(p(line)));
|
||||
}
|
||||
|
||||
return new Document({
|
||||
styles: {
|
||||
default: { document: { run: { font: FONT, size: SIZE } } },
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
page: {
|
||||
size: { width: 12240, height: 15840, orientation: PageOrientation.PORTRAIT },
|
||||
margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 },
|
||||
},
|
||||
},
|
||||
children: [
|
||||
p(headerLine1, { bold: true, align: AlignmentType.CENTER }),
|
||||
p(headerLine2, { bold: true, align: AlignmentType.CENTER }),
|
||||
emptyP(),
|
||||
captionTable,
|
||||
...bodyParagraphs,
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export async function downloadPleading(input: PleadingInput, filename: string) {
|
||||
const doc = buildPleadingDoc(input);
|
||||
const blob = await Packer.toBlob(doc);
|
||||
saveAs(blob, filename.endsWith(".docx") ? filename : `${filename}.docx`);
|
||||
}
|
||||
|
||||
// ---------- Generic template (custom fields) ----------
|
||||
|
||||
export interface GenericDocInput {
|
||||
title?: string;
|
||||
body: string; // Already merged (fields substituted)
|
||||
fontFamily?: string;
|
||||
fontSizePt?: number;
|
||||
}
|
||||
|
||||
export async function downloadGeneric(input: GenericDocInput, filename: string) {
|
||||
const font = input.fontFamily || "Bookman Old Style";
|
||||
const size = (input.fontSizePt || 12) * 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: Paragraph[] = [];
|
||||
if (input.title) {
|
||||
children.push(mkP(input.title, true, true));
|
||||
children.push(new Paragraph({ children: [new TextRun({ text: "", font, size })] }));
|
||||
}
|
||||
input.body.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);
|
||||
saveAs(blob, filename.endsWith(".docx") ? filename : `${filename}.docx`);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Florida judicial circuits (1st–20th) and the counties they cover.
|
||||
export const FL_CIRCUITS: { value: string; label: string; counties: string[] }[] = [
|
||||
{ value: "FIRST", label: "First", counties: ["Escambia", "Okaloosa", "Santa Rosa", "Walton"] },
|
||||
{ value: "SECOND", label: "Second", counties: ["Franklin", "Gadsden", "Jefferson", "Leon", "Liberty", "Wakulla"] },
|
||||
{ value: "THIRD", label: "Third", counties: ["Columbia", "Dixie", "Hamilton", "Lafayette", "Madison", "Suwannee", "Taylor"] },
|
||||
{ value: "FOURTH", label: "Fourth", counties: ["Clay", "Duval", "Nassau"] },
|
||||
{ value: "FIFTH", label: "Fifth", counties: ["Citrus", "Hernando", "Lake", "Marion", "Sumter"] },
|
||||
{ value: "SIXTH", label: "Sixth", counties: ["Pasco", "Pinellas"] },
|
||||
{ value: "SEVENTH", label: "Seventh", counties: ["Flagler", "Putnam", "St. Johns", "Volusia"] },
|
||||
{ value: "EIGHTH", label: "Eighth", counties: ["Alachua", "Baker", "Bradford", "Gilchrist", "Levy", "Union"] },
|
||||
{ value: "NINTH", label: "Ninth", counties: ["Orange", "Osceola"] },
|
||||
{ value: "TENTH", label: "Tenth", counties: ["Hardee", "Highlands", "Polk"] },
|
||||
{ value: "ELEVENTH", label: "Eleventh", counties: ["Miami-Dade"] },
|
||||
{ value: "TWELFTH", label: "Twelfth", counties: ["DeSoto", "Manatee", "Sarasota"] },
|
||||
{ value: "THIRTEENTH", label: "Thirteenth", counties: ["Hillsborough"] },
|
||||
{ value: "FOURTEENTH", label: "Fourteenth", counties: ["Bay", "Calhoun", "Gulf", "Holmes", "Jackson", "Washington"] },
|
||||
{ value: "FIFTEENTH", label: "Fifteenth", counties: ["Palm Beach"] },
|
||||
{ value: "SIXTEENTH", label: "Sixteenth", counties: ["Monroe"] },
|
||||
{ value: "SEVENTEENTH", label: "Seventeenth", counties: ["Broward"] },
|
||||
{ value: "EIGHTEENTH", label: "Eighteenth", counties: ["Brevard", "Seminole"] },
|
||||
{ value: "NINETEENTH", label: "Nineteenth", counties: ["Indian River", "Martin", "Okeechobee", "St. Lucie"] },
|
||||
{ value: "TWENTIETH", label: "Twentieth", counties: ["Charlotte", "Collier", "Glades", "Hendry", "Lee"] },
|
||||
];
|
||||
|
||||
export const FL_COUNTIES: string[] = Array.from(
|
||||
new Set(FL_CIRCUITS.flatMap((c) => c.counties)),
|
||||
).sort();
|
||||
@@ -14,6 +14,7 @@ import { Route as SettingsRouteImport } from './routes/settings'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as IndexRouteImport } from './routes/index'
|
||||
import { Route as SettingsIndexRouteImport } from './routes/settings.index'
|
||||
import { Route as DocumentsIndexRouteImport } from './routes/documents.index'
|
||||
import { Route as CollectionsIndexRouteImport } from './routes/collections.index'
|
||||
import { Route as ClientsIndexRouteImport } from './routes/clients.index'
|
||||
import { Route as CasesIndexRouteImport } from './routes/cases.index'
|
||||
@@ -24,6 +25,10 @@ import { Route as ClientsClientIdRouteImport } from './routes/clients.$clientId'
|
||||
import { Route as CasesNewRouteImport } from './routes/cases.new'
|
||||
import { Route as CasesCaseIdRouteImport } from './routes/cases.$caseId'
|
||||
import { Route as AdminUsersRouteImport } from './routes/admin.users'
|
||||
import { Route as DocumentsTemplatesIndexRouteImport } from './routes/documents.templates.index'
|
||||
import { Route as DocumentsTemplatesNewRouteImport } from './routes/documents.templates.new'
|
||||
import { Route as DocumentsTemplatesTemplateIdRouteImport } from './routes/documents.templates.$templateId'
|
||||
import { Route as DocumentsPleadingNewRouteImport } from './routes/documents.pleading.new'
|
||||
|
||||
const SetupRoute = SetupRouteImport.update({
|
||||
id: '/setup',
|
||||
@@ -50,6 +55,11 @@ const SettingsIndexRoute = SettingsIndexRouteImport.update({
|
||||
path: '/',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const DocumentsIndexRoute = DocumentsIndexRouteImport.update({
|
||||
id: '/documents/',
|
||||
path: '/documents/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const CollectionsIndexRoute = CollectionsIndexRouteImport.update({
|
||||
id: '/collections/',
|
||||
path: '/collections/',
|
||||
@@ -100,6 +110,27 @@ const AdminUsersRoute = AdminUsersRouteImport.update({
|
||||
path: '/admin/users',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const DocumentsTemplatesIndexRoute = DocumentsTemplatesIndexRouteImport.update({
|
||||
id: '/documents/templates/',
|
||||
path: '/documents/templates/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const DocumentsTemplatesNewRoute = DocumentsTemplatesNewRouteImport.update({
|
||||
id: '/documents/templates/new',
|
||||
path: '/documents/templates/new',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const DocumentsTemplatesTemplateIdRoute =
|
||||
DocumentsTemplatesTemplateIdRouteImport.update({
|
||||
id: '/documents/templates/$templateId',
|
||||
path: '/documents/templates/$templateId',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const DocumentsPleadingNewRoute = DocumentsPleadingNewRouteImport.update({
|
||||
id: '/documents/pleading/new',
|
||||
path: '/documents/pleading/new',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
@@ -116,7 +147,12 @@ export interface FileRoutesByFullPath {
|
||||
'/cases/': typeof CasesIndexRoute
|
||||
'/clients/': typeof ClientsIndexRoute
|
||||
'/collections/': typeof CollectionsIndexRoute
|
||||
'/documents/': typeof DocumentsIndexRoute
|
||||
'/settings/': typeof SettingsIndexRoute
|
||||
'/documents/pleading/new': typeof DocumentsPleadingNewRoute
|
||||
'/documents/templates/$templateId': typeof DocumentsTemplatesTemplateIdRoute
|
||||
'/documents/templates/new': typeof DocumentsTemplatesNewRoute
|
||||
'/documents/templates/': typeof DocumentsTemplatesIndexRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
@@ -132,7 +168,12 @@ export interface FileRoutesByTo {
|
||||
'/cases': typeof CasesIndexRoute
|
||||
'/clients': typeof ClientsIndexRoute
|
||||
'/collections': typeof CollectionsIndexRoute
|
||||
'/documents': typeof DocumentsIndexRoute
|
||||
'/settings': typeof SettingsIndexRoute
|
||||
'/documents/pleading/new': typeof DocumentsPleadingNewRoute
|
||||
'/documents/templates/$templateId': typeof DocumentsTemplatesTemplateIdRoute
|
||||
'/documents/templates/new': typeof DocumentsTemplatesNewRoute
|
||||
'/documents/templates': typeof DocumentsTemplatesIndexRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
@@ -150,7 +191,12 @@ export interface FileRoutesById {
|
||||
'/cases/': typeof CasesIndexRoute
|
||||
'/clients/': typeof ClientsIndexRoute
|
||||
'/collections/': typeof CollectionsIndexRoute
|
||||
'/documents/': typeof DocumentsIndexRoute
|
||||
'/settings/': typeof SettingsIndexRoute
|
||||
'/documents/pleading/new': typeof DocumentsPleadingNewRoute
|
||||
'/documents/templates/$templateId': typeof DocumentsTemplatesTemplateIdRoute
|
||||
'/documents/templates/new': typeof DocumentsTemplatesNewRoute
|
||||
'/documents/templates/': typeof DocumentsTemplatesIndexRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
@@ -169,7 +215,12 @@ export interface FileRouteTypes {
|
||||
| '/cases/'
|
||||
| '/clients/'
|
||||
| '/collections/'
|
||||
| '/documents/'
|
||||
| '/settings/'
|
||||
| '/documents/pleading/new'
|
||||
| '/documents/templates/$templateId'
|
||||
| '/documents/templates/new'
|
||||
| '/documents/templates/'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to:
|
||||
| '/'
|
||||
@@ -185,7 +236,12 @@ export interface FileRouteTypes {
|
||||
| '/cases'
|
||||
| '/clients'
|
||||
| '/collections'
|
||||
| '/documents'
|
||||
| '/settings'
|
||||
| '/documents/pleading/new'
|
||||
| '/documents/templates/$templateId'
|
||||
| '/documents/templates/new'
|
||||
| '/documents/templates'
|
||||
id:
|
||||
| '__root__'
|
||||
| '/'
|
||||
@@ -202,7 +258,12 @@ export interface FileRouteTypes {
|
||||
| '/cases/'
|
||||
| '/clients/'
|
||||
| '/collections/'
|
||||
| '/documents/'
|
||||
| '/settings/'
|
||||
| '/documents/pleading/new'
|
||||
| '/documents/templates/$templateId'
|
||||
| '/documents/templates/new'
|
||||
| '/documents/templates/'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
@@ -218,6 +279,11 @@ export interface RootRouteChildren {
|
||||
CasesIndexRoute: typeof CasesIndexRoute
|
||||
ClientsIndexRoute: typeof ClientsIndexRoute
|
||||
CollectionsIndexRoute: typeof CollectionsIndexRoute
|
||||
DocumentsIndexRoute: typeof DocumentsIndexRoute
|
||||
DocumentsPleadingNewRoute: typeof DocumentsPleadingNewRoute
|
||||
DocumentsTemplatesTemplateIdRoute: typeof DocumentsTemplatesTemplateIdRoute
|
||||
DocumentsTemplatesNewRoute: typeof DocumentsTemplatesNewRoute
|
||||
DocumentsTemplatesIndexRoute: typeof DocumentsTemplatesIndexRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
@@ -257,6 +323,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsIndexRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/documents/': {
|
||||
id: '/documents/'
|
||||
path: '/documents'
|
||||
fullPath: '/documents/'
|
||||
preLoaderRoute: typeof DocumentsIndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/collections/': {
|
||||
id: '/collections/'
|
||||
path: '/collections'
|
||||
@@ -327,6 +400,34 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AdminUsersRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/documents/templates/': {
|
||||
id: '/documents/templates/'
|
||||
path: '/documents/templates'
|
||||
fullPath: '/documents/templates/'
|
||||
preLoaderRoute: typeof DocumentsTemplatesIndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/documents/templates/new': {
|
||||
id: '/documents/templates/new'
|
||||
path: '/documents/templates/new'
|
||||
fullPath: '/documents/templates/new'
|
||||
preLoaderRoute: typeof DocumentsTemplatesNewRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/documents/templates/$templateId': {
|
||||
id: '/documents/templates/$templateId'
|
||||
path: '/documents/templates/$templateId'
|
||||
fullPath: '/documents/templates/$templateId'
|
||||
preLoaderRoute: typeof DocumentsTemplatesTemplateIdRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/documents/pleading/new': {
|
||||
id: '/documents/pleading/new'
|
||||
path: '/documents/pleading/new'
|
||||
fullPath: '/documents/pleading/new'
|
||||
preLoaderRoute: typeof DocumentsPleadingNewRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,6 +460,11 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
CasesIndexRoute: CasesIndexRoute,
|
||||
ClientsIndexRoute: ClientsIndexRoute,
|
||||
CollectionsIndexRoute: CollectionsIndexRoute,
|
||||
DocumentsIndexRoute: DocumentsIndexRoute,
|
||||
DocumentsPleadingNewRoute: DocumentsPleadingNewRoute,
|
||||
DocumentsTemplatesTemplateIdRoute: DocumentsTemplatesTemplateIdRoute,
|
||||
DocumentsTemplatesNewRoute: DocumentsTemplatesNewRoute,
|
||||
DocumentsTemplatesIndexRoute: DocumentsTemplatesIndexRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 as unknown as FieldDef[]) : []);
|
||||
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: 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 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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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: fields as any,
|
||||
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'll be replaced when generating a document.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</PageContainer>
|
||||
</ProtectedLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
-- Documents templates and generated docs
|
||||
|
||||
CREATE TABLE public.document_templates (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name text NOT NULL,
|
||||
description text,
|
||||
kind text NOT NULL DEFAULT 'general', -- 'general' | 'pleading'
|
||||
body text NOT NULL DEFAULT '',
|
||||
fields jsonb NOT NULL DEFAULT '[]'::jsonb, -- [{key, label, type}]
|
||||
font_family text NOT NULL DEFAULT 'Bookman Old Style',
|
||||
font_size_pt integer NOT NULL DEFAULT 12,
|
||||
created_by uuid,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE public.document_templates ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY "doc_templates_select_auth" ON public.document_templates
|
||||
FOR SELECT TO authenticated USING (true);
|
||||
CREATE POLICY "doc_templates_insert_auth" ON public.document_templates
|
||||
FOR INSERT TO authenticated WITH CHECK (auth.uid() IS NOT NULL);
|
||||
CREATE POLICY "doc_templates_update_owner" ON public.document_templates
|
||||
FOR UPDATE TO authenticated USING (is_admin(auth.uid()) OR created_by = auth.uid());
|
||||
CREATE POLICY "doc_templates_delete_owner" ON public.document_templates
|
||||
FOR DELETE TO authenticated USING (is_admin(auth.uid()) OR created_by = auth.uid());
|
||||
|
||||
CREATE TRIGGER trg_doc_templates_updated
|
||||
BEFORE UPDATE ON public.document_templates
|
||||
FOR EACH ROW EXECUTE FUNCTION public.tg_set_updated_at();
|
||||
|
||||
CREATE TABLE public.generated_documents (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name text NOT NULL,
|
||||
template_id uuid REFERENCES public.document_templates(id) ON DELETE SET NULL,
|
||||
kind text NOT NULL DEFAULT 'general',
|
||||
payload jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
body text,
|
||||
storage_path text,
|
||||
created_by uuid,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE public.generated_documents ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY "gen_docs_select_owner" ON public.generated_documents
|
||||
FOR SELECT TO authenticated USING (is_admin(auth.uid()) OR created_by = auth.uid());
|
||||
CREATE POLICY "gen_docs_insert_auth" ON public.generated_documents
|
||||
FOR INSERT TO authenticated WITH CHECK (auth.uid() IS NOT NULL);
|
||||
CREATE POLICY "gen_docs_update_owner" ON public.generated_documents
|
||||
FOR UPDATE TO authenticated USING (is_admin(auth.uid()) OR created_by = auth.uid());
|
||||
CREATE POLICY "gen_docs_delete_owner" ON public.generated_documents
|
||||
FOR DELETE TO authenticated USING (is_admin(auth.uid()) OR created_by = auth.uid());
|
||||
|
||||
CREATE TRIGGER trg_gen_docs_updated
|
||||
BEFORE UPDATE ON public.generated_documents
|
||||
FOR EACH ROW EXECUTE FUNCTION public.tg_set_updated_at();
|
||||
|
||||
-- Storage bucket for generated docs
|
||||
INSERT INTO storage.buckets (id, name, public) VALUES ('generated-documents', 'generated-documents', false)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
CREATE POLICY "gen_docs_storage_select" ON storage.objects
|
||||
FOR SELECT TO authenticated
|
||||
USING (bucket_id = 'generated-documents' AND auth.uid()::text = (storage.foldername(name))[1]);
|
||||
CREATE POLICY "gen_docs_storage_insert" ON storage.objects
|
||||
FOR INSERT TO authenticated
|
||||
WITH CHECK (bucket_id = 'generated-documents' AND auth.uid()::text = (storage.foldername(name))[1]);
|
||||
CREATE POLICY "gen_docs_storage_delete" ON storage.objects
|
||||
FOR DELETE TO authenticated
|
||||
USING (bucket_id = 'generated-documents' AND auth.uid()::text = (storage.foldername(name))[1]);
|
||||
|
||||
-- Seed default Pleading template
|
||||
INSERT INTO public.document_templates (name, kind, description, body, fields)
|
||||
VALUES (
|
||||
'Florida Pleading',
|
||||
'pleading',
|
||||
'Standard Florida court pleading with caption header.',
|
||||
'',
|
||||
'[]'::jsonb
|
||||
);
|
||||
Reference in New Issue
Block a user