Added archive route & sidebar
X-Lovable-Edit-ID: edt-31833c1c-8606-4eb7-a6f6-08ee3c41a947 Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
@@ -22,6 +22,7 @@ import {
|
||||
User as UserIcon,
|
||||
Inbox as InboxIcon,
|
||||
CreditCard,
|
||||
Archive as ArchiveIcon,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ReactNode } from "react";
|
||||
@@ -43,6 +44,7 @@ const NAV: NavItem[] = (() => {
|
||||
const dashboard: NavItem = { to: "/", label: "Dashboard", icon: LayoutDashboard };
|
||||
const rest: NavItem[] = [
|
||||
{ to: "/admin/users", label: "Users", icon: ShieldCheck, adminOnly: true },
|
||||
{ to: "/archive", label: "Archive", icon: ArchiveIcon },
|
||||
{ to: "/calendar", label: "Calendar", icon: CalendarIcon },
|
||||
{ to: "/cases", label: "Cases", icon: Briefcase },
|
||||
{ to: "/clients", label: "Clients", icon: Users },
|
||||
|
||||
@@ -14,6 +14,80 @@ export type Database = {
|
||||
}
|
||||
public: {
|
||||
Tables: {
|
||||
archive_categories: {
|
||||
Row: {
|
||||
active: boolean
|
||||
created_at: string
|
||||
created_by: string | null
|
||||
id: string
|
||||
key: string
|
||||
label: string
|
||||
sort_order: number
|
||||
updated_at: string
|
||||
}
|
||||
Insert: {
|
||||
active?: boolean
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
id?: string
|
||||
key: string
|
||||
label: string
|
||||
sort_order?: number
|
||||
updated_at?: string
|
||||
}
|
||||
Update: {
|
||||
active?: boolean
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
id?: string
|
||||
key?: string
|
||||
label?: string
|
||||
sort_order?: number
|
||||
updated_at?: string
|
||||
}
|
||||
Relationships: []
|
||||
}
|
||||
archive_records: {
|
||||
Row: {
|
||||
batch_id: string | null
|
||||
category_id: string
|
||||
created_at: string
|
||||
created_by: string | null
|
||||
data: Json
|
||||
id: string
|
||||
row_index: number | null
|
||||
source_filename: string | null
|
||||
}
|
||||
Insert: {
|
||||
batch_id?: string | null
|
||||
category_id: string
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
data?: Json
|
||||
id?: string
|
||||
row_index?: number | null
|
||||
source_filename?: string | null
|
||||
}
|
||||
Update: {
|
||||
batch_id?: string | null
|
||||
category_id?: string
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
data?: Json
|
||||
id?: string
|
||||
row_index?: number | null
|
||||
source_filename?: string | null
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: "archive_records_category_id_fkey"
|
||||
columns: ["category_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "archive_categories"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
call_logs: {
|
||||
Row: {
|
||||
billable: boolean
|
||||
|
||||
@@ -28,6 +28,7 @@ import { Route as CollectionsIndexRouteImport } from './routes/collections.index
|
||||
import { Route as ClientsIndexRouteImport } from './routes/clients.index'
|
||||
import { Route as CasesIndexRouteImport } from './routes/cases.index'
|
||||
import { Route as CalendarIndexRouteImport } from './routes/calendar.index'
|
||||
import { Route as ArchiveIndexRouteImport } from './routes/archive.index'
|
||||
import { Route as SettingsWorkflowsRouteImport } from './routes/settings.workflows'
|
||||
import { Route as SettingsWorkflowRouteImport } from './routes/settings.workflow'
|
||||
import { Route as SettingsSmtpRouteImport } from './routes/settings.smtp'
|
||||
@@ -150,6 +151,11 @@ const CalendarIndexRoute = CalendarIndexRouteImport.update({
|
||||
path: '/calendar/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ArchiveIndexRoute = ArchiveIndexRouteImport.update({
|
||||
id: '/archive/',
|
||||
path: '/archive/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const SettingsWorkflowsRoute = SettingsWorkflowsRouteImport.update({
|
||||
id: '/workflows',
|
||||
path: '/workflows',
|
||||
@@ -308,6 +314,7 @@ export interface FileRoutesByFullPath {
|
||||
'/settings/smtp': typeof SettingsSmtpRoute
|
||||
'/settings/workflow': typeof SettingsWorkflowRoute
|
||||
'/settings/workflows': typeof SettingsWorkflowsRoute
|
||||
'/archive/': typeof ArchiveIndexRoute
|
||||
'/calendar/': typeof CalendarIndexRoute
|
||||
'/cases/': typeof CasesIndexRoute
|
||||
'/clients/': typeof ClientsIndexRoute
|
||||
@@ -354,6 +361,7 @@ export interface FileRoutesByTo {
|
||||
'/settings/smtp': typeof SettingsSmtpRoute
|
||||
'/settings/workflow': typeof SettingsWorkflowRoute
|
||||
'/settings/workflows': typeof SettingsWorkflowsRoute
|
||||
'/archive': typeof ArchiveIndexRoute
|
||||
'/calendar': typeof CalendarIndexRoute
|
||||
'/cases': typeof CasesIndexRoute
|
||||
'/clients': typeof ClientsIndexRoute
|
||||
@@ -402,6 +410,7 @@ export interface FileRoutesById {
|
||||
'/settings/smtp': typeof SettingsSmtpRoute
|
||||
'/settings/workflow': typeof SettingsWorkflowRoute
|
||||
'/settings/workflows': typeof SettingsWorkflowsRoute
|
||||
'/archive/': typeof ArchiveIndexRoute
|
||||
'/calendar/': typeof CalendarIndexRoute
|
||||
'/cases/': typeof CasesIndexRoute
|
||||
'/clients/': typeof ClientsIndexRoute
|
||||
@@ -451,6 +460,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/smtp'
|
||||
| '/settings/workflow'
|
||||
| '/settings/workflows'
|
||||
| '/archive/'
|
||||
| '/calendar/'
|
||||
| '/cases/'
|
||||
| '/clients/'
|
||||
@@ -497,6 +507,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/smtp'
|
||||
| '/settings/workflow'
|
||||
| '/settings/workflows'
|
||||
| '/archive'
|
||||
| '/calendar'
|
||||
| '/cases'
|
||||
| '/clients'
|
||||
@@ -544,6 +555,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/smtp'
|
||||
| '/settings/workflow'
|
||||
| '/settings/workflows'
|
||||
| '/archive/'
|
||||
| '/calendar/'
|
||||
| '/cases/'
|
||||
| '/clients/'
|
||||
@@ -582,6 +594,7 @@ export interface RootRouteChildren {
|
||||
InvoicesInvoiceIdRoute: typeof InvoicesInvoiceIdRoute
|
||||
InvoicesNewRoute: typeof InvoicesNewRouteWithChildren
|
||||
PayIdRoute: typeof PayIdRoute
|
||||
ArchiveIndexRoute: typeof ArchiveIndexRoute
|
||||
CalendarIndexRoute: typeof CalendarIndexRoute
|
||||
CasesIndexRoute: typeof CasesIndexRoute
|
||||
ClientsIndexRoute: typeof ClientsIndexRoute
|
||||
@@ -737,6 +750,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof CalendarIndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/archive/': {
|
||||
id: '/archive/'
|
||||
path: '/archive'
|
||||
fullPath: '/archive/'
|
||||
preLoaderRoute: typeof ArchiveIndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/settings/workflows': {
|
||||
id: '/settings/workflows'
|
||||
path: '/workflows'
|
||||
@@ -982,6 +1002,7 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
InvoicesInvoiceIdRoute: InvoicesInvoiceIdRoute,
|
||||
InvoicesNewRoute: InvoicesNewRouteWithChildren,
|
||||
PayIdRoute: PayIdRoute,
|
||||
ArchiveIndexRoute: ArchiveIndexRoute,
|
||||
CalendarIndexRoute: CalendarIndexRoute,
|
||||
CasesIndexRoute: CasesIndexRoute,
|
||||
ClientsIndexRoute: ClientsIndexRoute,
|
||||
|
||||
@@ -0,0 +1,539 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import Papa from "papaparse";
|
||||
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 { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
DialogDescription,
|
||||
} from "@/components/ui/dialog";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import { toast } from "sonner";
|
||||
import { Archive as ArchiveIcon, Plus, Upload, Trash2, FileSpreadsheet } from "lucide-react";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
|
||||
export const Route = createFileRoute("/archive/")({
|
||||
component: () => (
|
||||
<ProtectedLayout>
|
||||
<ArchivePage />
|
||||
</ProtectedLayout>
|
||||
),
|
||||
});
|
||||
|
||||
interface Category {
|
||||
id: string;
|
||||
key: string;
|
||||
label: string;
|
||||
sort_order: number;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
interface ArchiveRow {
|
||||
id: string;
|
||||
category_id: string;
|
||||
data: Record<string, unknown>;
|
||||
source_filename: string | null;
|
||||
batch_id: string | null;
|
||||
row_index: number | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
function ArchivePage() {
|
||||
const { isAdmin } = useAuth();
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [activeId, setActiveId] = useState<string>("");
|
||||
const [rows, setRows] = useState<ArchiveRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [search, setSearch] = useState("");
|
||||
const [uploadOpen, setUploadOpen] = useState(false);
|
||||
const [newCatOpen, setNewCatOpen] = useState(false);
|
||||
|
||||
const loadCategories = async () => {
|
||||
const { data, error } = await supabase
|
||||
.from("archive_categories")
|
||||
.select("*")
|
||||
.eq("active", true)
|
||||
.order("sort_order");
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
return;
|
||||
}
|
||||
setCategories(data ?? []);
|
||||
if (!activeId && data && data.length > 0) {
|
||||
setActiveId(data[0].id);
|
||||
}
|
||||
};
|
||||
|
||||
const loadRows = async (categoryId: string) => {
|
||||
if (!categoryId) return;
|
||||
setLoading(true);
|
||||
const { data, error } = await supabase
|
||||
.from("archive_records")
|
||||
.select("*")
|
||||
.eq("category_id", categoryId)
|
||||
.order("created_at", { ascending: false })
|
||||
.limit(1000);
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setRows((data ?? []) as ArchiveRow[]);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadCategories();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeId) loadRows(activeId);
|
||||
}, [activeId]);
|
||||
|
||||
const activeCategory = categories.find((c) => c.id === activeId);
|
||||
|
||||
// Compute the union of all keys across rows for table headers
|
||||
const columns = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
for (const r of rows) {
|
||||
if (r.data && typeof r.data === "object") {
|
||||
for (const k of Object.keys(r.data)) set.add(k);
|
||||
}
|
||||
}
|
||||
return Array.from(set);
|
||||
}, [rows]);
|
||||
|
||||
const filteredRows = useMemo(() => {
|
||||
if (!search.trim()) return rows;
|
||||
const s = search.toLowerCase();
|
||||
return rows.filter((r) => JSON.stringify(r.data).toLowerCase().includes(s));
|
||||
}, [rows, search]);
|
||||
|
||||
const deleteRow = async (id: string) => {
|
||||
if (!confirm("Delete this record?")) return;
|
||||
const { error } = await supabase.from("archive_records").delete().eq("id", id);
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
return;
|
||||
}
|
||||
setRows((prev) => prev.filter((r) => r.id !== id));
|
||||
toast.success("Record deleted");
|
||||
};
|
||||
|
||||
const deleteAllInCategory = async () => {
|
||||
if (!activeCategory) return;
|
||||
if (!confirm(`Delete ALL ${rows.length} records in "${activeCategory.label}"? This cannot be undone.`)) return;
|
||||
const { error } = await supabase.from("archive_records").delete().eq("category_id", activeCategory.id);
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
return;
|
||||
}
|
||||
setRows([]);
|
||||
toast.success("All records deleted");
|
||||
};
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader
|
||||
title="Archive"
|
||||
description="Historical records uploaded from CSV. Read-only reference data."
|
||||
actions={
|
||||
isAdmin ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setNewCatOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" /> New tab
|
||||
</Button>
|
||||
<Button onClick={() => setUploadOpen(true)} disabled={!activeCategory}>
|
||||
<Upload className="h-4 w-4 mr-2" /> Upload CSV
|
||||
</Button>
|
||||
</>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-1 border-b border-border mb-4 overflow-x-auto">
|
||||
{categories.map((cat) => {
|
||||
const isActive = cat.id === activeId;
|
||||
return (
|
||||
<button
|
||||
key={cat.id}
|
||||
onClick={() => setActiveId(cat.id)}
|
||||
className={
|
||||
"px-4 py-2 text-sm font-medium whitespace-nowrap border-b-2 transition-colors " +
|
||||
(isActive
|
||||
? "border-primary text-foreground"
|
||||
: "border-transparent text-muted-foreground hover:text-foreground")
|
||||
}
|
||||
>
|
||||
{cat.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{categories.length === 0 && (
|
||||
<div className="px-4 py-2 text-sm text-muted-foreground">No categories yet.</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Toolbar */}
|
||||
<Card className="border-border/60 mb-4">
|
||||
<CardContent className="p-3 flex flex-col sm:flex-row gap-2 items-stretch sm:items-center">
|
||||
<Input
|
||||
placeholder="Search rows…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="flex-1"
|
||||
/>
|
||||
<div className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{filteredRows.length} of {rows.length} rows
|
||||
</div>
|
||||
{isAdmin && rows.length > 0 && (
|
||||
<Button variant="outline" size="sm" onClick={deleteAllInCategory}>
|
||||
<Trash2 className="h-4 w-4 mr-1" /> Clear tab
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Table */}
|
||||
<Card className="border-border/60 overflow-hidden">
|
||||
<CardContent className="p-0">
|
||||
{loading ? (
|
||||
<div className="text-center py-12 text-muted-foreground">Loading…</div>
|
||||
) : rows.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<ArchiveIcon className="h-8 w-8 mx-auto mb-2 opacity-40" />
|
||||
No records in this tab yet.
|
||||
{isAdmin && activeCategory && (
|
||||
<div className="mt-2 text-xs">Click "Upload CSV" to add records.</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto max-w-full">
|
||||
<table className="w-full text-xs">
|
||||
<thead className="bg-muted/50 text-[10px] uppercase tracking-wider text-muted-foreground">
|
||||
<tr>
|
||||
{columns.map((c) => (
|
||||
<th key={c} className="text-left px-3 py-2 font-medium whitespace-nowrap">
|
||||
{c}
|
||||
</th>
|
||||
))}
|
||||
<th className="text-right px-3 py-2 font-medium whitespace-nowrap">Imported</th>
|
||||
{isAdmin && <th className="px-3 py-2 w-10"></th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filteredRows.map((r) => (
|
||||
<tr key={r.id} className="border-t hover:bg-muted/30">
|
||||
{columns.map((c) => (
|
||||
<td key={c} className="px-3 py-2 align-top max-w-xs truncate" title={String(r.data?.[c] ?? "")}>
|
||||
{String(r.data?.[c] ?? "")}
|
||||
</td>
|
||||
))}
|
||||
<td className="px-3 py-2 text-right text-muted-foreground whitespace-nowrap">
|
||||
{formatDateTime(r.created_at)}
|
||||
{r.source_filename && (
|
||||
<div className="text-[10px] flex items-center justify-end gap-1 mt-0.5">
|
||||
<FileSpreadsheet className="h-3 w-3" />
|
||||
{r.source_filename}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
{isAdmin && (
|
||||
<td className="px-3 py-2 text-right">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => deleteRow(r.id)}
|
||||
title="Delete row"
|
||||
className="text-destructive hover:text-destructive h-7 w-7 p-0"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{activeCategory && (
|
||||
<UploadDialog
|
||||
open={uploadOpen}
|
||||
onOpenChange={setUploadOpen}
|
||||
category={activeCategory}
|
||||
onDone={() => {
|
||||
setUploadOpen(false);
|
||||
loadRows(activeCategory.id);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<NewCategoryDialog
|
||||
open={newCatOpen}
|
||||
onOpenChange={setNewCatOpen}
|
||||
existingKeys={categories.map((c) => c.key)}
|
||||
onCreated={(id) => {
|
||||
setNewCatOpen(false);
|
||||
loadCategories().then(() => setActiveId(id));
|
||||
}}
|
||||
/>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function NewCategoryDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
existingKeys,
|
||||
onCreated,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
existingKeys: string[];
|
||||
onCreated: (id: string) => void;
|
||||
}) {
|
||||
const [label, setLabel] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const submit = async () => {
|
||||
const trimmed = label.trim();
|
||||
if (!trimmed) {
|
||||
toast.error("Name required");
|
||||
return;
|
||||
}
|
||||
let key = trimmed.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
||||
if (!key) key = `tab_${Date.now()}`;
|
||||
let suffix = 1;
|
||||
let finalKey = key;
|
||||
while (existingKeys.includes(finalKey)) {
|
||||
suffix += 1;
|
||||
finalKey = `${key}_${suffix}`;
|
||||
}
|
||||
setSubmitting(true);
|
||||
const { data, error } = await supabase
|
||||
.from("archive_categories")
|
||||
.insert({ key: finalKey, label: trimmed, sort_order: 1000 })
|
||||
.select("id")
|
||||
.single();
|
||||
setSubmitting(false);
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
return;
|
||||
}
|
||||
setLabel("");
|
||||
toast.success("Tab created");
|
||||
onCreated(data.id);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>New archive tab</DialogTitle>
|
||||
<DialogDescription>Create a new category for archived records.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div>
|
||||
<Label className="text-xs">Tab name</Label>
|
||||
<Input
|
||||
value={label}
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
placeholder="e.g. Closed Files"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={submit} disabled={submitting}>
|
||||
{submitting ? "Creating…" : "Create"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function UploadDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
category,
|
||||
onDone,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
category: Category;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [preview, setPreview] = useState<Record<string, string>[]>([]);
|
||||
const [parsing, setParsing] = useState(false);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const reset = () => {
|
||||
setFile(null);
|
||||
setPreview([]);
|
||||
setProgress(null);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) reset();
|
||||
}, [open]);
|
||||
|
||||
const onPick = async (f: File) => {
|
||||
setFile(f);
|
||||
setParsing(true);
|
||||
Papa.parse<Record<string, string>>(f, {
|
||||
header: true,
|
||||
skipEmptyLines: true,
|
||||
preview: 5,
|
||||
complete: (result) => {
|
||||
setPreview(result.data ?? []);
|
||||
setParsing(false);
|
||||
},
|
||||
error: (err) => {
|
||||
toast.error(err.message);
|
||||
setParsing(false);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const upload = async () => {
|
||||
if (!file) return;
|
||||
setUploading(true);
|
||||
Papa.parse<Record<string, string>>(file, {
|
||||
header: true,
|
||||
skipEmptyLines: true,
|
||||
complete: async (result) => {
|
||||
const allRows = result.data ?? [];
|
||||
const batchId = crypto.randomUUID();
|
||||
const filename = file.name;
|
||||
const total = allRows.length;
|
||||
setProgress({ done: 0, total });
|
||||
const chunkSize = 500;
|
||||
let done = 0;
|
||||
for (let i = 0; i < allRows.length; i += chunkSize) {
|
||||
const chunk = allRows.slice(i, i + chunkSize).map((data, idx) => ({
|
||||
category_id: category.id,
|
||||
data,
|
||||
source_filename: filename,
|
||||
batch_id: batchId,
|
||||
row_index: i + idx,
|
||||
}));
|
||||
const { error } = await supabase.from("archive_records").insert(chunk);
|
||||
if (error) {
|
||||
toast.error(`Upload failed at row ${i}: ${error.message}`);
|
||||
setUploading(false);
|
||||
return;
|
||||
}
|
||||
done += chunk.length;
|
||||
setProgress({ done, total });
|
||||
}
|
||||
toast.success(`Uploaded ${total} rows to ${category.label}`);
|
||||
setUploading(false);
|
||||
onDone();
|
||||
},
|
||||
error: (err) => {
|
||||
toast.error(err.message);
|
||||
setUploading(false);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-3xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Upload CSV to {category.label}</DialogTitle>
|
||||
<DialogDescription>
|
||||
All columns from the CSV are stored as-is. No mapping required.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<Label className="text-xs">CSV file</Label>
|
||||
<Input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept=".csv,text/csv"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
if (f) onPick(f);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{parsing && <div className="text-sm text-muted-foreground">Parsing preview…</div>}
|
||||
|
||||
{preview.length > 0 && (
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground mb-1">
|
||||
Preview (first {preview.length} rows)
|
||||
</div>
|
||||
<div className="border rounded overflow-x-auto max-h-64">
|
||||
<table className="w-full text-xs">
|
||||
<thead className="bg-muted/50 sticky top-0">
|
||||
<tr>
|
||||
{Object.keys(preview[0]).map((k) => (
|
||||
<th key={k} className="text-left px-2 py-1 font-medium whitespace-nowrap">
|
||||
{k}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{preview.map((row, i) => (
|
||||
<tr key={i} className="border-t">
|
||||
{Object.keys(preview[0]).map((k) => (
|
||||
<td key={k} className="px-2 py-1 align-top max-w-[200px] truncate" title={row[k]}>
|
||||
{row[k]}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{progress && (
|
||||
<div className="text-sm">
|
||||
Uploading {progress.done.toLocaleString()} / {progress.total.toLocaleString()} rows…
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={uploading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={upload} disabled={!file || uploading || parsing}>
|
||||
{uploading ? "Uploading…" : "Upload"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
void Badge;
|
||||
@@ -0,0 +1,62 @@
|
||||
-- Categories: list of archive types (cases, time, expenses, plus user-added)
|
||||
CREATE TABLE public.archive_categories (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
key text NOT NULL UNIQUE,
|
||||
label text NOT NULL,
|
||||
sort_order integer NOT NULL DEFAULT 0,
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
created_by uuid
|
||||
);
|
||||
|
||||
ALTER TABLE public.archive_categories ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY "ac_select_auth" ON public.archive_categories
|
||||
FOR SELECT TO authenticated USING (true);
|
||||
CREATE POLICY "ac_insert_admin" ON public.archive_categories
|
||||
FOR INSERT TO authenticated WITH CHECK (public.is_admin(auth.uid()));
|
||||
CREATE POLICY "ac_update_admin" ON public.archive_categories
|
||||
FOR UPDATE TO authenticated USING (public.is_admin(auth.uid()));
|
||||
CREATE POLICY "ac_delete_admin" ON public.archive_categories
|
||||
FOR DELETE TO authenticated USING (public.is_admin(auth.uid()));
|
||||
|
||||
CREATE TRIGGER trg_ac_updated BEFORE UPDATE ON public.archive_categories
|
||||
FOR EACH ROW EXECUTE FUNCTION public.tg_set_updated_at();
|
||||
|
||||
-- Records: one row per CSV row, columns preserved verbatim in `data` JSONB
|
||||
CREATE TABLE public.archive_records (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
category_id uuid NOT NULL REFERENCES public.archive_categories(id) ON DELETE CASCADE,
|
||||
data jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
source_filename text,
|
||||
batch_id uuid,
|
||||
row_index integer,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
created_by uuid
|
||||
);
|
||||
|
||||
CREATE INDEX idx_archive_records_category ON public.archive_records(category_id, created_at DESC);
|
||||
CREATE INDEX idx_archive_records_batch ON public.archive_records(batch_id);
|
||||
|
||||
ALTER TABLE public.archive_records ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY "ar_select_auth" ON public.archive_records
|
||||
FOR SELECT TO authenticated USING (true);
|
||||
CREATE POLICY "ar_insert_admin" ON public.archive_records
|
||||
FOR INSERT TO authenticated WITH CHECK (public.is_admin(auth.uid()));
|
||||
CREATE POLICY "ar_delete_admin" ON public.archive_records
|
||||
FOR DELETE TO authenticated USING (public.is_admin(auth.uid()));
|
||||
|
||||
-- Seed default categories
|
||||
INSERT INTO public.archive_categories (key, label, sort_order) VALUES
|
||||
('cases', 'Cases', 10),
|
||||
('time_entries', 'Time Entries', 20),
|
||||
('expenses', 'Expenses', 30),
|
||||
('invoices', 'Invoices', 40),
|
||||
('clients', 'Clients', 50),
|
||||
('status_updates', 'Status Updates', 60),
|
||||
('contacts', 'Contacts', 70),
|
||||
('homeowners', 'Homeowners', 80),
|
||||
('call_logs', 'Call Logs', 90),
|
||||
('documents', 'Documents', 100);
|
||||
Reference in New Issue
Block a user