diff --git a/app/utils/chart-data-buckets.ts b/app/utils/chart-data-buckets.ts index 1165c4541f..1cc4a43308 100644 --- a/app/utils/chart-data-buckets.ts +++ b/app/utils/chart-data-buckets.ts @@ -34,17 +34,13 @@ export function buildWeeklyEvolution( if (sorted.length === 0) return [] const rangeStartDate = parseIsoDate(rangeStartIso) + const rangeEndDate = parseIsoDate(rangeEndIso) - // Align from last day with actual data (npm has 1-2 day delay, today is incomplete) - const lastNonZero = sorted.findLast(d => d.value > 0) - const pickerEnd = parseIsoDate(rangeEndIso) - const effectiveEnd = lastNonZero ? parseIsoDate(lastNonZero.day) : pickerEnd - const rangeEndDate = effectiveEnd.getTime() < pickerEnd.getTime() ? effectiveEnd : pickerEnd - - // Group into 7-day buckets from END backwards const buckets = new Map() + for (const item of sorted) { - const offset = Math.floor((rangeEndDate.getTime() - parseIsoDate(item.day).getTime()) / DAY_MS) + const itemDate = parseIsoDate(item.day) + const offset = Math.floor((rangeEndDate.getTime() - itemDate.getTime()) / DAY_MS) if (offset < 0) continue const idx = Math.floor(offset / 7) buckets.set(idx, (buckets.get(idx) ?? 0) + item.value) diff --git a/test/unit/app/utils/chart-data-buckets.spec.ts b/test/unit/app/utils/chart-data-buckets.spec.ts index 8538f18138..141a9688c3 100644 --- a/test/unit/app/utils/chart-data-buckets.spec.ts +++ b/test/unit/app/utils/chart-data-buckets.spec.ts @@ -84,7 +84,7 @@ describe('buildWeeklyEvolution', () => { expect(result[1]!.weekEnd).toBe('2025-03-10') }) - it('aligns from last non-zero data day, ignoring trailing zeros', () => { + it('always aligns from rangeEnd, even with trailing zeros', () => { const daily = [ { day: '2025-03-01', value: 10 }, { day: '2025-03-02', value: 10 }, @@ -99,10 +99,14 @@ describe('buildWeeklyEvolution', () => { const result = buildWeeklyEvolution(daily, '2025-03-01', '2025-03-09') - expect(result).toHaveLength(1) - expect(result[0]!.value).toBe(70) + // Bucket 0: 03-03..03-09 = 50, Bucket 1: 03-01..03-02 (partial, scaled) + expect(result).toHaveLength(2) expect(result[0]!.weekStart).toBe('2025-03-01') - expect(result[0]!.weekEnd).toBe('2025-03-07') + expect(result[0]!.weekEnd).toBe('2025-03-02') + expect(result[0]!.value).toBe(Math.round((20 * 7) / 2)) + expect(result[1]!.weekStart).toBe('2025-03-03') + expect(result[1]!.weekEnd).toBe('2025-03-09') + expect(result[1]!.value).toBe(50) }) it('returns empty array for empty input', () => {