import React, { useState, useEffect, useMemo, useRef } from 'react';
import { toast } from 'sonner';
import {
Sparkles, CheckCircle2, Loader2, RefreshCw, Link2, Link2Off,
XCircle, Eye, EyeOff, Search, Clock, ChevronLeft, ChevronRight,
ArrowUp, ArrowDown, ArrowUpDown,
} from 'lucide-react';
import { api } from '@/api';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { SectionCard } from './dataShared';
import BillModal from '@/components/BillModal';
import {
MatchBillDialog,
transactionTitle,
transactionDate,
formatTransactionAmount,
} from '@/components/transactions/MatchBillDialog';
const TRANSACTION_FILTERS = [
{ id: 'open', label: 'Open', params: { ignored: 'false' } },
{ id: 'unmatched', label: 'Unmatched', params: { match_status: 'unmatched', ignored: 'false' } },
{ id: 'matched', label: 'Matched', params: { match_status: 'matched', ignored: 'false' } },
{ id: 'ignored', label: 'Ignored', params: { match_status: 'ignored', ignored: 'true' } },
{ id: 'all', label: 'All', params: { ignored: 'all' } },
];
function transactionStatus(tx) {
if (tx?.ignored) return 'ignored';
return tx?.match_status || 'unmatched';
}
function TransactionStatusBadge({ tx }) {
const status = transactionStatus(tx);
const styles = {
matched: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600',
ignored: 'border-muted-foreground/30 bg-muted/40 text-muted-foreground',
unmatched: 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
};
return (
{status}
);
}
function matchScoreTone(score) {
const value = Number(score) || 0;
if (value >= 80) return 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400';
if (value >= 55) return 'border-sky-500/30 bg-sky-500/10 text-sky-600 dark:text-sky-400';
return 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400';
}
function SuggestedMatchesPanel({ suggestions, loading, actionId, onAccept, onReject }) {
return (
Suggested matches
{loading ? 'Checking transactions' : `${suggestions.length} ready for review`}
{loading ? (
Finding likely bill matches...
) : suggestions.length === 0 ? (
No suggested matches right now.
) : (
{suggestions.map(suggestion => {
const tx = suggestion.transaction || {};
const bill = suggestion.bill || {};
const acceptBusy = actionId === `suggestion-match:${suggestion.id}`;
const rejectBusy = actionId === `suggestion-reject:${suggestion.id}`;
const busy = acceptBusy || rejectBusy;
return (
{suggestion.score}
{transactionTitle(tx)}
{transactionDate(tx)} · {tx.source_label || tx.source_type_label || 'Transaction'}
{formatTransactionAmount(tx.amount, tx.currency)}
{bill.name || `Bill ${suggestion.billId}`}
Expected ${Number(bill.expected_amount || 0).toFixed(2)}
{suggestion.reasons?.length > 0 && (
{suggestion.reasons.slice(0, 4).map(reason => (
{reason}
))}
)}
);
})}
)}
);
}
function parseUtc(str) {
if (!str) return null;
const normalized = str.includes('T') ? str : str.replace(' ', 'T') + 'Z';
return new Date(normalized);
}
function timeAgo(iso) {
if (!iso) return null;
const secs = Math.floor((Date.now() - parseUtc(iso).getTime()) / 1000);
if (secs < 60) return 'just now';
if (secs < 3600) return `${Math.floor(secs / 60)}m ago`;
if (secs < 86400) return `${Math.floor(secs / 3600)}h ago`;
return `${Math.floor(secs / 86400)}d ago`;
}
export default function TransactionMatchingSection({ refreshKey, simplefinConn, cardProps = {} }) {
const [transactions, setTransactions] = useState([]);
const [suggestions, setSuggestions] = useState([]);
const [bills, setBills] = useState([]);
const [filter, setFilter] = useState('open');
const [loading, setLoading] = useState(true);
const [suggestionsLoading, setSuggestionsLoading] = useState(true);
const [billsLoading, setBillsLoading] = useState(true);
const [actionId, setActionId] = useState(null);
const [matchOpen, setMatchOpen] = useState(false);
const [matchTransaction, setMatchTransaction] = useState(null);
const [categories, setCategories] = useState([]);
const [createBillSourceTx, setCreateBillSourceTx] = useState(null);
const [page, setPage] = useState(1);
const [totalCount, setTotalCount] = useState(0);
const [search, setSearch] = useState('');
const [sortBy, setSortBy] = useState('date');
const [sortDir, setSortDir] = useState('desc');
const searchTimerRef = useRef(null);
const PAGE_SIZE = 10;
const totalPages = Math.ceil(totalCount / PAGE_SIZE) || 1;
const currentFilter = TRANSACTION_FILTERS.find(item => item.id === filter) || TRANSACTION_FILTERS[0];
const loadTransactions = async (pageNum, searchOverride, sortByOverride, sortDirOverride) => {
const p = pageNum ?? page;
const q = searchOverride !== undefined ? searchOverride : search;
const sb = sortByOverride !== undefined ? sortByOverride : sortBy;
const sd = sortDirOverride !== undefined ? sortDirOverride : sortDir;
setLoading(true);
try {
const params = { limit: PAGE_SIZE, offset: (p - 1) * PAGE_SIZE, sort_by: sb, sort_dir: sd, ...currentFilter.params };
if (q) params.q = q;
const resp = await api.transactions(params);
setTransactions(resp.transactions || []);
setTotalCount(resp.total || 0);
} catch (err) {
toast.error(err.message || 'Failed to load transactions.');
setTransactions([]);
} finally {
setLoading(false);
}
};
const loadSuggestions = async () => {
setSuggestionsLoading(true);
try {
const data = await api.matchSuggestions({ limit: 8 });
setSuggestions(data || []);
} catch (err) {
toast.error(err.message || 'Failed to load match suggestions.');
setSuggestions([]);
} finally {
setSuggestionsLoading(false);
}
};
const refreshTransactionWorkbench = async () => {
await Promise.all([loadTransactions(), loadSuggestions()]);
};
const loadBills = async () => {
setBillsLoading(true);
try {
const data = await api.bills();
setBills(data || []);
} catch (err) {
setBills([]);
toast.error(err.message || 'Failed to load bills for matching.');
} finally {
setBillsLoading(false);
}
};
useEffect(() => { loadBills(); }, []);
useEffect(() => { setSearch(''); setPage(1); loadTransactions(1, ''); }, [filter, refreshKey]);
useEffect(() => { loadSuggestions(); }, [refreshKey]);
useEffect(() => {
api.categories().then(data => setCategories(data || [])).catch(err => console.error('[TransactionMatchingSection] failed to load categories', err));
}, []);
const changePage = (newPage) => {
setPage(newPage);
loadTransactions(newPage);
};
const handleSearchChange = (e) => {
const value = e.target.value;
setSearch(value);
clearTimeout(searchTimerRef.current);
searchTimerRef.current = setTimeout(() => {
setPage(1);
loadTransactions(1, value);
}, 300);
};
const handleSortClick = (column) => {
const newDir = sortBy === column && sortDir === 'desc' ? 'asc' : 'desc';
setSortBy(column);
setSortDir(newDir);
setPage(1);
loadTransactions(1, undefined, column, newDir);
};
const openMatchDialog = (tx) => {
setMatchTransaction(tx);
setMatchOpen(true);
if (!bills.length && !billsLoading) loadBills();
};
const openCreateBill = (tx, nameOverride) => {
const amount = Math.abs(Number(tx.amount || 0)) / 100;
const dateStr = transactionDate(tx);
const day = dateStr ? parseInt(dateStr.slice(8, 10), 10) : 1;
setCreateBillSourceTx({
tx,
initialBill: {
name: nameOverride || transactionTitle(tx),
expected_amount: amount || 0,
due_day: day >= 1 && day <= 31 ? day : 1,
billing_cycle: 'monthly',
cycle_type: 'monthly',
cycle_day: '1',
active: 1,
},
});
};
const handleBillCreated = async (newBill) => {
const tx = createBillSourceTx?.tx;
setCreateBillSourceTx(null);
if (tx && newBill?.id) {
try {
await api.matchTransaction(tx.id, newBill.id);
toast.success('Bill created and matched to transaction.');
} catch (err) {
toast.error(err.message || 'Bill created but match failed.');
}
}
await Promise.all([loadBills(), refreshTransactionWorkbench()]);
};
const runTransactionAction = async (tx, action) => {
setActionId(`${action}:${tx.id}`);
try {
if (action === 'unmatch') {
await api.unmatchTransaction(tx.id);
toast.success('Transaction unmatched.');
} else if (action === 'ignore') {
await api.ignoreTransaction(tx.id);
toast.success('Transaction ignored.');
} else if (action === 'unignore') {
await api.unignoreTransaction(tx.id);
toast.success('Transaction restored.');
}
await refreshTransactionWorkbench();
} catch (err) {
toast.error(err.message || 'Transaction action failed.');
} finally {
setActionId(null);
}
};
const confirmMatch = async (billId) => {
if (!matchTransaction) return;
setActionId(`match:${matchTransaction.id}`);
try {
await api.matchTransaction(matchTransaction.id, billId);
toast.success('Transaction matched to bill.');
setMatchOpen(false);
setMatchTransaction(null);
await refreshTransactionWorkbench();
} catch (err) {
toast.error(err.message || 'Transaction match failed.');
} finally {
setActionId(null);
}
};
const acceptSuggestion = async (suggestion) => {
setActionId(`suggestion-match:${suggestion.id}`);
try {
await api.matchTransaction(suggestion.transactionId, suggestion.billId);
toast.success('Suggested match confirmed.');
await refreshTransactionWorkbench();
} catch (err) {
toast.error(err.message || 'Suggested match failed.');
} finally {
setActionId(null);
}
};
const rejectSuggestion = async (suggestion) => {
setActionId(`suggestion-reject:${suggestion.id}`);
try {
await api.rejectMatchSuggestion(suggestion.id);
toast.success('Suggestion rejected.');
await loadSuggestions();
} catch (err) {
toast.error(err.message || 'Suggestion could not be rejected.');
} finally {
setActionId(null);
}
};
const [quickSyncing, setQuickSyncing] = useState(false);
const handleQuickSync = async () => {
if (!simplefinConn) return;
setQuickSyncing(true);
try {
await api.syncDataSource(simplefinConn.id);
await refreshTransactionWorkbench();
} catch (err) {
toast.error(err.message || 'Sync failed');
} finally {
setQuickSyncing(false);
}
};
return (
{simplefinConn && (
SimpleFIN
{simplefinConn.last_sync_at && (
· synced {timeAgo(simplefinConn.last_sync_at)}
)}
{simplefinConn.last_error && (
· {simplefinConn.last_error}
)}
)}
{TRANSACTION_FILTERS.map(item => (
))}
{loading ? (
Loading transactions…
) : transactions.length === 0 ? (
No transactions found for this filter.
) : (
| handleSortClick('date')}
>
Date
{sortBy === 'date'
? sortDir === 'desc'
?
:
: }
|
Transaction |
Match |
handleSortClick('amount')}
>
{sortBy === 'amount'
? sortDir === 'desc'
?
:
: }
Amount
|
Actions |
{transactions.map(tx => {
const status = transactionStatus(tx);
const busy = actionId?.endsWith(`:${tx.id}`);
return (
|
{transactionDate(tx)}
|
{transactionTitle(tx)}
{[tx.description, tx.account_name, tx.source_label].filter(Boolean).join(' · ') || '—'}
|
{tx.pending ? (
Pending
) : null}
{tx.matched_bill_name ? (
{tx.matched_bill_name}
) : tx.advisory_filter?.confidence === 'high' ? (
Probably not a bill
) : (
No bill linked
)}
|
{formatTransactionAmount(tx.amount, tx.currency)}
|
{status === 'ignored' ? (
) : (
<>
{status === 'matched' ? (
) : (
)}
>
)}
|
);
})}
)}
{totalCount > 0 && (
{totalCount} transaction{totalCount !== 1 ? 's' : ''}
{totalPages > 1 && (
Page {page} of {totalPages}
)}
)}
{createBillSourceTx && (
setCreateBillSourceTx(null)}
onSave={handleBillCreated}
/>
)}
);
}