From 2d0b0bc4706c525e1b85e40297374e3adcfa30ba Mon Sep 17 00:00:00 2001 From: Vishesh 'ironeagle' Bangotra Date: Fri, 1 May 2026 17:07:35 +0530 Subject: [PATCH] fixes for correct comparison period --- src/features/report/report.mapper.ts | 47 ++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/src/features/report/report.mapper.ts b/src/features/report/report.mapper.ts index 024b183..33a738d 100644 --- a/src/features/report/report.mapper.ts +++ b/src/features/report/report.mapper.ts @@ -25,14 +25,57 @@ const toLabel = (start: string, end: string, type: "weekly" | "monthly") => { })}`; }; +const getWeekOfMonth = (date: Date) => { + const firstDay = new Date(date.getFullYear(), date.getMonth(), 1); + return Math.ceil((date.getDate() + firstDay.getDay()) / 7); +}; + +const findCompareBucket = ( + current: ReportBucket, + buckets: ReportBucket[], + type: "weekly" | "monthly" +): ReportBucket | undefined => { + const start = new Date(current.start); + + if (type === "monthly") { + const targetYear = start.getFullYear() - 1; + const targetMonth = start.getMonth(); + + return buckets.find(b => { + const d = new Date(b.start); + return ( + d.getFullYear() === targetYear && + d.getMonth() === targetMonth + ); + }); + } + + if (type === "weekly") { + const weekIndex = getWeekOfMonth(start); // you must define this + const target = new Date(start); + target.setMonth(target.getMonth() - 1); + + return buckets.find(b => { + const d = new Date(b.start); + return ( + d.getFullYear() === target.getFullYear() && + d.getMonth() === target.getMonth() && + getWeekOfMonth(d) === weekIndex + ); + }); + } + + return undefined; +}; + const toPoints = ( buckets: ReportBucket[], type: "weekly" | "monthly", flow: "expenses" | "incomes" ): ChartDataPoint[] => { - return buckets.map((b, i) => { + return buckets.map((b) => { const amount = sumBucket(b, flow); - const prev = buckets[i - 1]; + const prev = findCompareBucket(b, buckets, type); return { id: toLabel(b.start, b.end, type),