63 lines
1.9 KiB
TypeScript
63 lines
1.9 KiB
TypeScript
import { ReportData, Transaction } from "../../features/report";
|
|
import {
|
|
mergeBucketPeriods,
|
|
periodIdToKey,
|
|
formatCurrency,
|
|
} from "../report.helpers";
|
|
import { LatestItem } from "./LatestItems.models";
|
|
|
|
// ─── Transaction extraction ─────────────────────────────────
|
|
|
|
function extractTransactions(
|
|
reportData: ReportData,
|
|
selectedPeriodId: string | null,
|
|
mode: "expense" | "income"
|
|
): Transaction[] {
|
|
if (selectedPeriodId) {
|
|
const key = periodIdToKey(selectedPeriodId);
|
|
const periods = mergeBucketPeriods(reportData.buckets, key);
|
|
const selected = periods.find((p) => p.id === selectedPeriodId);
|
|
|
|
if (!selected) return [];
|
|
|
|
return mode === "expense"
|
|
? (selected.expenses.transactions || [])
|
|
: (selected.incomes.transactions || []);
|
|
}
|
|
|
|
const periods = mergeBucketPeriods(reportData.buckets, "full");
|
|
|
|
if (!periods.length) return [];
|
|
|
|
const full = periods[0];
|
|
|
|
return mode === "expense"
|
|
? (full.expenses.transactions || [])
|
|
: (full.incomes.transactions || []);
|
|
}
|
|
|
|
// ─── Main adapter ────────────────────────────────────────────
|
|
|
|
export function buildLatestItems(
|
|
reportData: ReportData,
|
|
selectedPeriodId: string | null,
|
|
mode: "expense" | "income"
|
|
): LatestItem[] {
|
|
const txns = extractTransactions(reportData, selectedPeriodId, mode);
|
|
|
|
return txns
|
|
.filter((t) => (mode === "expense" ? t.amount < 0 : t.amount >= 0))
|
|
.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"),
|
|
}));
|
|
}
|