68 lines
2.1 KiB
TypeScript
68 lines
2.1 KiB
TypeScript
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?.tags && selectedGroupKey.tags.length > 0) {
|
|
return rawTxns.filter(txn => {
|
|
if (!txn.tags) return false;
|
|
const txnTags = txn.tags.map(t => typeof t === "string" ? t : t.name);
|
|
return selectedGroupKey.tags!.every(selectedTag => txnTags.includes(selectedTag));
|
|
});
|
|
}
|
|
|
|
return rawTxns;
|
|
}
|
|
|
|
// ─── Main adapter ────────────────────────────────────────────
|
|
|
|
export function buildLatestItems(
|
|
reportData: ReportData,
|
|
selectedPeriodId: string | null,
|
|
selectedGroupKey: GroupKey | null,
|
|
mode: "expense" | "income"
|
|
): 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"),
|
|
}));
|
|
}
|