import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { toast } from 'sonner'; import { Bell, CalendarDays, CheckCircle2, CheckCircle, Cloud, ArrowDown, ArrowUp, GripVertical, Link2, Loader2, Pause, Plus, RefreshCw, Repeat, Search, Sparkles, X, } from 'lucide-react'; import { api } from '@/api'; import { cn, fmt, fmtDate } from '@/lib/utils'; import { scheduleLabel } from '@/lib/billingSchedule'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Input } from '@/components/ui/input'; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, } from '@/components/ui/dialog'; import BillModal from '@/components/BillModal'; import { moveInArray, movedItemId, reorderPayload } from '@/lib/reorder'; const TYPE_LABELS = { streaming: 'Streaming', software: 'Software', cloud: 'Cloud', music: 'Music', news: 'News', fitness: 'Fitness', gaming: 'Gaming', utilities: 'Utilities', insurance: 'Insurance', food: 'Food', education: 'Education', shopping: 'Shopping', security: 'Security', other: 'Other', }; function cycleLabel(item) { return scheduleLabel(item); } function StatCard({ icon: Icon, label, value, hint }) { return (
{label}

{value}

{hint &&

{hint}

}
); } function SubscriptionRow({ item, onEdit, onToggle, moveControls, dragProps }) { return (
{TYPE_LABELS[item.subscription_type] || 'Other'} {!item.active && ( Paused )}
{item.category_name || 'Uncategorized'} Due {fmtDate(item.next_due_date)} {cycleLabel(item)} {item.reminder_days_before ?? 3}d reminder

Per cycle

{fmt(item.expected_amount)}

Monthly

{fmt(item.monthly_equivalent)}

); } function BillPickerDialog({ open, onClose, recommendation, bills, onConfirm, busy }) { const [search, setSearch] = useState(''); const [selectedId, setSelectedId] = useState(null); useEffect(() => { if (open) { setSearch(''); setSelectedId(null); } }, [open]); const filtered = useMemo(() => { const q = search.toLowerCase(); return (bills || []).filter(b => !q || b.name.toLowerCase().includes(q)); }, [bills, search]); return ( { if (!v) onClose(); }}> Link to existing bill

{recommendation?.name} {recommendation && ( {recommendation.occurrence_count} charge{recommendation.occurrence_count !== 1 ? 's' : ''} · {fmt(recommendation.expected_amount)} )}

The matching transactions will be marked as paid under the selected bill.

setSearch(e.target.value)} className="text-sm" />
{filtered.length === 0 ? (

No bills found.

) : filtered.map(bill => ( ))}
); } function TxResultRow({ tx, onTrack }) { const dollars = (Math.abs(tx.amount) / 100).toFixed(2); const label = tx.payee || tx.description || tx.memo || '—'; const account = tx.account_name || tx.data_source_name || null; const isMatched = tx.match_status === 'matched'; const catalogMatch = tx.catalog_match; return (
{label} {isMatched ? ( {tx.matched_bill_name || 'Matched'} ) : ( Unmatched )} {catalogMatch && ( Known: {catalogMatch.name} )}

{tx.posted_date}{account ? ` · ${account}` : ''} {catalogMatch ? ` · ${TYPE_LABELS[catalogMatch.subscription_type] || 'Other'}` : ''}

${dollars} {!isMatched && ( )}
); } function RecommendationCard({ recommendation, categoryId, onAccept, onDecline, onMatch, busy }) { return (

{recommendation.name}

{TYPE_LABELS[recommendation.subscription_type] || 'Other'} · {recommendation.occurrence_count} charges · last seen {fmtDate(recommendation.last_seen_date)}

{fmt(recommendation.expected_amount)}

{fmt(recommendation.monthly_equivalent)} / mo

{recommendation.confidence}% match {recommendation.reasons?.map(reason => ( {reason} ))}
); } export default function SubscriptionsPage() { const [data, setData] = useState({ summary: {}, subscriptions: [] }); const [recommendations, setRecommendations] = useState([]); const [categories, setCategories] = useState([]); const [bills, setBills] = useState([]); const [loading, setLoading] = useState(true); const [recommendationsLoading, setRecommendationsLoading] = useState(true); const [busyId, setBusyId] = useState(null); const [modal, setModal] = useState(null); const [matchTarget, setMatchTarget] = useState(null); const [recSearch, setRecSearch] = useState(''); const [draggingId, setDraggingId] = useState(null); const [dropTargetId, setDropTargetId] = useState(null); const [movingBillId, setMovingBillId] = useState(null); const [txQuery, setTxQuery] = useState(''); const [txResults, setTxResults] = useState([]); const [txSearching, setTxSearching] = useState(false); const txDebounce = useRef(null); const subscriptionCategoryId = useMemo(() => { const match = categories.find(category => /subscrip/i.test(category.name)); return match?.id || null; }, [categories]); const load = useCallback(async () => { setLoading(true); try { const [subscriptionData, categoryData] = await Promise.all([ api.subscriptions(), api.categories(), ]); setData(subscriptionData); setCategories(categoryData || []); } catch (err) { toast.error(err.message || 'Failed to load subscriptions.'); } finally { setLoading(false); } }, []); const loadRecommendations = useCallback(async () => { setRecommendationsLoading(true); try { const result = await api.subscriptionRecommendations(); setRecommendations(result.recommendations || []); } catch (err) { toast.error(err.message || 'Failed to scan subscription recommendations.'); } finally { setRecommendationsLoading(false); } }, []); useEffect(() => { load(); loadRecommendations(); api.allBills().then(b => setBills(Array.isArray(b) ? b : [])).catch(() => {}); }, [load, loadRecommendations]); useEffect(() => { clearTimeout(txDebounce.current); const q = txQuery.trim(); if (!q) { setTxResults([]); return; } txDebounce.current = setTimeout(async () => { setTxSearching(true); try { const result = await api.subscriptionTransactionMatches({ q, limit: 50 }); setTxResults(Array.isArray(result) ? result : (result?.transactions ?? [])); } catch { setTxResults([]); } finally { setTxSearching(false); } }, 300); return () => clearTimeout(txDebounce.current); }, [txQuery]); async function refreshAll() { await Promise.all([load(), loadRecommendations()]); } async function toggleSubscription(item) { setBusyId(`toggle-${item.id}`); try { await api.updateSubscription(item.id, { active: !item.active }); toast.success(item.active ? 'Subscription paused' : 'Subscription resumed'); await load(); } catch (err) { toast.error(err.message || 'Subscription could not be updated.'); } finally { setBusyId(null); } } async function acceptRecommendation(recommendation) { setBusyId(`rec-${recommendation.id}`); try { await api.createSubscriptionFromRecommendation(recommendation); toast.success(`${recommendation.name} is now tracked.`); await refreshAll(); } catch (err) { toast.error(err.message || 'Could not create subscription.'); } finally { setBusyId(null); } } async function declineRecommendation(recommendation) { if (!recommendation.decline_key) return; setBusyId(`dec-${recommendation.id}`); try { await api.declineRecommendation(recommendation.decline_key); setRecommendations(prev => prev.filter(r => r.id !== recommendation.id)); } catch (err) { toast.error(err.message || 'Could not dismiss recommendation.'); } finally { setBusyId(null); } } async function matchRecommendationToBill(billId) { if (!matchTarget || !billId) return; setBusyId(`match-${matchTarget.id}`); try { const result = await api.matchRecommendationToBill(matchTarget.transaction_ids, billId, matchTarget.merchant); toast.success(`Linked ${result.matched_count} transaction${result.matched_count !== 1 ? 's' : ''} to "${result.bill_name}".`); setMatchTarget(null); setRecommendations(prev => prev.filter(r => r.id !== matchTarget.id)); } catch (err) { toast.error(err.message || 'Could not link recommendation to bill.'); } finally { setBusyId(null); } } function openManualSubscription() { setModal({ bill: null, initialBill: { name: '', category_id: subscriptionCategoryId, due_day: new Date().getDate(), expected_amount: '', billing_cycle: 'monthly', cycle_type: 'monthly', cycle_day: String(new Date().getDate()), is_subscription: 1, subscription_type: 'other', reminder_days_before: 3, }, }); } function openFromTransaction(tx) { const catalogMatch = tx.catalog_match; const label = catalogMatch?.name || tx.payee || tx.description || tx.memo || ''; const dollars = Math.abs(tx.amount ?? 0) / 100; const rawDay = tx.posted_date ? new Date(tx.posted_date + 'T12:00:00').getDate() : NaN; const dueDay = Number.isInteger(rawDay) && rawDay >= 1 && rawDay <= 31 ? rawDay : new Date().getDate(); setModal({ bill: null, initialBill: { name: label, category_id: subscriptionCategoryId, due_day: dueDay, expected_amount: dollars > 0 ? dollars.toFixed(2) : '', cycle_type: 'monthly', is_subscription: 1, subscription_type: catalogMatch?.subscription_type || 'other', website: catalogMatch?.website || undefined, notes: catalogMatch ? `Matched known subscription catalog entry: ${catalogMatch.name}` : undefined, reminder_days_before: 3, }, }); } const summary = data.summary || {}; const subscriptions = data.subscriptions || []; const active = subscriptions.filter(item => item.active); const paused = subscriptions.filter(item => !item.active); const reorderEnabled = !loading && bills.length > 0; async function persistSubscriptionOrder(nextSubscriptions, nextBills, movedId) { setData(prev => ({ ...prev, subscriptions: nextSubscriptions })); setBills(nextBills); setMovingBillId(movedId); try { await api.reorderBills(reorderPayload(nextBills)); toast.success('Subscription order saved'); await load(); api.allBills().then(b => setBills(Array.isArray(b) ? b : [])).catch(() => {}); } catch (err) { toast.error(err.message || 'Failed to save subscription order'); await load(); } finally { setMovingBillId(null); } } function reorderSubscriptionGroup(activeState, orderedGroup) { const sourceGroup = subscriptions.filter(item => !!item.active === activeState); const replacements = [...orderedGroup]; const nextSubscriptions = subscriptions.map(item => ( !!item.active === activeState ? replacements.shift() : item )); const sourceBills = bills.length ? bills : subscriptions; const affectedIds = new Set(sourceGroup.map(item => item.id)); const billById = new Map(sourceBills.map(item => [item.id, item])); const orderedBills = orderedGroup.map(item => ({ ...(billById.get(item.id) || item), ...item })); const nextBills = sourceBills.map(bill => ( affectedIds.has(bill.id) ? orderedBills.shift() : bill )); persistSubscriptionOrder(nextSubscriptions, nextBills, movedItemId(sourceGroup, orderedGroup)); } function moveControlsForGroup(group, activeState) { return (item, index) => ({ enabled: reorderEnabled, moving: movingBillId === item.id, canMoveUp: index > 0, canMoveDown: index < group.length - 1, onMoveUp: () => reorderSubscriptionGroup(activeState, moveInArray(group, index, index - 1)), onMoveDown: () => reorderSubscriptionGroup(activeState, moveInArray(group, index, index + 1)), }); } function dragPropsForGroup(group, activeState) { return (item, index) => { if (!reorderEnabled) return { draggable: false }; return { draggable: true, isDragging: draggingId === item.id, isDropTarget: dropTargetId === item.id && draggingId !== item.id, onDragStart: (event) => { setDraggingId(item.id); event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.setData('text/plain', String(item.id)); }, onDragEnter: () => { if (draggingId && draggingId !== item.id) setDropTargetId(item.id); }, onDragOver: (event) => { event.preventDefault(); event.dataTransfer.dropEffect = 'move'; if (draggingId && draggingId !== item.id) setDropTargetId(item.id); }, onDrop: (event) => { event.preventDefault(); const sourceId = Number(event.dataTransfer.getData('text/plain') || draggingId); const fromIndex = group.findIndex(row => row.id === sourceId); if (fromIndex >= 0) reorderSubscriptionGroup(activeState, moveInArray(group, fromIndex, index)); setDraggingId(null); setDropTargetId(null); }, onDragEnd: () => { setDraggingId(null); setDropTargetId(null); }, }; }; } const MIN_CONFIDENCE = 90; const highConfidenceRecs = useMemo( () => recommendations.filter(r => (r.confidence ?? 0) >= MIN_CONFIDENCE), [recommendations], ); const filteredRecs = useMemo(() => { const q = recSearch.trim().toLowerCase(); return q ? highConfidenceRecs.filter(r => r.name?.toLowerCase().includes(q)) : highConfidenceRecs; }, [highConfidenceRecs, recSearch]); return (

Recurring Services

Subscriptions

Track manual subscriptions and review recurring SimpleFIN charges.

Tracked Subscriptions Subscriptions are bills with recurring-service metadata. {loading ? (
{Array.from({ length: 4 }).map((_, index) => (
))}
) : subscriptions.length === 0 ? (

No subscriptions tracked yet.

Add one manually or accept a SimpleFIN recommendation.

) : ( <> {active.map((item, index) => ( setModal({ bill })} onToggle={toggleSubscription} moveControls={moveControlsForGroup(active, true)(item, index)} dragProps={dragPropsForGroup(active, true)(item, index)} /> ))} {paused.map((item, index) => ( setModal({ bill })} onToggle={toggleSubscription} moveControls={moveControlsForGroup(paused, false)(item, index)} dragProps={dragPropsForGroup(paused, false)(item, index)} /> ))} )}
Recommendations {!recommendationsLoading && highConfidenceRecs.length > 0 && ( {filteredRecs.length} of {highConfidenceRecs.length} )}
Recurring charges from your accounts with 90%+ confidence. {!recommendationsLoading && highConfidenceRecs.length > 0 && (
setRecSearch(e.target.value)} className="pl-8 h-8 text-sm" />
)}
{recommendationsLoading ? (
Scanning transactions…
) : highConfidenceRecs.length === 0 ? (

No high-confidence recommendations.

{recommendations.length > 0 ? `${recommendations.length} low-confidence pattern${recommendations.length !== 1 ? 's' : ''} found — more account activity will improve accuracy.` : 'Sync your accounts after a few recurring charges appear.'}

) : filteredRecs.length === 0 ? (

No matches for "{recSearch}"

) : ( filteredRecs.map(recommendation => ( setMatchTarget(rec)} /> )) )}
{/* Transaction search */}
Search Bank Transactions
Search all account charges — matched and unmatched — to find subscriptions the algorithm may have missed.
setTxQuery(e.target.value)} className="pl-8 h-9 text-sm" autoComplete="off" />
{(txQuery.trim() || txSearching) && ( {txSearching ? (
Searching transactions…
) : txResults.length === 0 ? (

No transactions found for "{txQuery}"

Try a different merchant name or description.

) : (

{txResults.length} result{txResults.length !== 1 ? 's' : ''} {txResults.length === 50 ? ' (showing first 50)' : ''}

{txResults.map(tx => ( ))}
)}
)}
{modal && ( setModal(null)} onSave={async () => { setModal(null); await refreshAll(); }} /> )} setMatchTarget(null)} recommendation={matchTarget} bills={bills} onConfirm={matchRecommendationToBill} busy={!!busyId?.startsWith('match-')} />
); }