Spaces:
Sleeping
Sleeping
Download befree-frontend/features/classify/ClassifyFeature.tsx from Coeinterns/bank-statement-api: direct link, hf CLI and curl.
- Browser
- Download file 66.2 kB
-
https://huggingface.co/spaces/Coeinterns/bank-statement-api/resolve/main/befree-frontend/features/classify/ClassifyFeature.tsx
- Command line
-
hf download hf://spaces/Coeinterns/bank-statement-api/befree-frontend/features/classify/ClassifyFeature.tsx
-
curl -L -o ClassifyFeature.tsx https://huggingface.co/spaces/Coeinterns/bank-statement-api/resolve/main/befree-frontend/features/classify/ClassifyFeature.tsx
66.2 kB
'use client';
import { Suspense, useState, useEffect, useCallback, useMemo } from 'react';
import { useParams, useRouter } from 'next/navigation';
import {
useTransactions,
useClassifyStatus,
useGenerateExport,
useCategories,
useRules,
useCreateCategory,
useUpdateCategory,
useDeleteCategory,
useCreateRule,
useUpdateRule,
useDeleteRule,
useConfirmClassifySuggestion,
useConfirmClassifySuggestionsBulk,
} from '@/hooks/useStatementAPI';
import { ClassificationTable } from '@/components/tables/ClassificationTable';
import { LoadingState, ErrorState } from '@/components/shared';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import { normalizeDownloadUrl } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import type { CategoryRecord, RuleRecord } from '@/services/api-client';
import {
X,
Search,
ChevronDown,
ChevronRight,
Tag,
Filter,
Plus,
Pencil,
Trash2,
Save,
XCircle,
Loader2,
AlertTriangle,
ToggleLeft,
ToggleRight,
Lock,
FileDown,
ArrowRight,
Check,
FileText,
Sliders,
Sparkles,
CheckCircle2,
} from 'lucide-react';
// βββ Colour map for sheet groups ββββββββββββββββββββββββββββββββββββββββββββββ
export const SHEET_COLORS: Record<string, { bg: string; text: string; border: string; dot: string; badge: string }> = {
'Food and Groceries': {
bg: 'bg-orange-50', text: 'text-orange-700',
border: 'border-orange-200', dot: 'bg-orange-400',
badge: 'bg-orange-100 text-orange-700',
},
'Recreation & Entertainment': {
bg: 'bg-rose-50', text: 'text-rose-700',
border: 'border-rose-200', dot: 'bg-rose-400',
badge: 'bg-rose-100 text-rose-700',
},
'Clothing & Personal Care': {
bg: 'bg-pink-50', text: 'text-pink-700',
border: 'border-pink-200', dot: 'bg-pink-400',
badge: 'bg-pink-100 text-pink-700',
},
'Transport & Auto': {
bg: 'bg-sky-50', text: 'text-sky-700',
border: 'border-sky-200', dot: 'bg-sky-400',
badge: 'bg-sky-100 text-sky-700',
},
'Owner Occupied Property Expense': {
bg: 'bg-yellow-50', text: 'text-yellow-700',
border: 'border-yellow-200', dot: 'bg-yellow-400',
badge: 'bg-yellow-100 text-yellow-700',
},
'Telephone & Internet': {
bg: 'bg-violet-50', text: 'text-violet-700',
border: 'border-violet-200', dot: 'bg-violet-400',
badge: 'bg-violet-100 text-violet-700',
},
'Medical, Health & Fitness': {
bg: 'bg-green-50', text: 'text-green-700',
border: 'border-green-200', dot: 'bg-green-400',
badge: 'bg-green-100 text-green-700',
},
'Miscellaneous': {
bg: 'bg-indigo-50', text: 'text-indigo-700',
border: 'border-indigo-200', dot: 'bg-indigo-400',
badge: 'bg-indigo-100 text-indigo-700',
},
'Public Education': {
bg: 'bg-teal-50', text: 'text-teal-700',
border: 'border-teal-200', dot: 'bg-teal-500',
badge: 'bg-teal-100 text-teal-700',
},
'Private Education': {
bg: 'bg-teal-50', text: 'text-teal-800',
border: 'border-teal-300', dot: 'bg-teal-600',
badge: 'bg-teal-100 text-teal-800',
},
'Health Insurance': {
bg: 'bg-emerald-50', text: 'text-emerald-700',
border: 'border-emerald-200', dot: 'bg-emerald-400',
badge: 'bg-emerald-100 text-emerald-700',
},
'General Insurance': {
bg: 'bg-amber-50', text: 'text-amber-700',
border: 'border-amber-200', dot: 'bg-amber-400',
badge: 'bg-amber-100 text-amber-700',
},
'Salaries & Wages': {
bg: 'bg-gray-50', text: 'text-gray-600',
border: 'border-gray-200', dot: 'bg-gray-400',
badge: 'bg-gray-100 text-gray-600',
},
'Tax / Loans / Financial': {
bg: 'bg-red-50', text: 'text-red-700',
border: 'border-red-200', dot: 'bg-red-400',
badge: 'bg-red-100 text-red-700',
},
'Transfers & Internal Movements': {
bg: 'bg-gray-100', text: 'text-gray-500',
border: 'border-gray-300', dot: 'bg-gray-400',
badge: 'bg-gray-200 text-gray-700',
},
'Children': {
bg: 'bg-lime-50', text: 'text-lime-700',
border: 'border-lime-200', dot: 'bg-lime-400',
badge: 'bg-lime-100 text-lime-700',
},
'Pet': {
bg: 'bg-cyan-50', text: 'text-cyan-700',
border: 'border-cyan-200', dot: 'bg-cyan-400',
badge: 'bg-cyan-100 text-cyan-700',
},
'Adult Dependants': {
bg: 'bg-purple-50', text: 'text-purple-700',
border: 'border-purple-200', dot: 'bg-purple-400',
badge: 'bg-purple-100 text-purple-700',
},
'Excluded': { bg: 'bg-gray-50', text: 'text-gray-600', border: 'border-gray-200', dot: 'bg-gray-400', badge: 'bg-gray-100 text-gray-600' },
};
export const DEFAULT_COLOR = { bg: 'bg-gray-50', text: 'text-gray-600', border: 'border-gray-200', dot: 'bg-gray-300', badge: 'bg-gray-100 text-gray-600' };
function getColor(sheetName: string | null | undefined) {
return SHEET_COLORS[sheetName ?? ''] ?? DEFAULT_COLOR;
}
// βββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function groupBySheet(categories: CategoryRecord[], rules: RuleRecord[]) {
const catById: Record<string, CategoryRecord> = {};
categories.forEach(c => { catById[c.id] = c; });
const rulesByCat: Record<string, RuleRecord[]> = {};
rules.forEach(r => {
if (!rulesByCat[r.category_id]) rulesByCat[r.category_id] = [];
rulesByCat[r.category_id].push(r);
});
const sheets: Record<string, CategoryRecord[]> = {};
categories.forEach(c => {
const key = c.sheet_name ?? 'Excluded';
if (!sheets[key]) sheets[key] = [];
sheets[key].push(c);
});
return { sheets, rulesByCat, catById };
}
// βββ Inline Edit Components βββββββββββββββββββββββββββββββββββββββββββββββββββ
interface CategoryFormProps {
initial?: Partial<CategoryRecord>;
onSave: (data: { name: string; sheet_name: string; sub_column: string }) => Promise<void>;
onCancel: () => void;
isSaving: boolean;
}
function CategoryForm({ initial, onSave, onCancel, isSaving }: CategoryFormProps) {
const [name, setName] = useState(initial?.name ?? '');
const [sheet, setSheet] = useState(initial?.sheet_name ?? '');
const [sub, setSub] = useState(initial?.sub_column ?? '');
const handleSubmit = async () => {
if (!name.trim()) return;
await onSave({ name: name.trim(), sheet_name: sheet.trim(), sub_column: sub.trim() });
};
return (
<div className="p-3 bg-blue-50 border border-blue-200 rounded-lg space-y-2">
<div className="grid grid-cols-3 gap-2">
<div>
<label className="text-xs font-medium text-gray-600 mb-0.5 block">Category name *</label>
<input
className="w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={name}
onChange={e => setName(e.target.value)}
placeholder="e.g. Groceries"
/>
</div>
<div>
<label className="text-xs font-medium text-gray-600 mb-0.5 block">Sheet name</label>
<input
className="w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={sheet}
onChange={e => setSheet(e.target.value)}
placeholder="e.g. Food & Dining"
/>
</div>
<div>
<label className="text-xs font-medium text-gray-600 mb-0.5 block">Sub column</label>
<input
className="w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={sub}
onChange={e => setSub(e.target.value)}
placeholder="e.g. Food and grocery"
/>
</div>
</div>
<div className="flex gap-2 justify-end">
<button onClick={onCancel} className="flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700 px-2 py-1 rounded hover:bg-gray-100">
<XCircle className="w-3.5 h-3.5" /> Cancel
</button>
<button
onClick={handleSubmit}
disabled={isSaving || !name.trim()}
className="flex items-center gap-1 text-xs font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 px-3 py-1 rounded"
>
{isSaving ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Save className="w-3.5 h-3.5" />}
Save
</button>
</div>
</div>
);
}
interface RuleFormProps {
categories: CategoryRecord[];
initial?: Partial<RuleRecord>;
defaultCategoryId?: string;
onSave: (data: Omit<RuleRecord, 'id' | 'created_at' | 'updated_at' | 'created_by' | 'updated_by' | 'category'>) => Promise<void>;
onCancel: () => void;
isSaving: boolean;
}
function RuleForm({ categories, initial, defaultCategoryId, onSave, onCancel, isSaving }: RuleFormProps) {
const [name, setName] = useState(initial?.name ?? '');
const [categoryId, setCategoryId] = useState(initial?.category_id ?? defaultCategoryId ?? '');
const [keywordsText, setKeywordsText] = useState((initial?.keywords ?? []).join('\n'));
const [priority, setPriority] = useState(initial?.priority ?? 5);
const [matchOn, setMatchOn] = useState<'description' | 'osko_reference'>(initial?.match_on ?? 'description');
const [txFilter, setTxFilter] = useState<'debit' | 'credit' | ''>(initial?.tx_type_filter ?? '');
const isActive = initial?.is_active ?? true;
const handleSubmit = async () => {
if (!name.trim() || !categoryId) return;
const keywords = keywordsText.split('\n').map(k => k.trim()).filter(Boolean);
await onSave({
name: name.trim(),
category_id: categoryId,
keywords,
priority,
match_on: matchOn,
tx_type_filter: (txFilter || null) as 'debit' | 'credit' | null,
amount_range: initial?.amount_range ?? null,
is_active: isActive,
});
};
return (
<div className="p-3 bg-blue-50 border border-blue-200 rounded-lg space-y-2">
<div className="grid grid-cols-2 gap-2">
<div>
<label className="text-xs font-medium text-gray-600 mb-0.5 block">Rule name *</label>
<input
className="w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={name}
onChange={e => setName(e.target.value)}
placeholder="e.g. supermarkets"
/>
</div>
<div>
<label className="text-xs font-medium text-gray-600 mb-0.5 block">Category *</label>
<select
className="w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={categoryId}
onChange={e => setCategoryId(e.target.value)}
>
<option value="">Select categoryβ¦</option>
{categories.map(c => (
<option key={c.id} value={c.id}>{c.name}</option>
))}
</select>
</div>
</div>
<div>
<label className="text-xs font-medium text-gray-600 mb-0.5 block">Keywords (one per line)</label>
<textarea
className="w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono"
rows={4}
value={keywordsText}
onChange={e => setKeywordsText(e.target.value)}
placeholder="woolworths coles aldi"
/>
</div>
<div className="grid grid-cols-3 gap-2">
<div>
<label className="text-xs font-medium text-gray-600 mb-0.5 block">Priority</label>
<input
type="number"
min={1} max={10}
className="w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={priority}
onChange={e => setPriority(Number(e.target.value))}
/>
</div>
<div>
<label className="text-xs font-medium text-gray-600 mb-0.5 block">Match on</label>
<select
className="w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={matchOn}
onChange={e => setMatchOn(e.target.value as any)}
>
<option value="description">Description</option>
<option value="osko_reference">OSKO reference</option>
</select>
</div>
<div>
<label className="text-xs font-medium text-gray-600 mb-0.5 block">Tx type filter</label>
<select
className="w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={txFilter}
onChange={e => setTxFilter(e.target.value as 'debit' | 'credit' | '')}
>
<option value="">Any</option>
<option value="debit">Debit only</option>
<option value="credit">Credit only</option>
</select>
</div>
</div>
<div className="flex gap-2 justify-end">
<button onClick={onCancel} className="flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700 px-2 py-1 rounded hover:bg-gray-100">
<XCircle className="w-3.5 h-3.5" /> Cancel
</button>
<button
onClick={handleSubmit}
disabled={isSaving || !name.trim() || !categoryId}
className="flex items-center gap-1 text-xs font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 px-3 py-1 rounded"
>
{isSaving ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Save className="w-3.5 h-3.5" />}
Save
</button>
</div>
</div>
);
}
// βββ Delete confirmation βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function ConfirmDelete({ label, onConfirm, onCancel }: { label: string; onConfirm: () => void; onCancel: () => void }) {
return (
<div className="flex items-center gap-2 bg-red-50 border border-red-200 rounded px-3 py-2">
<AlertTriangle className="w-4 h-4 text-red-600 shrink-0" />
<span className="text-xs text-red-700 flex-1">Delete <strong>{label}</strong>?</span>
<button onClick={onCancel} className="text-xs text-gray-500 hover:text-gray-700 px-2 py-0.5 rounded hover:bg-gray-100">Cancel</button>
<button onClick={onConfirm} className="text-xs font-medium text-white bg-red-600 hover:bg-red-700 px-2 py-0.5 rounded">Delete</button>
</div>
);
}
// βββ Main Modal βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
interface PresetRulesModalProps {
onClose: () => void;
isAdmin: boolean;
isManager: boolean;
}
function PresetRulesModal({ onClose, isAdmin, isManager }: PresetRulesModalProps) {
const { toast } = useToast();
const [search, setSearch] = useState('');
const [filterMatchOn, setFilterMatchOn] = useState<'all' | 'description' | 'osko_reference'>('all');
const [includeInactive, setIncludeInactive] = useState(false);
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set());
// Edit state
const [editingCategoryId, setEditingCategoryId] = useState<string | null>(null);
const [addingCategoryInSheet, setAddingCategoryInSheet] = useState<string | null>(null);
const [deletingCategoryId, setDeletingCategoryId] = useState<string | null>(null);
const [editingRuleId, setEditingRuleId] = useState<string | null>(null);
const [addingRuleInCategoryId, setAddingRuleInCategoryId] = useState<string | null>(null);
const [deletingRuleId, setDeletingRuleId] = useState<string | null>(null);
// Data
const { data: categoriesData, isLoading: catsLoading } = useCategories((isAdmin || isManager) && includeInactive);
const { data: rulesData, isLoading: rulesLoading } = useRules(
(isAdmin || isManager) && includeInactive ? { include_inactive: true } : undefined
);
// Mutations
const createCategoryMut = useCreateCategory();
const updateCategoryMut = useUpdateCategory();
const deleteCategoryMut = useDeleteCategory();
const createRuleMut = useCreateRule();
const updateRuleMut = useUpdateRule();
const deleteRuleMut = useDeleteRule();
const categories = categoriesData?.items ?? [];
const rules = rulesData?.items ?? [];
const isLoading = catsLoading || rulesLoading;
// ββ Toggle helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const toggleGroup = (g: string) => setExpandedGroups(prev => {
const s = new Set(prev); s.has(g) ? s.delete(g) : s.add(g); return s;
});
const toggleCategory = (c: string) => setExpandedCategories(prev => {
const s = new Set(prev); s.has(c) ? s.delete(c) : s.add(c); return s;
});
// ββ Filtering ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const q = search.toLowerCase();
// Fix 1: case-insensitive rule filtering
const filteredRules = rules.filter(r => {
const matchesSearch =
!q ||
r.name.toLowerCase().includes(q) ||
r.category.toLowerCase().includes(q) ||
r.keywords.some(kw => kw.toLowerCase().includes(q));
const matchesFilter = filterMatchOn === 'all' || r.match_on === filterMatchOn;
return matchesSearch && matchesFilter;
});
// Fix 2: include parent categories of matching rules
const matchingCatIds = new Set(filteredRules.map(r => r.category_id));
const filteredCats = categories.filter(c =>
!q ||
c.name.toLowerCase().includes(q) ||
(c.sheet_name ?? '').toLowerCase().includes(q) ||
matchingCatIds.has(c.id)
);
// Fix 3: pass correctly filtered data to groupBySheet
const { sheets, rulesByCat } = groupBySheet(
search ? filteredCats : categories,
search || filterMatchOn !== 'all' ? filteredRules : rules
);
// ββ Category handlers ββββββββββββββββββββββββββββββββββββββββββββββββββββ
const handleSaveCategory = async (id: string | null, data: { name: string; sheet_name: string; sub_column: string }) => {
try {
if (id) {
await updateCategoryMut.mutateAsync({ id, payload: { name: data.name, sheet_name: data.sheet_name || null, sub_column: data.sub_column || null } });
toast({ title: 'Category updated', variant: 'success' });
setEditingCategoryId(null);
} else {
await createCategoryMut.mutateAsync({ name: data.name, sheet_name: data.sheet_name || null, sub_column: data.sub_column || null });
toast({ title: 'Category created', variant: 'success' });
setAddingCategoryInSheet(null);
}
} catch (e: any) {
toast({ title: 'Error', description: e?.response?.data?.detail ?? String(e), variant: 'destructive' });
}
};
const handleToggleCategoryActive = async (cat: CategoryRecord) => {
try {
await updateCategoryMut.mutateAsync({ id: cat.id, payload: { is_active: !cat.is_active } });
toast({ title: `Category ${cat.is_active ? 'deactivated' : 'activated'}`, variant: 'success' });
} catch (e: any) {
toast({ title: 'Error', description: String(e), variant: 'destructive' });
}
};
const handleDeleteCategory = async (id: string) => {
try {
await deleteCategoryMut.mutateAsync(id);
toast({ title: 'Category deactivated', variant: 'success' });
setDeletingCategoryId(null);
} catch (e: any) {
toast({ title: 'Error', description: String(e), variant: 'destructive' });
}
};
// ββ Rule handlers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const handleSaveRule = async (
id: string | null,
data: Omit<RuleRecord, 'id' | 'created_at' | 'updated_at' | 'created_by' | 'updated_by' | 'category'>
) => {
try {
if (id) {
await updateRuleMut.mutateAsync({ id, payload: data });
toast({ title: 'Rule updated', variant: 'success' });
setEditingRuleId(null);
} else {
await createRuleMut.mutateAsync(data);
toast({ title: 'Rule created', variant: 'success' });
setAddingRuleInCategoryId(null);
}
} catch (e: any) {
toast({ title: 'Error', description: e?.response?.data?.detail ?? String(e), variant: 'destructive' });
}
};
const handleDeleteRule = async (id: string) => {
try {
await deleteRuleMut.mutateAsync(id);
toast({ title: 'Rule deleted', variant: 'success' });
setDeletingRuleId(null);
} catch (e: any) {
toast({ title: 'Error', description: String(e), variant: 'destructive' });
}
};
const isMutating =
createCategoryMut.isPending || updateCategoryMut.isPending ||
deleteCategoryMut.isPending || createRuleMut.isPending ||
updateRuleMut.isPending || deleteRuleMut.isPending;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center">
<div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={onClose} />
<div className="relative z-10 bg-white rounded-2xl shadow-2xl w-full max-w-3xl mx-4 max-h-[88vh] flex flex-col overflow-hidden">
{/* Header */}
<div className="flex items-start justify-between px-6 pt-6 pb-4 border-b border-gray-100 shrink-0">
<div>
<div className="flex items-center gap-2">
<h2 className="text-xl font-bold text-gray-900">Preset Classification Rules</h2>
{(isAdmin || isManager) && (
<span className="text-xs px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 font-medium">{isAdmin ? 'Admin' : 'Manager'}</span>
)}
</div>
<p className="text-sm text-gray-500 mt-0.5">
{categories.length} categories Β· {rules.length} rules Β· keyword-based auto-classification
</p>
</div>
<button onClick={onClose} className="p-2 rounded-lg hover:bg-gray-100 text-gray-400 hover:text-gray-700 transition-colors">
<X className="w-5 h-5" />
</button>
</div>
{/* Search + filter */}
<div className="px-6 py-3 border-b border-gray-100 flex gap-3 items-center shrink-0">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<input
type="text"
placeholder="Search rules, categories, or keywordsβ¦"
value={search}
onChange={e => setSearch(e.target.value)}
className="w-full pl-9 pr-3 py-2 text-sm border border-gray-200 rounded-lg bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
<div className="flex items-center gap-1.5 shrink-0">
<Filter className="w-4 h-4 text-gray-400" />
<select
value={filterMatchOn}
onChange={e => setFilterMatchOn(e.target.value as any)}
className="text-sm border border-gray-200 rounded-lg px-2 py-2 bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="all">All match types</option>
<option value="description">Description</option>
<option value="osko_reference">OSKO reference</option>
</select>
</div>
{(isAdmin || isManager) && (
<button
onClick={() => setIncludeInactive(v => !v)}
className={`flex items-center gap-1.5 text-xs px-2.5 py-2 rounded-lg border transition-colors ${includeInactive ? 'bg-gray-800 text-white border-gray-800' : 'bg-gray-50 text-gray-600 border-gray-200 hover:bg-gray-100'
}`}
>
{includeInactive ? <ToggleRight className="w-4 h-4" /> : <ToggleLeft className="w-4 h-4" />}
Inactive
</button>
)}
</div>
{/* Body */}
<div className="overflow-y-auto flex-1 px-6 py-4 space-y-3">
{isLoading && (
<div className="flex items-center justify-center py-12 gap-2 text-gray-400">
<Loader2 className="w-5 h-5 animate-spin" /> Loading rules from databaseβ¦
</div>
)}
{!isLoading && Object.entries(sheets).length === 0 && (
<div className="text-center py-12 text-gray-400 text-sm">No rules match your search.</div>
)}
{!isLoading && Object.entries(sheets).map(([sheetName, sheetCats]) => {
const colors = getColor(sheetName);
const totalRulesInSheet = sheetCats.reduce((sum, c) => sum + (rulesByCat[c.id]?.length ?? 0), 0);
const isGroupOpen = expandedGroups.has(sheetName) || !!search;
return (
<div key={sheetName} className={`rounded-xl border ${colors.border} overflow-hidden`}>
{/* Sheet header */}
<div className={`flex items-center justify-between px-4 py-3 ${colors.bg}`}>
<button
onClick={() => toggleGroup(sheetName)}
className="flex items-center gap-2.5 flex-1 text-left"
>
<span className={`w-2.5 h-2.5 rounded-full ${colors.dot}`} />
<span className={`font-semibold text-sm ${colors.text}`}>{sheetName === 'Excluded' ? 'Excluded (not on report)' : sheetName}</span>
<span className={`text-xs px-2 py-0.5 rounded-full bg-white/60 ${colors.text}`}>
{sheetCats.length} categories Β· {totalRulesInSheet} rules
</span>
</button>
<div className="flex items-center gap-1.5">
{(isAdmin || isManager) && (
<button
onClick={() => setAddingCategoryInSheet(addingCategoryInSheet === sheetName ? null : sheetName)}
className={`flex items-center gap-1 text-xs px-2 py-1 rounded ${colors.text} bg-white/60 hover:bg-white transition-colors`}
title="Add category to this sheet"
>
<Plus className="w-3.5 h-3.5" /> Category
</button>
)}
{isGroupOpen && !search
? <ChevronDown className={`w-4 h-4 ${colors.text}`} onClick={() => toggleGroup(sheetName)} />
: <ChevronRight className={`w-4 h-4 ${colors.text}`} onClick={() => toggleGroup(sheetName)} />}
</div>
</div>
{/* Add category form */}
{(isAdmin || isManager) && addingCategoryInSheet === sheetName && (
<div className="px-4 py-3 border-t border-gray-100 bg-gray-50">
<CategoryForm
initial={{ sheet_name: sheetName === 'Excluded' ? '' : sheetName }}
onSave={(data) => handleSaveCategory(null, data)}
onCancel={() => setAddingCategoryInSheet(null)}
isSaving={createCategoryMut.isPending}
/>
</div>
)}
{/* Categories */}
{(isGroupOpen || !!search) && (
<div className="divide-y divide-gray-100">
{sheetCats.map(cat => {
const catRules = rulesByCat[cat.id] ?? [];
const isCatOpen = expandedCategories.has(cat.id) || !!search;
return (
<div key={cat.id} className={!cat.is_active ? 'opacity-50' : ''}>
{/* Category row */}
{editingCategoryId === cat.id ? (
<div className="px-4 py-3 bg-white">
<CategoryForm
initial={cat}
onSave={(data) => handleSaveCategory(cat.id, data)}
onCancel={() => setEditingCategoryId(null)}
isSaving={updateCategoryMut.isPending}
/>
</div>
) : deletingCategoryId === cat.id ? (
<div className="px-4 py-3 bg-white">
<ConfirmDelete
label={cat.name}
onConfirm={() => handleDeleteCategory(cat.id)}
onCancel={() => setDeletingCategoryId(null)}
/>
</div>
) : (
<div className="flex items-center justify-between px-4 py-2.5 bg-white hover:bg-gray-50 transition-colors group">
<button
onClick={() => toggleCategory(cat.id)}
className="flex items-center gap-2 flex-1 text-left"
>
<Tag className="w-3.5 h-3.5 text-gray-400" />
<span className="text-sm font-medium text-gray-800">{cat.name}</span>
{!cat.is_active && <span className="text-xs px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">inactive</span>}
<span className="text-xs text-gray-400">{catRules.length} rule{catRules.length !== 1 ? 's' : ''}</span>
</button>
{(isAdmin || isManager) && (
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={() => { setAddingRuleInCategoryId(cat.id); setExpandedCategories(prev => new Set([...prev, cat.id])); }}
className="p-1 rounded hover:bg-blue-50 text-blue-500 hover:text-blue-700"
title="Add rule"
>
<Plus className="w-3.5 h-3.5" />
</button>
<button
onClick={() => setEditingCategoryId(cat.id)}
className="p-1 rounded hover:bg-gray-100 text-gray-400 hover:text-gray-700"
title="Edit category"
>
<Pencil className="w-3.5 h-3.5" />
</button>
{isAdmin && (
<>
<button
onClick={() => handleToggleCategoryActive(cat)}
className="p-1 rounded hover:bg-gray-100 text-gray-400 hover:text-gray-700"
title={cat.is_active ? 'Deactivate' : 'Activate'}
>
{cat.is_active ? <ToggleRight className="w-3.5 h-3.5 text-green-500" /> : <ToggleLeft className="w-3.5 h-3.5" />}
</button>
<button
onClick={() => setDeletingCategoryId(cat.id)}
className="p-1 rounded hover:bg-red-50 text-gray-400 hover:text-red-600"
title="Delete category"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</>
)}
</div>
)}
<button onClick={() => toggleCategory(cat.id)} className="ml-1">
{isCatOpen ? <ChevronDown className="w-3.5 h-3.5 text-gray-400" /> : <ChevronRight className="w-3.5 h-3.5 text-gray-400" />}
</button>
</div>
)}
{/* Rules */}
{(isCatOpen || !!search) && (
<div className="bg-gray-50 border-t border-gray-100 divide-y divide-gray-100">
{/* Add rule form */}
{(isAdmin || isManager) && addingRuleInCategoryId === cat.id && (
<div className="px-5 py-3">
<RuleForm
categories={categories}
defaultCategoryId={cat.id}
onSave={(data) => handleSaveRule(null, data)}
onCancel={() => setAddingRuleInCategoryId(null)}
isSaving={createRuleMut.isPending}
/>
</div>
)}
{catRules.length === 0 && addingRuleInCategoryId !== cat.id && (
<div className="px-5 py-3 text-xs text-gray-400 italic">No rules β {(isAdmin || isManager) ? 'click + to add one' : 'empty'}</div>
)}
{catRules.map(rule => (
<div key={rule.id} className="px-5 py-3">
{editingRuleId === rule.id ? (
<RuleForm
categories={categories}
initial={rule}
onSave={(data) => handleSaveRule(rule.id, data)}
onCancel={() => setEditingRuleId(null)}
isSaving={updateRuleMut.isPending}
/>
) : deletingRuleId === rule.id ? (
<ConfirmDelete
label={rule.name}
onConfirm={() => handleDeleteRule(rule.id)}
onCancel={() => setDeletingRuleId(null)}
/>
) : (
<div className={`group ${!rule.is_active ? 'opacity-50' : ''}`}>
<div className="flex items-center gap-2 flex-wrap mb-1.5">
<span className="text-xs font-mono text-gray-500 bg-gray-200 px-1.5 py-0.5 rounded">{rule.name}</span>
<span className="text-xs text-gray-400">
match on <span className="font-medium text-gray-600">{rule.match_on === 'osko_reference' ? 'OSKO ref' : 'description'}</span>
</span>
<span className="text-xs text-gray-400">
priority <span className="font-semibold text-gray-700">{rule.priority}</span>
</span>
{rule.tx_type_filter && (
<span className="text-xs px-1.5 py-0.5 rounded bg-amber-100 text-amber-700">{rule.tx_type_filter} only</span>
)}
{!rule.is_active && (
<span className="text-xs px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">inactive</span>
)}
{(isAdmin || isManager) && (
<div className="ml-auto flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={() => setEditingRuleId(rule.id)}
className="p-0.5 rounded hover:bg-gray-200 text-gray-400 hover:text-gray-700"
title="Edit rule"
>
<Pencil className="w-3.5 h-3.5" />
</button>
{isAdmin && (
<button
onClick={() => setDeletingRuleId(rule.id)}
className="p-0.5 rounded hover:bg-red-50 text-gray-400 hover:text-red-600"
title="Delete rule"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
)}
</div>
)}
</div>
<div className="flex flex-wrap gap-1.5">
{rule.keywords.map(kw => (
<span
key={kw}
className={`text-xs px-2 py-0.5 rounded-full border ${
// Fix 4: case-insensitive keyword highlight
q && kw.toLowerCase().includes(q)
? 'bg-blue-100 border-blue-300 text-blue-800 font-medium'
: 'bg-white border-gray-200 text-gray-600'
}`}
>
{kw}
</span>
))}
</div>
</div>
)}
</div>
))}
</div>
)}
</div>
);
})}
</div>
)}
</div>
);
})}
</div>
{/* Footer */}
<div className="px-6 py-3 border-t border-gray-100 shrink-0 flex items-center justify-between bg-gray-50">
<p className="text-xs text-gray-400">
Rules run before AI suggestions Β· Higher priority wins Β· Changes apply on next classify run
</p>
<button
onClick={onClose}
className="text-sm font-medium text-gray-600 hover:text-gray-900 px-3 py-1.5 rounded-lg hover:bg-gray-200 transition-colors"
>
Close
</button>
</div>
</div>
</div>
);
}
// βββ Main Feature βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function ClassifyFeatureInner() {
const params = useParams();
const statementId = params.statementId as string;
const router = useRouter();
const { toast, dismiss } = useToast();
const { user } = useAuthStore();
const isAdmin = user?.role === 'admin';
const isManager = user?.role === 'manager';
const { data: statusData, isLoading: statusLoading } = useClassifyStatus(statementId);
const { data: transactionsData, isLoading: txLoading, refetch: refetchTransactions } = useTransactions(statementId, {
pageSize: 10000,
});
const exportMutation = useGenerateExport(statementId);
const verifySelectedMutation = useConfirmClassifySuggestionsBulk(statementId);
const confirmSingleMutation = useConfirmClassifySuggestion(statementId);
const [selectedTxIds, setSelectedTxIds] = useState<string[]>([]);
const [pendingVerifyTxId, setPendingVerifyTxId] = useState<string | null>(null);
const [pendingBulkVerifyIds, setPendingBulkVerifyIds] = useState<Set<string>>(new Set());
const pendingVerifyIds = useMemo(() => {
const ids = new Set(pendingBulkVerifyIds);
if (pendingVerifyTxId) ids.add(pendingVerifyTxId);
return ids;
}, [pendingBulkVerifyIds, pendingVerifyTxId]);
const [isExporting, setIsExporting] = useState(false);
const [showPresetRules, setShowPresetRules] = useState(false);
// HITL Verification & Pill Filtering states
const [filter, setFilter] = useState<'all' | 'unverified' | 'ai' | 'rule' | 'manual'>('all');
const [confidenceFilter, setConfidenceFilter] = useState<'All' | 'Low' | 'Medium' | 'High'>('All');
const [tableSearch, setTableSearch] = useState('');
const handleVerifySingle = useCallback(
(txId: string) => {
setPendingVerifyTxId(txId);
const loadingId = toast({
title: 'Verifying suggestionβ¦',
description: 'Sent for verification β please wait while we confirm this.',
variant: 'loading',
duration: Infinity,
});
confirmSingleMutation.mutate(txId, {
onSuccess: () => {
dismiss(loadingId);
toast({ title: 'Transaction verified', variant: 'success' });
},
onError: (e: any) => {
dismiss(loadingId);
toast({
title: 'Verification failed',
description: e?.response?.data?.detail ?? 'Please try again.',
variant: 'destructive',
});
},
onSettled: () => setPendingVerifyTxId(null),
});
},
[confirmSingleMutation, toast, dismiss]
);
const classificationCandidates = useMemo(() => {
if (!transactionsData?.items) return [];
return transactionsData.items.filter((t) => t.selectedForClassification !== false);
}, [transactionsData?.items]);
const runBulkVerify = useCallback(
(ids: string[]) => {
if (ids.length === 0) return;
setPendingBulkVerifyIds(new Set(ids));
const loadingId = toast({
title: `Verifying ${ids.length} transaction${ids.length > 1 ? 's' : ''}β¦`,
description: 'Sent for verification β please wait while we confirm these.',
variant: 'loading',
duration: Infinity,
});
verifySelectedMutation.mutate(ids, {
onSuccess: (data: { count?: number } | null) => {
dismiss(loadingId);
toast({
title: `${data?.count ?? ids.length} transaction(s) verified`,
variant: 'success',
});
setSelectedTxIds([]);
},
onError: (e: any) => {
dismiss(loadingId);
toast({
title: 'Bulk verification failed',
description: e?.response?.data?.detail ?? 'Please try again.',
variant: 'destructive',
});
},
onSettled: () => setPendingBulkVerifyIds(new Set()),
});
},
[verifySelectedMutation, toast, dismiss]
);
const handleVerifyAllUnverified = useCallback(() => {
const unverifiedIds = classificationCandidates
.filter((t) => (t.categorySource?.startsWith('ml') || t.categorySource?.startsWith('llm')) && !t.verified)
.map((t) => t.id);
runBulkVerify(unverifiedIds);
}, [classificationCandidates, runBulkVerify]);
const unverifiedCount = useMemo(() => {
if (!classificationCandidates) return 0;
return classificationCandidates.filter(
(t) => (t.categorySource?.startsWith('ml') || t.categorySource?.startsWith('llm')) && !t.verified
).length;
}, [classificationCandidates]);
const aiCount = useMemo(() => {
if (!classificationCandidates) return 0;
return classificationCandidates.filter(
(t) => t.categorySource?.startsWith('ml') || t.categorySource?.startsWith('llm')
).length;
}, [classificationCandidates]);
const ruleCount = useMemo(() => {
if (!classificationCandidates) return 0;
return classificationCandidates.filter((t) => t.categorySource?.startsWith('rule')).length;
}, [classificationCandidates]);
const manualCount = useMemo(() => {
if (!classificationCandidates) return 0;
return classificationCandidates.filter(
(t) => t.categorySource === 'manual' || t.categoryConfidence === 'manual'
).length;
}, [classificationCandidates]);
const filteredTransactions = useMemo(() => {
if (!classificationCandidates) return [];
let txs = classificationCandidates;
if (filter === 'unverified') {
txs = txs.filter((t) => (t.categorySource?.startsWith('ml') || t.categorySource?.startsWith('llm')) && !t.verified);
} else if (filter === 'ai') {
txs = txs.filter((t) => t.categorySource?.startsWith('ml') || t.categorySource?.startsWith('llm'));
} else if (filter === 'rule') {
txs = txs.filter((t) => t.categorySource?.startsWith('rule'));
} else if (filter === 'manual') {
txs = txs.filter((t) => t.categorySource === 'manual' || t.categoryConfidence === 'manual');
}
if (filter === 'unverified' && confidenceFilter !== 'All') {
txs = txs.filter((t) => {
const rawSrc = t.categorySource || '';
const src = rawSrc ? rawSrc.split(':')[0] : '';
if (src === 'ml' || src === 'llm') {
const conf = typeof t.categoryConfidence === 'number' ? t.categoryConfidence : parseFloat(String(t.categoryConfidence || 'NaN'));
if (Number.isFinite(conf)) {
const pct = Math.round(conf * 100);
if (confidenceFilter === 'Low') return pct < 40;
if (confidenceFilter === 'Medium') return pct >= 40 && pct <= 80;
if (confidenceFilter === 'High') return pct > 80;
}
}
return false;
});
}
// Text search β applied last, after all other filters
if (tableSearch.trim()) {
const q = tableSearch.toLowerCase();
txs = txs.filter((t) =>
t.description?.toLowerCase().includes(q) ||
t.category?.toLowerCase().includes(q) ||
t.date?.toLowerCase().includes(q)
);
}
return txs;
}, [classificationCandidates, filter, confidenceFilter, tableSearch]);
useEffect(() => {
if (statusData?.status === 'completed') {
refetchTransactions();
}
}, [statusData?.status, refetchTransactions]);
if (statusLoading || txLoading) {
return <LoadingState message="Loading classification data..." fullPage />;
}
if (!statusData || !transactionsData) {
return <ErrorState title="Failed to load classification data" />;
}
if (statusData.status === 'classifying') {
return (
<LoadingState
message={`Running Classification Pipeline... (${statusData.classified}/${statusData.total} transactions classified)`}
fullPage
/>
);
}
const handleProceedToExport = () => {
if (unverifiedCount > 0) {
const shouldContinue = window.confirm(
`There are ${unverifiedCount} unverified AI suggestions. Please verify them before exporting.\n\nDo you want to continue to the export step anyway?`
);
if (!shouldContinue) {
toast({
title: 'Export paused',
description: 'Verify pending AI suggestions before exporting.',
variant: 'destructive',
});
return;
}
}
router.push(`/export/${statementId}`);
};
return (
<div className="h-full flex flex-col bg-gray-50 overflow-hidden relative">
{showPresetRules && (
<PresetRulesModal onClose={() => setShowPresetRules(false)} isAdmin={isAdmin} isManager={isManager} />
)}
{/* Summary Cards */}
<div className="px-4 py-3 grid grid-cols-4 gap-3 shrink-0">
{/* Total / Classified */}
<div className="bg-white p-3 rounded-xl border border-gray-200 shadow-sm flex items-center justify-between relative">
<div className="flex flex-col text-left">
<p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Total / Classified</p>
<p className="text-xl font-bold text-slate-800 mt-1">
{statusData.total} / {statusData.classified}
</p>
<span className="text-[10px] text-slate-400 mt-0.5 font-medium">
{statusData.total > 0 && Math.round((statusData.classified / statusData.total) * 100)}% classified
</span>
</div>
<div className="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center shrink-0 shadow-sm">
<FileText className="w-5 h-5" />
</div>
</div>
{/* Preset Rules */}
<div className="bg-white p-3 rounded-xl border border-gray-200 shadow-sm flex items-center justify-between relative">
<div className="flex flex-col text-left">
<div className="flex items-center gap-1">
<p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Rule-Based</p>
{(isAdmin || isManager) && (
<span className="text-[8px] px-1 py-0.2 rounded bg-slate-100 text-slate-600 font-bold uppercase tracking-wide leading-none">{isAdmin ? 'Admin' : 'Manager'}</span>
)}
</div>
<p className="text-xl font-bold text-slate-800 mt-1">
{statusData.breakdown.rule || 0}
</p>
<button
onClick={() => setShowPresetRules(true)}
className="text-[10px] font-bold text-blue-600 hover:text-blue-800 mt-1 transition-colors flex items-center gap-0.5 cursor-pointer hover:underline"
>
{(isAdmin || isManager) ? 'View & edit rules' : 'View rules'}
<ChevronRight className="w-3.5 h-3.5" />
</button>
</div>
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0 shadow-sm">
<Sliders className="w-5 h-5" />
</div>
</div>
{/* AI Suggestions */}
<div className="bg-white p-3 rounded-xl border border-gray-200 shadow-sm flex items-center justify-between relative">
<div className="flex flex-col text-left">
<p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">AI Suggestions</p>
<p className="text-xl font-bold text-slate-800 mt-1">
{(statusData.breakdown.ml || 0) + (statusData.breakdown.llm || 0)}
</p>
{unverifiedCount > 0 && (
<span className="text-[9px] font-bold bg-purple-50 text-purple-600 px-2 py-0.5 rounded-full border border-purple-100 inline-block w-fit mt-1">
{unverifiedCount} require verification
</span>
)}
</div>
<div className="w-10 h-10 rounded-xl bg-purple-50 text-purple-600 flex items-center justify-center shrink-0 shadow-sm">
<Sparkles className="w-5 h-5" />
</div>
</div>
{/* Edited Manually */}
<div className="bg-white p-3 rounded-xl border border-gray-200 shadow-sm flex items-center justify-between relative">
<div className="flex flex-col text-left">
<p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Edited</p>
<p className="text-xl font-bold text-slate-800 mt-1">
{statusData.breakdown.manual || 0}
</p>
</div>
<div className="w-10 h-10 rounded-xl bg-teal-50 text-teal-600 flex items-center justify-center shrink-0 shadow-sm">
<CheckCircle2 className="w-5 h-5" />
</div>
</div>
</div>
{/* Warning Banner for HITL */}
{unverifiedCount > 0 && (
<div className="mx-4 mb-3 px-4 py-2.5 bg-amber-50 border border-amber-200 rounded-xl flex items-center justify-between shadow-sm shrink-0 gap-4 animate-in fade-in slide-in-from-top-2 duration-300">
<div className="flex items-center gap-3 min-w-0">
<AlertTriangle className="w-4 h-4 text-amber-600 shrink-0" />
<div className="flex items-center gap-2 text-xs text-amber-900 min-w-0 flex-wrap">
<span className="font-bold shrink-0">Human-in-the-Loop Verification Required</span>
<span className="text-amber-300 shrink-0 select-none">|</span>
<span className="truncate">
{selectedTxIds.length > 0 ? (
<strong className="font-semibold text-amber-700">{selectedTxIds.length} selected for bulk verify</strong>
) : (
`${unverifiedCount} AI suggested classifications pending human review.`
)}
</span>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
onClick={() => runBulkVerify(selectedTxIds)}
disabled={verifySelectedMutation.isPending || selectedTxIds.length === 0}
className="h-8 text-xs font-semibold px-3 py-0 bg-white hover:bg-slate-50 text-slate-800 border-slate-200 shadow-sm shrink-0 cursor-pointer"
>
{verifySelectedMutation.isPending ? (
<span className="inline-flex items-center gap-1.5">
<Loader2 className="w-3.5 h-3.5 animate-spin" />
Verifying...
</span>
) : (
'Verify Selected'
)}
</Button>
{/* <Button
variant="secondary"
onClick={handleVerifyAllUnverified}
disabled={verifySelectedMutation.isPending || unverifiedCount === 0}
className="h-8 text-xs font-semibold px-3 py-0 bg-slate-100 hover:bg-slate-200 text-slate-800 border-slate-200 shadow-sm shrink-0 cursor-pointer"
>
{verifySelectedMutation.isPending ? (
<span className="inline-flex items-center gap-1.5">
<Loader2 className="w-3.5 h-3.5 animate-spin" />
Verifying...
</span>
) : (
'Verify all unverified'
)}
</Button> */}
</div>
</div>
)}
{/* Main Table Container */}
<div className="flex-1 px-4 pb-4 overflow-hidden flex flex-col">
<div className="bg-white border border-gray-200 rounded-xl shadow-sm flex-1 overflow-hidden flex flex-col">
{/* Filter tab bar */}
<div className="px-4 border-b border-gray-200 shrink-0 bg-white">
<div className="flex items-center justify-between">
{/* Tab buttons */}
<div className="flex items-center gap-0">
{/* All */}
<button
onClick={() => { setFilter('all'); setConfidenceFilter('All'); }}
className={`relative flex items-center gap-1.5 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap cursor-pointer ${
filter === 'all'
? 'text-blue-600 after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-blue-600'
: 'text-slate-500 hover:text-slate-800'
}`}
>
All
<span className={`inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded-full text-xs font-bold ${
filter === 'all' ? 'bg-blue-100 text-blue-700' : 'bg-slate-100 text-slate-600'
}`}>
{classificationCandidates.length}
</span>
</button>
{/* Needs review */}
<button
onClick={() => setFilter('unverified')}
className={`relative flex items-center gap-1.5 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap cursor-pointer ${
filter === 'unverified'
? 'text-amber-600 after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-amber-500'
: 'text-slate-500 hover:text-slate-800'
}`}
>
Needs review
{unverifiedCount > 0 ? (
<span className={`inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded-full text-xs font-bold ${
filter === 'unverified' ? 'bg-amber-100 text-amber-700' : 'bg-amber-400 text-white'
}`}>
{unverifiedCount}
</span>
) : (
<span className="inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded-full text-xs font-bold bg-slate-100 text-slate-500">
0
</span>
)}
</button>
{/* Confidence sub-filter β only visible when Needs review is active */}
{filter === 'unverified' && (
<select
value={confidenceFilter}
onChange={(e) => setConfidenceFilter(e.target.value as any)}
className="my-2 h-7 text-xs font-semibold bg-white text-slate-700 border border-slate-200 rounded-lg pl-2.5 pr-7 focus:outline-none focus:ring-1 focus:ring-amber-500 shadow-sm appearance-none cursor-pointer"
style={{
backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23334155' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 9 12 15 18 9'></polyline></svg>")`,
backgroundRepeat: 'no-repeat',
backgroundPosition: 'right 6px center',
backgroundSize: '12px',
}}
>
<option value="All">All Confidence</option>
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
)}
{/* AI suggested */}
<button
onClick={() => { setFilter('ai'); setConfidenceFilter('All'); }}
className={`relative flex items-center gap-1.5 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap cursor-pointer ${
filter === 'ai'
? 'text-purple-600 after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-purple-600'
: 'text-slate-500 hover:text-slate-800'
}`}
>
AI suggested
<span className={`inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded-full text-xs font-bold ${
filter === 'ai' ? 'bg-purple-100 text-purple-700' : 'bg-slate-100 text-slate-600'
}`}>
{aiCount}
</span>
</button>
{/* Rule-based */}
<button
onClick={() => { setFilter('rule'); setConfidenceFilter('All'); }}
className={`relative flex items-center gap-1.5 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap cursor-pointer ${
filter === 'rule'
? 'text-blue-600 after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-blue-600'
: 'text-slate-500 hover:text-slate-800'
}`}
>
Rule-based
<span className={`inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded-full text-xs font-bold ${
filter === 'rule' ? 'bg-blue-100 text-blue-700' : 'bg-slate-100 text-slate-600'
}`}>
{ruleCount}
</span>
</button>
{/* Edited */}
<button
onClick={() => { setFilter('manual'); setConfidenceFilter('All'); }}
className={`relative flex items-center gap-1.5 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap cursor-pointer ${
filter === 'manual'
? 'text-emerald-600 after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-emerald-600'
: 'text-slate-500 hover:text-slate-800'
}`}
>
Edited
<span className={`inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded-full text-xs font-bold ${
filter === 'manual' ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-600'
}`}>
{manualCount}
</span>
</button>
</div>
{/* Search β far right */}
<div className="relative flex items-center py-2">
<Search className="absolute left-2.5 w-3.5 h-3.5 text-slate-400 pointer-events-none" />
<input
type="text"
value={tableSearch}
onChange={(e) => setTableSearch(e.target.value)}
placeholder="Search..."
className="h-8 pl-8 pr-8 text-sm rounded-lg border border-slate-200 bg-white text-slate-700 focus:outline-none focus:ring-1 focus:ring-blue-400 placeholder:text-slate-400 w-44"
/>
{tableSearch && (
<button
onClick={() => setTableSearch('')}
className="absolute right-2 text-slate-400 hover:text-slate-600"
aria-label="Clear search"
>
<X className="w-3.5 h-3.5" />
</button>
)}
</div>
</div>
</div>
<ClassificationTable
statementId={statementId}
transactions={filteredTransactions}
selectedIds={selectedTxIds}
onSelectionChange={setSelectedTxIds}
onVerify={handleVerifySingle}
pendingVerifyIds={pendingVerifyIds}
/>
</div>
</div>
{/* Footer bar β "Showing X of Y" left, "Proceed to export" right */}
<div className="shrink-0 bg-white border-t border-gray-200 px-6 py-3 flex items-center justify-between">
<span className="text-sm text-slate-500">
Showing {filteredTransactions.length} of {classificationCandidates.length} transactions
</span>
<Button
onClick={handleProceedToExport}
variant="outline"
className="flex items-center gap-2 text-sm font-medium text-slate-700 border-slate-300 hover:bg-slate-50 cursor-pointer"
>
Proceed to export
<ArrowRight className="w-4 h-4" />
</Button>
</div>
</div>
);
}
export function ClassifyFeature() {
return (
<Suspense fallback={<LoadingState message="Initializing classification..." fullPage />}>
<ClassifyFeatureInner />
</Suspense>
);
}
'use client';
import { Suspense, useState, useEffect, useCallback, useMemo } from 'react';
import { useParams, useRouter } from 'next/navigation';
import {
useTransactions,
useClassifyStatus,
useGenerateExport,
useCategories,
useRules,
useCreateCategory,
useUpdateCategory,
useDeleteCategory,
useCreateRule,
useUpdateRule,
useDeleteRule,
useConfirmClassifySuggestion,
useConfirmClassifySuggestionsBulk,
} from '@/hooks/useStatementAPI';
import { ClassificationTable } from '@/components/tables/ClassificationTable';
import { LoadingState, ErrorState } from '@/components/shared';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import { normalizeDownloadUrl } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import type { CategoryRecord, RuleRecord } from '@/services/api-client';
import {
X,
Search,
ChevronDown,
ChevronRight,
Tag,
Filter,
Plus,
Pencil,
Trash2,
Save,
XCircle,
Loader2,
AlertTriangle,
ToggleLeft,
ToggleRight,
Lock,
FileDown,
ArrowRight,
Check,
FileText,
Sliders,
Sparkles,
CheckCircle2,
} from 'lucide-react';
// βββ Colour map for sheet groups ββββββββββββββββββββββββββββββββββββββββββββββ
export const SHEET_COLORS: Record<string, { bg: string; text: string; border: string; dot: string; badge: string }> = {
'Food and Groceries': {
bg: 'bg-orange-50', text: 'text-orange-700',
border: 'border-orange-200', dot: 'bg-orange-400',
badge: 'bg-orange-100 text-orange-700',
},
'Recreation & Entertainment': {
bg: 'bg-rose-50', text: 'text-rose-700',
border: 'border-rose-200', dot: 'bg-rose-400',
badge: 'bg-rose-100 text-rose-700',
},
'Clothing & Personal Care': {
bg: 'bg-pink-50', text: 'text-pink-700',
border: 'border-pink-200', dot: 'bg-pink-400',
badge: 'bg-pink-100 text-pink-700',
},
'Transport & Auto': {
bg: 'bg-sky-50', text: 'text-sky-700',
border: 'border-sky-200', dot: 'bg-sky-400',
badge: 'bg-sky-100 text-sky-700',
},
'Owner Occupied Property Expense': {
bg: 'bg-yellow-50', text: 'text-yellow-700',
border: 'border-yellow-200', dot: 'bg-yellow-400',
badge: 'bg-yellow-100 text-yellow-700',
},
'Telephone & Internet': {
bg: 'bg-violet-50', text: 'text-violet-700',
border: 'border-violet-200', dot: 'bg-violet-400',
badge: 'bg-violet-100 text-violet-700',
},
'Medical, Health & Fitness': {
bg: 'bg-green-50', text: 'text-green-700',
border: 'border-green-200', dot: 'bg-green-400',
badge: 'bg-green-100 text-green-700',
},
'Miscellaneous': {
bg: 'bg-indigo-50', text: 'text-indigo-700',
border: 'border-indigo-200', dot: 'bg-indigo-400',
badge: 'bg-indigo-100 text-indigo-700',
},
'Public Education': {
bg: 'bg-teal-50', text: 'text-teal-700',
border: 'border-teal-200', dot: 'bg-teal-500',
badge: 'bg-teal-100 text-teal-700',
},