Open-source personal finance manager. Self-hosted, privacy-first.
feat: add Indian financial year support (#841)
Saikumar Madel4f580c7d6102
diff --git a/backend/app/api/reports.py b/backend/app/api/reports.pyindex 3f441d31..02ad9a38 100644--- a/backend/app/api/reports.py+++ b/backend/app/api/reports.py@@ -1,7 +1,7 @@import uuidfrom typing import Optional-from fastapi import APIRouter, Depends, Query+from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.database import get_async_session@@ -12,6 +12,21 @@ from app.services import report_servicerouter = APIRouter(prefix="/api/reports", tags=["reports"])+def _financial_year_start_month(tax_jurisdiction: str | None) -> int:+ """Return the first month of the workspace's financial year."""+ return 4 if (tax_jurisdiction or "").upper() == "IN" else 1+++def _reject_unsupported_fiscal_year_report(+ period: str | None, interval: str, financial_year_start_month: int+) -> None:+ if period == "ytd" and interval == "yearly" and financial_year_start_month != 1:+ raise HTTPException(+ status_code=422,+ detail="Yearly YTD reports are not supported for non-calendar financial years",+ )++@router.get("/net-worth", response_model=ReportResponse)async def get_net_worth(months: int = Query(12, ge=1, le=24),@@ -22,9 +37,12 @@ async def get_net_worth(ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):+ financial_year_start_month = _financial_year_start_month(ctx.workspace.tax_jurisdiction)+ _reject_unsupported_fiscal_year_report(period, interval, financial_year_start_month)return await report_service.get_net_worth_report(session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency,account_ids=account_ids, asset_group_ids=asset_group_ids, period=period,+ financial_year_start_month=financial_year_start_month,)@@ -39,9 +57,12 @@ async def get_income_expenses(session: AsyncSession = Depends(get_async_session),):"""`days` overrides `months` with an exact rolling window ending today."""+ financial_year_start_month = _financial_year_start_month(ctx.workspace.tax_jurisdiction)+ _reject_unsupported_fiscal_year_report(period, interval, financial_year_start_month)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, days=days,+ financial_year_start_month=financial_year_start_month,)diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 22d09942..6d5cc49a 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -58,7 +58,11 @@ _ASSET_TYPE_COLORS: dict[str, str] = {def _report_start_date(- today: date, months: int, period: str | None = None, days: int | None = None+ today: date,+ months: int,+ period: str | None = None,+ days: int | None = None,+ financial_year_start_month: int = 1,) -> date:"""Resolve historical report start date.@@ -69,7 +73,10 @@ def _report_start_date(return today - timedelta(days=days - 1)if period == "ytd":- return date(today.year, 1, 1)+ if not 1 <= financial_year_start_month <= 12:+ raise ValueError("financial_year_start_month must be between 1 and 12")+ year = today.year - (today.month < financial_year_start_month)+ return date(year, financial_year_start_month, 1)start = date(today.year, today.month, 1) - timedelta(days=months * 30)return start.replace(day=1)@@ -282,13 +289,16 @@ async def get_net_worth_report(account_ids: Optional[list[uuid.UUID]] = None,asset_group_ids: Optional[list[uuid.UUID]] = None,period: str | None = None,+ financial_year_start_month: int = 1,) -> ReportResponse:"""Build a full ReportResponse for net worth over time."""# A wallet-only collection (wallets, no accounts) still filters.if asset_group_ids is not None and account_ids is None:account_ids = []today = date.today()- start = _report_start_date(today, months, period)+ start = _report_start_date(+ today, months, period, financial_year_start_month=financial_year_start_month+ )# Get user's primary currencyuser = await session.get(User, user_id)@@ -385,12 +395,19 @@ async def get_income_expenses_report(account_ids: Optional[list[uuid.UUID]] = None,period: str | None = None,days: int | None = None,+ financial_year_start_month: int = 1,) -> 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, days)+ start = _report_start_date(+ today,+ months,+ period=period,+ days=days,+ financial_year_start_month=financial_year_start_month,+ )# Get user's primary currency + global reporting modeuser = await session.get(User, user_id)diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.pyindex 16ca7bad..bc062452 100644--- a/backend/tests/test_report_service.py+++ b/backend/tests/test_report_service.py@@ -1,8 +1,11 @@import uuidfrom datetime import date, datetime, timedelta, timezonefrom decimal import Decimal+from types import SimpleNamespace+from unittest.mock import AsyncMockimport pytest+from fastapi import HTTPExceptionfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.account import Account@@ -19,6 +22,10 @@ from app.schemas.report import (ReportSummary,)from app.services import report_service+from app.api.reports import (+ _financial_year_start_month,+ _reject_unsupported_fiscal_year_report,+)from app.services.report_service import (_add_months,_asset_value_at,@@ -30,6 +37,8 @@ from app.services.report_service import (get_net_worth_report,)from app.models.recurring_transaction import RecurringTransaction+from app.core.workspace_context import current_workspace+from app.main import app# ---------------------------------------------------------------------------@@ -179,6 +188,22 @@ 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_ytd_uses_april_for_indian_financial_year():+ assert _report_start_date(+ date(2026, 3, 31), 12, period="ytd", financial_year_start_month=4+ ) == date(2025, 4, 1)+ assert _report_start_date(+ date(2026, 4, 1), 12, period="ytd", financial_year_start_month=4+ ) == date(2026, 4, 1)+++def test_report_start_date_ytd_rejects_invalid_financial_year_month():+ with pytest.raises(ValueError, match="financial_year_start_month"):+ _report_start_date(+ date(2025, 6, 15), 12, period="ytd", financial_year_start_month=13+ )++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)@@ -546,11 +571,15 @@ 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, days=None):+ async def fake_report(+ session, workspace_id, user_id, months, interval, currency,+ account_ids=None, period=None, days=None, financial_year_start_month=1,+ ):assert months == 12assert interval == "monthly"assert period == "ytd"assert days is None+ assert financial_year_start_month == 1return ReportResponse(summary=ReportSummary(primary_value=0,@@ -584,7 +613,10 @@ async def test_income_expenses_api_forwards_days_window(client, auth_headers, mo"""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):+ async def fake_report(+ session, workspace_id, user_id, months, interval, currency,+ account_ids=None, period=None, days=None, financial_year_start_month=1,+ ):seen["days"] = daysreturn ReportResponse(summary=ReportSummary(@@ -622,6 +654,68 @@ async def test_income_expenses_api_forwards_days_window(client, auth_headers, moassert resp.status_code == 422+def test_financial_year_start_month_uses_india_jurisdiction():+ assert _financial_year_start_month("IN") == 4+ assert _financial_year_start_month("in") == 4+ assert _financial_year_start_month("BR") == 1+ assert _financial_year_start_month(None) == 1+++def test_indian_yearly_ytd_reports_are_rejected_until_fiscal_buckets_exist():+ with pytest.raises(HTTPException, match="Yearly YTD reports"):+ _reject_unsupported_fiscal_year_report("ytd", "yearly", 4)+ _reject_unsupported_fiscal_year_report("ytd", "yearly", 1)++[email protected](("tax_jurisdiction", "expected_month"), [("IN", 4), ("BR", 1)])+async def test_report_api_forwards_workspace_financial_year(+ client, auth_headers, monkeypatch, tax_jurisdiction, expected_month+):+ context = SimpleNamespace(+ workspace=SimpleNamespace(id=uuid.uuid4(), tax_jurisdiction=tax_jurisdiction),+ user_id=uuid.uuid4(),+ user=SimpleNamespace(primary_currency="INR"),+ )++ async def override_workspace():+ return context++ empty_report = ReportResponse(+ summary=ReportSummary(+ primary_value=0, change_amount=0, change_percent=None, breakdowns=[]+ ),+ trend=[],+ meta=ReportMeta(+ type="income_expenses",+ series_keys=["income", "expenses"],+ currency="INR",+ interval="monthly",+ ),+ composition=[],+ category_trend=[],+ )+ net_worth = AsyncMock(return_value=empty_report)+ income_expenses = AsyncMock(return_value=empty_report)+ app.dependency_overrides[current_workspace] = override_workspace+ monkeypatch.setattr(report_service, "get_net_worth_report", net_worth)+ monkeypatch.setattr(report_service, "get_income_expenses_report", income_expenses)+ try:+ net_response = await client.get(+ "/api/reports/net-worth", params={"period": "ytd"}, headers=auth_headers+ )+ income_response = await client.get(+ "/api/reports/income-expenses", params={"period": "ytd"}, headers=auth_headers+ )+ finally:+ app.dependency_overrides.pop(current_workspace, None)++ assert net_response.status_code == 200+ assert income_response.status_code == 200+ assert net_worth.call_args.kwargs["financial_year_start_month"] == expected_month+ assert income_expenses.call_args.kwargs["financial_year_start_month"] == expected_month++@pytest.mark.asyncioasync def test_income_expenses_api_requires_auth(client):"""GET /reports/income-expenses requires authentication."""diff --git a/frontend/src/lib/format.test.ts b/frontend/src/lib/format.test.tsindex 2f663df0..9642bc09 100644--- a/frontend/src/lib/format.test.ts+++ b/frontend/src/lib/format.test.ts@@ -31,6 +31,7 @@ describe('resolveDisplayLocale', () => {expect(resolveDisplayLocale('auto', 'BRL')).toBe('pt-BR')expect(resolveDisplayLocale('auto', 'EUR')).toBe('de-DE')expect(resolveDisplayLocale('auto', 'JPY')).toBe('ja-JP')+ expect(resolveDisplayLocale('auto', 'INR')).toBe('en-IN')})it('treats a missing number format like auto', () => {@@ -61,6 +62,7 @@ describe('resolveDateOrder', () => {expect(resolveDateOrder('auto', 'auto', 'USD')).toBe('mdy')expect(resolveDateOrder('auto', 'auto', 'BRL')).toBe('dmy')expect(resolveDateOrder('auto', 'auto', 'EUR')).toBe('dmy')+ expect(resolveDateOrder('auto', 'auto', 'INR')).toBe('dmy')})it('defaults to day-first when nothing is configured', () => {@@ -105,6 +107,7 @@ describe('formatCurrency', () => {expect(normalize(formatCurrency(1234.5, 'USD', 'en-US'))).toBe('$1,234.50')expect(normalize(formatCurrency(1234.5, 'BRL', 'pt-BR'))).toBe('R$ 1.234,50')expect(normalize(formatCurrency(1234.5, 'EUR', 'de-DE'))).toBe('1.234,50 €')+ expect(normalize(formatCurrency(100000, 'INR', 'en-IN'))).toBe('₹1,00,000.00')})it('keeps each currency at its own precision', () => {