import { ReportData, Transaction, GroupKey } from "../../features/report"; import { mergeBucketPeriods, periodIdToKey, formatCurrency, filterBuckets, } from "../report.helpers"; import { LatestItem } from "./LatestItems.models"; // ─── Transaction extraction ───────────────────────────────── function extractTransactions( reportData: ReportData, selectedPeriodId: string | null, selectedGroupKey: GroupKey | null, ): Transaction[] { // 1. Get raw transactions let rawTxns: Transaction[] = []; if (selectedPeriodId) { const key = periodIdToKey(selectedPeriodId); const periods = mergeBucketPeriods(reportData.buckets, key); const selected = periods.find((p) => p.id === selectedPeriodId); rawTxns = selected?.metric.transactions || []; } else { const periods = mergeBucketPeriods(reportData.buckets, "all"); if (periods.length > 0) { rawTxns = periods[0].metric.transactions || []; } } // 2. Filter by group key if (selectedGroupKey) { rawTxns = rawTxns.filter(txn => { let match = true; if (selectedGroupKey.tags && selectedGroupKey.tags.length > 0) { if (!txn.tags) match = false; else { const txnTags = txn.tags.map(t => typeof t === "string" ? t : t.name); if (!selectedGroupKey.tags.every(selectedTag => txnTags.includes(selectedTag))) match = false; } } if (match && selectedGroupKey.payee && selectedGroupKey.payee.length > 0) { if (!txn.payee || !txn.payee.name) match = false; else { if (!selectedGroupKey.payee.includes(txn.payee.name)) match = false; } } return match; }); } return rawTxns; } // ─── Main adapter ──────────────────────────────────────────── export function buildLatestItems( reportData: ReportData, selectedPeriodId: string | null, selectedGroupKey: GroupKey | null, flow: "outflows" | "inflows" ): LatestItem[] { const txns = extractTransactions(reportData, selectedPeriodId, selectedGroupKey); return txns .sort( (a, b) => new Date(b.occurred_at).getTime() - new Date(a.occurred_at).getTime() ) .map((t, index) => ({ id: index + 1, title: t.payee.name, subtitle: t.tags.map((tag) => tag.name).join(", "), amount: formatCurrency(t.amount), timeAgo: new Date(t.occurred_at).toLocaleDateString("en-IN"), })); }