Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
575 lines
18 KiB
TypeScript
575 lines
18 KiB
TypeScript
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;
|
|
}
|
|
|
|
const PAGE_SIZE = 200;
|
|
|
|
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 [loadingMore, setLoadingMore] = useState(false);
|
|
const [search, setSearch] = useState("");
|
|
const [debouncedSearch, setDebouncedSearch] = useState("");
|
|
const [totalCount, setTotalCount] = useState(0);
|
|
const [uploadOpen, setUploadOpen] = useState(false);
|
|
const [newCatOpen, setNewCatOpen] = useState(false);
|
|
|
|
// Debounce search input (300ms)
|
|
useEffect(() => {
|
|
const t = setTimeout(() => setDebouncedSearch(search.trim()), 300);
|
|
return () => clearTimeout(t);
|
|
}, [search]);
|
|
|
|
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 buildQuery = (categoryId: string, searchTerm: string) => {
|
|
let q = supabase
|
|
.from("archive_records")
|
|
.select("*", { count: "exact" })
|
|
.eq("category_id", categoryId);
|
|
if (searchTerm) {
|
|
// Cast jsonb to text and search case-insensitively
|
|
q = q.ilike("data::text", `%${searchTerm}%`);
|
|
}
|
|
return q.order("created_at", { ascending: false });
|
|
};
|
|
|
|
const loadRows = async (categoryId: string, searchTerm: string) => {
|
|
if (!categoryId) return;
|
|
setLoading(true);
|
|
const { data, error, count } = await buildQuery(categoryId, searchTerm).range(
|
|
0,
|
|
PAGE_SIZE - 1,
|
|
);
|
|
if (error) {
|
|
toast.error(error.message);
|
|
setLoading(false);
|
|
return;
|
|
}
|
|
setRows((data ?? []) as ArchiveRow[]);
|
|
setTotalCount(count ?? 0);
|
|
setLoading(false);
|
|
};
|
|
|
|
const loadMore = async () => {
|
|
if (!activeId || loadingMore) return;
|
|
setLoadingMore(true);
|
|
const { data, error } = await buildQuery(activeId, debouncedSearch).range(
|
|
rows.length,
|
|
rows.length + PAGE_SIZE - 1,
|
|
);
|
|
if (error) {
|
|
toast.error(error.message);
|
|
setLoadingMore(false);
|
|
return;
|
|
}
|
|
setRows((prev) => [...prev, ...((data ?? []) as ArchiveRow[])]);
|
|
setLoadingMore(false);
|
|
};
|
|
|
|
useEffect(() => {
|
|
loadCategories();
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (activeId) loadRows(activeId, debouncedSearch);
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [activeId, debouncedSearch]);
|
|
|
|
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 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));
|
|
setTotalCount((c) => Math.max(0, c - 1));
|
|
toast.success("Record deleted");
|
|
};
|
|
|
|
const deleteAllInCategory = async () => {
|
|
if (!activeCategory) return;
|
|
if (!confirm(`Delete ALL ${totalCount} 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([]);
|
|
setTotalCount(0);
|
|
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">
|
|
Showing {rows.length} of {totalCount} {debouncedSearch ? "matching" : ""} 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;
|