Open-source personal finance manager. Self-hosted, privacy-first.
feat: YTD reporting period implementation (#273)
z0diake957f31f962f
diff --git a/backend/app/api/reports.py b/backend/app/api/reports.pyindex 318143fe..1772c4f6 100644--- a/backend/app/api/reports.py+++ b/backend/app/api/reports.py@@ -13,11 +13,18 @@ router = APIRouter(prefix="/api/reports", tags=["reports"])async def get_net_worth(months: int = Query(12, ge=1, le=24),interval: str = Query("monthly", pattern="^(daily|weekly|monthly|yearly)$"),+ period: str | None = Query(None, pattern="^ytd$"),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):return await report_service.get_net_worth_report(- session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency+ session,+ ctx.workspace.id,+ ctx.user_id,+ months,+ interval,+ ctx.user.primary_currency,+ period=period,)@@ -25,11 +32,18 @@ async def get_net_worth(async def get_income_expenses(months: int = Query(12, ge=1, le=24),interval: str = Query("monthly", pattern="^(daily|weekly|monthly|yearly)$"),+ period: str | None = Query(None, pattern="^ytd$"),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):return await report_service.get_income_expenses_report(- session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency+ session,+ ctx.workspace.id,+ ctx.user_id,+ months,+ interval,+ ctx.user.primary_currency,+ period=period,)diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 404bd6b8..20159b13 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -36,6 +36,15 @@ from app.services.dashboard_service import _get_open_accounts, _account_balance_CATEGORY_TREND_TOP_N = 11+def _report_start_date(today: date, months: int, period: str | None = None) -> date:+ """Resolve historical report start date."""+ if period == "ytd":+ return date(today.year, 1, 1)++ start = date(today.year, today.month, 1) - timedelta(days=months * 30)+ return start.replace(day=1)++async def _asset_value_at(session: AsyncSession, workspace_id: uuid.UUID, cutoff: date,primary_currency: str = "USD",@@ -153,11 +162,11 @@ async def get_net_worth_report(months: int = 12,interval: str = "monthly",currency: str = "USD",+ period: str | None = None,) -> ReportResponse:"""Build a full ReportResponse for net worth over time."""today = date.today()- start = date(today.year, today.month, 1) - timedelta(days=months * 30)- start = start.replace(day=1) # Align to month start+ start = _report_start_date(today, months, period)# Get user's primary currencyuser = await session.get(User, user_id)@@ -323,11 +332,11 @@ async def get_income_expenses_report(months: int = 12,interval: str = "monthly",currency: str = "USD",+ period: str | None = None,) -> ReportResponse:"""Build a ReportResponse for income vs expenses over time."""today = date.today()- start = date(today.year, today.month, 1) - timedelta(days=months * 30)- start = start.replace(day=1)+ start = _report_start_date(today, months, period)# 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 ad498b9e..de13fd1c 100644--- a/backend/tests/test_report_service.py+++ b/backend/tests/test_report_service.py@@ -11,13 +11,21 @@ from app.models.asset_value import AssetValuefrom app.models.bank_connection import BankConnectionfrom app.models.transaction import Transactionfrom app.models.user import User-from app.schemas.report import CategoryTrendItem, ReportDataPoint, ReportResponse+from app.schemas.report import (+ CategoryTrendItem,+ ReportDataPoint,+ ReportMeta,+ ReportResponse,+ ReportSummary,+)+from app.services import report_servicefrom app.services.report_service import (_add_months,_asset_value_at,_date_points,_format_date_label,_net_worth_at,+ _report_start_date,get_cash_flow_report,get_net_worth_report,)@@ -158,6 +166,19 @@ def test_date_points_last_point_replaces_same_period():assert len(labels) == len(set(labels))+# ---------------------------------------------------------------------------+# Pure-function tests: _report_start_date+# ---------------------------------------------------------------------------+++def test_report_start_date_month_range_aligns_to_month_start():+ assert _report_start_date(date(2025, 6, 15), 6) == date(2024, 12, 1)+++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)++# ---------------------------------------------------------------------------# Service-level tests: get_net_worth_report (works with SQLite)# ---------------------------------------------------------------------------@@ -320,6 +341,19 @@ async def test_net_worth_report_intervals(session: AsyncSession, test_user, testassert len(report.trend) > 0+async def test_net_worth_report_ytd_starts_at_current_year(+ session: AsyncSession, test_user, test_workspace+):+ """YTD report window starts at Jan 1 while preserving granularity."""+ report = await get_net_worth_report(+ session, test_workspace.id, test_user.id, months=24, interval="monthly", period="ytd"+ )++ assert report.trend[0].date == f"{date.today().year}-01"+ assert all(point.date.startswith(str(date.today().year)) for point in report.trend)++# ---------------------------------------------------------------------------# API-level tests: /reports/net-worth# ---------------------------------------------------------------------------@@ -343,6 +377,20 @@ async def test_net_worth_api_endpoint(client, auth_headers, test_transactions):assert isinstance(data["trend"], list)+async def test_net_worth_api_accepts_ytd_period(client, auth_headers):+ """GET /reports/net-worth accepts period=ytd."""+ response = await client.get(+ "/api/reports/net-worth",+ params={"period": "ytd", "interval": "monthly"},+ headers=auth_headers,+ )+ assert response.status_code == 200+ data = response.json()++ assert data["trend"][0]["date"] == f"{date.today().year}-01"++@pytest.mark.asyncioasync def test_net_worth_api_validation(client, auth_headers):"""GET /reports/net-worth validates query params."""@@ -354,6 +402,14 @@ async def test_net_worth_api_validation(client, auth_headers):)assert resp.status_code == 422+ # Invalid period+ resp = await client.get(+ "/api/reports/net-worth",+ params={"period": "rolling"},+ headers=auth_headers,+ )+ assert resp.status_code == 422+# Months out of rangeresp = await client.get("/api/reports/net-worth",@@ -466,6 +522,49 @@ async def test_income_expenses_api_validation(client, auth_headers):)assert resp.status_code == 422+ resp = await client.get(+ "/api/reports/income-expenses",+ params={"period": "rolling"},+ headers=auth_headers,+ )+ assert resp.status_code == 422+++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, period=None):+ assert months == 12+ assert interval == "monthly"+ assert period == "ytd"+ 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={"period": "ytd", "interval": "monthly"},+ headers=auth_headers,+ )+ assert resp.status_code == 200+@pytest.mark.asyncioasync def test_income_expenses_api_requires_auth(client):diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 1c98d375..1d7f032d 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -931,12 +931,12 @@ export const assetGroups = {// Reportsexport const reports = {- netWorth: async (months = 12, interval = 'monthly'): Promise<ReportResponse> => {- const { data } = await api.get('/reports/net-worth', { params: { months, interval } })+ netWorth: async (months = 12, interval = 'monthly', period?: 'ytd'): Promise<ReportResponse> => {+ const { data } = await api.get('/reports/net-worth', { params: { months, interval, period } })return data},- incomeExpenses: async (months = 12, interval = 'monthly'): Promise<ReportResponse> => {- const { data } = await api.get('/reports/income-expenses', { params: { months, interval } })+ incomeExpenses: async (months = 12, interval = 'monthly', period?: 'ytd'): Promise<ReportResponse> => {+ const { data } = await api.get('/reports/income-expenses', { params: { months, interval, period } })return data},cashFlow: async (months = 6, interval = 'daily', baseline = false): Promise<ReportResponse> => {diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 2b380614..04f2f1f7 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -943,6 +943,7 @@"range3m": "3M","range6m": "6M","range1y": "1Y",+ "rangeYtd": "YTD","range12m": "12M","range2y": "2Y","intervalDaily": "D",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 9d626b6e..e963713a 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -941,6 +941,7 @@"range3m": "3M","range6m": "6M","range1y": "1A",+ "rangeYtd": "YTD","range12m": "12M","range2y": "2A","intervalDaily": "D",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex c58e58b2..8a0a0ee4 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -1009,6 +1009,7 @@"range3m": "3M","range6m": "6M","range1y": "1R",+ "rangeYtd": "YTD","range12m": "12M","range2y": "2L","intervalDaily": "D",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex a9cc9a60..fa2f9b81 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -943,6 +943,7 @@"range3m": "3M","range6m": "6M","range1y": "1A",+ "rangeYtd": "YTD","range12m": "12M","range2y": "2A","intervalDaily": "D",diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsxindex 2b006a2c..128be0b8 100644--- a/frontend/src/pages/reports.tsx+++ b/frontend/src/pages/reports.tsx@@ -42,10 +42,11 @@ function formatCompact(value: number, currency = 'USD', locale = 'en-US') {const COMPOSITION_TOP_N = 6-type RangeOption = { key: string; months: number }+type RangeOption = { key: string; months: number; period?: 'ytd' }const HISTORICAL_RANGE_OPTIONS: readonly RangeOption[] = [{ key: '6m', months: 6 },+ { key: 'ytd', months: 12, period: 'ytd' },{ key: '1y', months: 12 },{ key: '2y', months: 24 },]@@ -80,6 +81,7 @@ const RANGE_LABELS: Record<string, string> = {'3m': 'range3m','6m': 'range6m','1y': 'range1y',+ ytd: 'rangeYtd','12m': 'range12m','2y': 'range2y',}@@ -87,13 +89,13 @@ const RANGE_LABELS: Record<string, string> = {interface ReportTab {key: stringlabelKey: string- fetch: (months: number, interval: string) => Promise<ReportResponse>+ fetch: (months: number, interval: string, period?: 'ytd') => Promise<ReportResponse>enabled: boolean}const REPORT_TABS: ReportTab[] = [- { key: 'net_worth', labelKey: 'reports.netWorth', fetch: (m, i) => reports.netWorth(m, i), enabled: true },- { key: 'income_expenses', labelKey: 'reports.incomeExpenses', fetch: (m, i) => reports.incomeExpenses(m, i), enabled: true },+ { key: 'net_worth', labelKey: 'reports.netWorth', fetch: (m, i, p) => reports.netWorth(m, i, p), enabled: true },+ { key: 'income_expenses', labelKey: 'reports.incomeExpenses', fetch: (m, i, p) => reports.incomeExpenses(m, i, p), enabled: true },{ key: 'cash_flow', labelKey: 'reports.cashFlow', fetch: (m, i) => reports.cashFlow(m, i), enabled: true },]@@ -104,7 +106,7 @@ export default function ReportsPage() {const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = useDisplayLocale()- const [months, setMonths] = useState(12)+ const [rangeKey, setRangeKey] = useState('1y')const [interval, setInterval] = useState('monthly')const [activeTab, setActiveTab] = useState('net_worth')const [compositionView, setCompositionView] = useState<string>('summary')@@ -117,6 +119,9 @@ export default function ReportsPage() {const isCashFlow = activeTab === 'cash_flow'const rangeOptions = isCashFlow ? FORWARD_RANGE_OPTIONS : HISTORICAL_RANGE_OPTIONSconst intervalOptions = isCashFlow ? CASH_FLOW_INTERVAL_OPTIONS : HISTORICAL_INTERVAL_OPTIONS+ const selectedRange = rangeOptions.find((r) => r.key === rangeKey) ?? rangeOptions[0]+ const months = selectedRange.months+ const period = selectedRange.periodconst handleSelectTab = (key: string) => {setActiveTab(key)@@ -124,8 +129,8 @@ export default function ReportsPage() {setSparklinePage(0)// Clamp months/interval to options supported by the new tabconst nextRanges = key === 'cash_flow' ? FORWARD_RANGE_OPTIONS : HISTORICAL_RANGE_OPTIONS- if (!nextRanges.some((r) => r.months === months)) {- setMonths(key === 'cash_flow' ? 6 : 12)+ if (!nextRanges.some((r) => r.key === rangeKey)) {+ setRangeKey(key === 'cash_flow' ? '6m' : '1y')}const nextIntervals = key === 'cash_flow' ? CASH_FLOW_INTERVAL_OPTIONS : HISTORICAL_INTERVAL_OPTIONSif (!nextIntervals.some((i) => i.value === interval)) {@@ -134,11 +139,11 @@ export default function ReportsPage() {}const { data, isLoading } = useQuery<ReportResponse>({- queryKey: ['reports', activeTab, months, interval, isCashFlow ? cashFlowBaseline : false],+ queryKey: ['reports', activeTab, rangeKey, months, period ?? null, interval, isCashFlow ? cashFlowBaseline : false],queryFn: () =>isCashFlow? reports.cashFlow(months, interval, cashFlowBaseline)- : currentTab.fetch(months, interval),+ : currentTab.fetch(months, interval, period),enabled: currentTab.enabled,})@@ -277,9 +282,9 @@ export default function ReportsPage() {{rangeOptions.map((opt) => (<buttonkey={opt.key}- onClick={() => setMonths(opt.months)}+ onClick={() => setRangeKey(opt.key)}className={`px-3 py-1.5 text-xs font-semibold transition-colors ${- months === opt.months+ rangeKey === opt.key? 'bg-primary text-primary-foreground': 'text-muted-foreground hover:text-foreground hover:bg-muted/50'}`}