Open-source personal finance manager. Self-hosted, privacy-first.
fix(reports): make Money Map 30D an exact 30-day window (#414)
Tássio Noronhacc302f707e55
diff --git a/backend/app/api/reports.py b/backend/app/api/reports.pyindex 9ad98f81..3f441d31 100644--- a/backend/app/api/reports.py+++ b/backend/app/api/reports.py@@ -34,12 +34,14 @@ async def get_income_expenses(interval: str = Query("monthly", pattern="^(daily|weekly|monthly|yearly)$"),account_ids: Optional[list[uuid.UUID]] = Query(None),period: str | None = Query(None, pattern="^ytd$"),+ days: Optional[int] = Query(None, ge=1, le=730),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):+ """`days` overrides `months` with an exact rolling window ending today."""return await report_service.get_income_expenses_report(session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency,- account_ids=account_ids, period=period,+ account_ids=account_ids, period=period, days=days,)diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 0c878829..6d932002 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -52,8 +52,17 @@ _ASSET_TYPE_COLORS: dict[str, str] = {}-def _report_start_date(today: date, months: int, period: str | None = None) -> date:- """Resolve historical report start date."""+def _report_start_date(+ today: date, months: int, period: str | None = None, days: int | None = None+) -> date:+ """Resolve historical report start date.++ `days` requests an exact rolling window ending today (inclusive), instead of+ the month-aligned window the `months` ranges use.+ """+ if days:+ return today - timedelta(days=days - 1)+if period == "ytd":return date(today.year, 1, 1)@@ -370,12 +379,13 @@ async def get_income_expenses_report(currency: str = "USD",account_ids: Optional[list[uuid.UUID]] = None,period: str | None = None,+ days: int | None = None,) -> ReportResponse:"""Build a ReportResponse for income vs expenses over time."""filtered = account_ids is not Noneacct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []today = date.today()- start = _report_start_date(today, months, period)+ start = _report_start_date(today, months, period, days)# Get user's primary currency + global reporting modeuser = await session.get(User, user_id)@@ -552,7 +562,11 @@ async def get_income_expenses_report(cursor = startwhile cursor <= today:m_start, m_end = _month_range(cursor)- projections = await _get_recurring_projections(session, workspace_id, m_start, m_end, account_ids)+ # A day-window range can start mid-month: only project occurrences that+ # fall inside the requested window.+ projections = await _get_recurring_projections(+ session, workspace_id, max(m_start, start), m_end, account_ids+ )for proj in projections:# Convert to primary currencyconverted, _ = await fx_convert(diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.pyindex ac7e110a..2a57648c 100644--- a/backend/tests/test_report_service.py+++ b/backend/tests/test_report_service.py@@ -179,6 +179,16 @@ def test_report_start_date_ytd_uses_current_year_start():assert _report_start_date(date(2025, 6, 15), 24, period="ytd") == date(2025, 1, 1)+def test_report_start_date_days_window_is_exact_and_inclusive():+ # 30 days ending today (inclusive), not the month-aligned window months gives.+ assert _report_start_date(date(2025, 7, 7), 1, days=30) == date(2025, 6, 8)+ assert _report_start_date(date(2025, 3, 1), 1, days=30) == date(2025, 1, 31)+++def test_report_start_date_days_overrides_months_and_period():+ assert _report_start_date(date(2025, 6, 15), 24, period="ytd", days=7) == date(2025, 6, 9)++# ---------------------------------------------------------------------------# Service-level tests: get_net_worth_report (works with SQLite)# ---------------------------------------------------------------------------@@ -534,10 +544,11 @@ async def test_income_expenses_api_validation(client, auth_headers):async def test_income_expenses_api_accepts_ytd_period(client, auth_headers, monkeypatch):"""GET /reports/income-expenses passes period=ytd to service."""- async def fake_report(session, workspace_id, user_id, months, interval, currency, account_ids=None, period=None):+ async def fake_report(session, workspace_id, user_id, months, interval, currency, account_ids=None, period=None, days=None):assert months == 12assert interval == "monthly"assert period == "ytd"+ assert days is Nonereturn ReportResponse(summary=ReportSummary(primary_value=0,@@ -566,6 +577,49 @@ async def test_income_expenses_api_accepts_ytd_period(client, auth_headers, monkassert resp.status_code == 200+async def test_income_expenses_api_forwards_days_window(client, auth_headers, monkeypatch):+ """GET /reports/income-expenses passes the exact day window to the service."""+ seen: dict = {}++ async def fake_report(session, workspace_id, user_id, months, interval, currency, account_ids=None, period=None, days=None):+ seen["days"] = days+ return ReportResponse(+ summary=ReportSummary(+ primary_value=0,+ change_amount=0,+ change_percent=None,+ breakdowns=[],+ ),+ trend=[],+ meta=ReportMeta(+ type="income_expenses",+ series_keys=["income", "expenses"],+ currency=currency,+ interval=interval,+ ),+ composition=[],+ category_trend=[],+ )++ monkeypatch.setattr(report_service, "get_income_expenses_report", fake_report)++ resp = await client.get(+ "/api/reports/income-expenses",+ params={"months": 1, "interval": "monthly", "days": 30},+ headers=auth_headers,+ )+ assert resp.status_code == 200+ assert seen["days"] == 30++ resp = await client.get(+ "/api/reports/income-expenses",+ params={"days": 0},+ headers=auth_headers,+ )+ assert resp.status_code == 422++@pytest.mark.asyncioasync def test_income_expenses_api_requires_auth(client):"""GET /reports/income-expenses requires authentication."""diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 12cb0277..439685dd 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1109,9 +1109,11 @@ export const reports = {})return data},- incomeExpenses: async (months = 12, interval = 'monthly', accountIds?: string[], period?: 'ytd'): Promise<ReportResponse> => {+ // `days` requests an exact rolling window ending today, instead of the+ // month-aligned window `months` produces.+ incomeExpenses: async (months = 12, interval = 'monthly', accountIds?: string[], period?: 'ytd', days?: number): Promise<ReportResponse> => {const extra = acctIdsParam(accountIds)- const { data } = await api.get('/reports/income-expenses', { params: { months, interval, period, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })+ const { data } = await api.get('/reports/income-expenses', { params: { months, interval, period, days, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })return data},cashFlow: async (months = 6, interval = 'daily', baseline = false, accountIds?: string[]): Promise<ReportResponse> => {diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsxindex 644f5888..cd644f39 100644--- a/frontend/src/pages/reports.tsx+++ b/frontend/src/pages/reports.tsx@@ -64,7 +64,9 @@ function formatCompact(value: number, currency = 'USD', locale = 'en-US') {-type RangeOption = { key: string; months: number; period?: 'ytd' }+// `days` (when set) asks for an exact rolling window ending today rather than+// the month-aligned window `months` produces.+type RangeOption = { key: string; months: number; period?: 'ytd'; days?: number }const HISTORICAL_RANGE_OPTIONS: readonly RangeOption[] = [{ key: '6m', months: 6 },@@ -82,7 +84,7 @@ const FORWARD_RANGE_OPTIONS: readonly RangeOption[] = [// The Money Map answers "where did my money go lately", so it leans on recent// windows (down to 30 days) and drops the 2Y trend view the other tabs keep.const MONEY_MAP_RANGE_OPTIONS: readonly RangeOption[] = [- { key: '30d', months: 1 },+ { key: '30d', months: 1, days: 30 },{ key: '3m', months: 3 },{ key: '6m', months: 6 },{ key: 'ytd', months: 12, period: 'ytd' },@@ -172,6 +174,7 @@ export default function ReportsPage() {const selectedRange = rangeOptions.find((r) => r.key === rangeKey) ?? rangeOptions[0]const months = selectedRange.monthsconst period = selectedRange.period+ const days = selectedRange.daysconst handleSelectTab = (key: string) => {setActiveTab(key)@@ -194,12 +197,12 @@ export default function ReportsPage() {}const { data, isLoading } = useQuery<ReportResponse>({- queryKey: ['reports', activeTab, rangeKey, months, period ?? null, interval, isCashFlow ? cashFlowBaseline : false, activeAccountIds, activeWalletIds],+ queryKey: ['reports', activeTab, rangeKey, months, period ?? null, days ?? null, interval, isCashFlow ? cashFlowBaseline : false, activeAccountIds, activeWalletIds],queryFn: () =>isCashFlow? reports.cashFlow(months, interval, cashFlowBaseline, acctIds): activeTab === 'income_expenses' || isMoneyMap- ? reports.incomeExpenses(months, interval, acctIds, period)+ ? reports.incomeExpenses(months, interval, acctIds, period, days): reports.netWorth(months, interval, acctIds, walletIds, period),enabled: currentTab.enabled && !(noAccounts && activeTab !== 'net_worth'),})