A local-first personal finance app
[AI] Add tracking budget forecast mode (#7884)
Sebastián Maluk8af35d71703b
diff --git a/packages/desktop-client/e2e/page-models/budget-page.ts b/packages/desktop-client/e2e/page-models/budget-page.tsindex 300d823a02..13e0947253 100644--- a/packages/desktop-client/e2e/page-models/budget-page.ts+++ b/packages/desktop-client/e2e/page-models/budget-page.ts@@ -7,6 +7,8 @@ export class BudgetPage {readonly budgetSummary: Locator;readonly budgetTable: Locator;readonly budgetTableTotals: Locator;+ readonly selectedMonthButton: Locator;+ readonly nextMonthButton: Locator;constructor(page: Page) {this.page = page;@@ -14,6 +16,8 @@ export class BudgetPage {this.budgetSummary = page.getByTestId('budget-summary');this.budgetTable = page.getByTestId('budget-table');this.budgetTableTotals = this.budgetTable.getByTestId('budget-totals');+ this.selectedMonthButton = page.getByTestId('selected-budget-month');+ this.nextMonthButton = page.getByTitle('Next month');}/**@@ -69,8 +73,66 @@ export class BudgetPage {};}- async showMoreMonths() {- await this.page.getByTestId('calendar-icon').first().click();+ async setBudgetedAmount(+ categoryName: string,+ amount: string,+ monthIndex = 0,+ ) {+ const row = this.budgetTable+ .getByTestId('row')+ .filter({ hasText: categoryName })+ .first();+ const budgetCell = row.getByTestId('budget').nth(monthIndex);++ await budgetCell.click();+ const input = budgetCell.locator('input');+ await input.waitFor({ state: 'visible' });+ await input.fill(amount);+ await input.press('Enter');+ }++ async getSelectedMonth() {+ const selectedMonth =+ await this.selectedMonthButton.getAttribute('data-month');++ if (!selectedMonth) {+ throw new Error('Failed to get the selected month.');+ }++ return selectedMonth;+ }++ async #waitForNewMonthToLoad({+ currentMonth,+ errorMessage,+ maxAttempts = 3,+ }: {+ currentMonth: string;+ errorMessage: string;+ maxAttempts: number;+ }) {+ for (let attempt = 0; attempt < maxAttempts; attempt++) {+ const newMonth = await this.getSelectedMonth();+ if (newMonth !== currentMonth) {+ return newMonth;+ }+ await this.page.waitForTimeout(500);+ }++ throw new Error(errorMessage);+ }++ async goToNextMonth({ maxAttempts = 3 }: { maxAttempts?: number } = {}) {+ const currentMonth = await this.getSelectedMonth();++ await this.nextMonthButton.click();++ return await this.#waitForNewMonthToLoad({+ currentMonth,+ maxAttempts,+ errorMessage:+ 'Failed to navigate to the next month after maximum attempts.',+ });}async getBalanceForRow(idx: number) {diff --git a/packages/desktop-client/e2e/page-models/navigation.ts b/packages/desktop-client/e2e/page-models/navigation.tsindex a457161acb..8777e7f0f4 100644--- a/packages/desktop-client/e2e/page-models/navigation.ts+++ b/packages/desktop-client/e2e/page-models/navigation.ts@@ -2,6 +2,7 @@ import type { Locator, Page } from '@playwright/test';import { AccountPage } from './account-page';import { BankSyncPage } from './bank-sync-page';+import { BudgetPage } from './budget-page';import { PayeesPage } from './payees-page';import { ReportsPage } from './reports-page';import { RulesPage } from './rules-page';@@ -84,6 +85,14 @@ export class Navigation {return new ReportsPage(this.page);}+ async goToBudgetPage() {+ await this.page.getByRole('link', { name: 'Budget', exact: true }).click();++ const budgetPage = new BudgetPage(this.page);+ await budgetPage.waitFor({ state: 'visible' });+ return budgetPage;+ }+async goToSchedulesPage() {await this.page.getByRole('link', { name: 'Schedules' }).click();diff --git a/packages/desktop-client/e2e/page-models/reports-page.ts b/packages/desktop-client/e2e/page-models/reports-page.tsindex da63084a2e..17dfac45e8 100644--- a/packages/desktop-client/e2e/page-models/reports-page.ts+++ b/packages/desktop-client/e2e/page-models/reports-page.ts@@ -87,6 +87,22 @@ export class ReportsPage {.waitFor({ state: 'visible' });}+ async selectForecastSource(+ source: 'Scheduled transactions' | 'Tracking budget',+ ) {+ await this.pageContent+ .getByRole('button', {+ name: /^(Scheduled transactions|Tracking budget)$/,+ })+ .click();+ const option = this.page.getByRole('button', { name: source });+ await option.waitFor({ state: 'visible' });+ await option.click();+ await this.pageContent+ .getByRole('button', { name: source })+ .waitFor({ state: 'visible' });+ }+async addWidget(widgetName: string) {await this.pageContent.getByRole('button', { name: 'Add new widget' })diff --git a/packages/desktop-client/e2e/reports.test.ts b/packages/desktop-client/e2e/reports.test.tsindex 9fcc9331f3..b6d79adf87 100644--- a/packages/desktop-client/e2e/reports.test.ts+++ b/packages/desktop-client/e2e/reports.test.ts@@ -6,7 +6,9 @@ import type { CustomReportPage } from './page-models/custom-report-page';import { Navigation } from './page-models/navigation';import type { ReportsPage } from './page-models/reports-page';-test.describe.parallel('Reports', () => {+test.describe('Reports', () => {+ test.describe.configure({ mode: 'serial' });+let page: Page;let navigation: Navigation;let reportsPage: ReportsPage;@@ -75,9 +77,29 @@ test.describe.parallel('Reports', () => {await expect(page).toMatchThemeScreenshots();});++ test('loads tracking budget forecast report', async () => {+ const settingsPage = await navigation.goToSettingsPage();+ await settingsPage.useBudgetType('Tracking');++ const budgetPage = await navigation.goToBudgetPage();+ await budgetPage.goToNextMonth();+ await budgetPage.setBudgetedAmount('Food', '1200', 0);+ await budgetPage.goToNextMonth();+ await budgetPage.setBudgetedAmount('Food', '1200', 0);+ await budgetPage.goToNextMonth();+ await budgetPage.setBudgetedAmount('Food', '1200', 0);++ reportsPage = await navigation.goToReportsPage();+ await reportsPage.waitToLoad();+ await reportsPage.goToBalanceForecastPage();+ await reportsPage.selectForecastSource('Tracking budget');++ await expect(page).toMatchThemeScreenshots();+ });});- test.describe.parallel('custom reports', () => {+ test.describe('custom reports', () => {let customReportPage: CustomReportPage;test.beforeEach(async () => {diff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-1-chromium-linux.pngnew file mode 100644index 0000000000..47bf78bb62Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-2-chromium-linux.pngnew file mode 100644index 0000000000..8291ecd524Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-3-chromium-linux.pngnew file mode 100644index 0000000000..22fdb744bfBinary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-3-chromium-linux.png differdiff --git a/packages/desktop-client/src/components/budget/MonthPicker.tsx b/packages/desktop-client/src/components/budget/MonthPicker.tsxindex 30b9cc0c69..bdf67d4ae2 100644--- a/packages/desktop-client/src/components/budget/MonthPicker.tsx+++ b/packages/desktop-client/src/components/budget/MonthPicker.tsx@@ -151,6 +151,8 @@ export const MonthPicker = ({return (<Viewkey={month}+ data-testid={selected ? 'selected-budget-month' : undefined}+ data-month={selected ? month : undefined}style={{alignItems: 'center',padding: '3px 3px',diff --git a/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsx b/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsxindex dc60e1d94d..d2c12fa39f 100644--- a/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsx+++ b/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsx@@ -15,6 +15,7 @@ import type {RuleConditionEntity,TimeFrame,} from '@actual-app/core/types/models';+import type { ForecastSource } from '@actual-app/core/types/models/forecast';import * as d from 'date-fns';import {CartesianGrid,@@ -41,6 +42,7 @@ import { useFormat } from '#hooks/useFormat';import { useLocale } from '#hooks/useLocale';import { usePrivacyMode } from '#hooks/usePrivacyMode';import { useRuleConditionFilters } from '#hooks/useRuleConditionFilters';+import { useSyncedPref } from '#hooks/useSyncedPref';import { addNotification } from '#notifications/notificationsSlice';import { useDispatch } from '#redux';@@ -78,6 +80,8 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {const locale = useLocale();const dispatch = useDispatch();const { data: accounts = [] } = useAccounts();+ const [budgetTypePref] = useSyncedPref('budgetType');+ const budgetType = budgetTypePref === 'tracking' ? 'tracking' : 'envelope';const {conditions,@@ -111,6 +115,19 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {const [granularity, setGranularity] = useState<'Daily' | 'Monthly'>(widget?.meta?.granularity ?? 'Monthly',);+ const [source, setSource] = useState<ForecastSource>(+ widget?.meta?.source === 'tracking-budget' && budgetType === 'tracking'+ ? 'tracking-budget'+ : 'schedules',+ );+ const isTrackingBudgetForecast = source === 'tracking-budget';++ useEffect(() => {+ if (budgetType !== 'tracking' && source === 'tracking-budget') {+ setSource('schedules');+ }+ }, [budgetType, source]);+const selectedAccountIds = useMemo(() => widget?.meta?.accounts ?? accounts.map(a => a.id),[accounts, widget?.meta?.accounts],@@ -125,12 +142,19 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {isPlaceholderData,isPending: isLoading,} = useBalanceForecast({- accountIds: widget ? selectedAccountIds : undefined,- conditions,- conditionsOp,+ accountIds: isTrackingBudgetForecast+ ? undefined+ : widget+ ? selectedAccountIds+ : undefined,+ conditions: isTrackingBudgetForecast ? undefined : conditions,+ conditionsOp: isTrackingBudgetForecast ? undefined : conditionsOp,startDate,endDate,- includeAccountlessSchedules: widget?.meta?.accounts === undefined,+ includeAccountlessSchedules: isTrackingBudgetForecast+ ? undefined+ : widget?.meta?.accounts === undefined,+ source,enabled: hasMonthOptions,});const errorMessage =@@ -140,7 +164,7 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {? t('Failed to load forecast'): null;const normalizedForecastData = forecastData ?? null;- const hasFilters = conditions.length > 0;+ const hasFilters = !isTrackingBudgetForecast && conditions.length > 0;const committedChartRange = useRef({ start, end });async function onSaveWidget() {@@ -156,7 +180,8 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {conditionsOp,startDate: start,endDate: end,- granularity,+ granularity: isTrackingBudgetForecast ? 'Monthly' : granularity,+ source,timeFrame: {start,end,@@ -252,6 +277,13 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {}};+ function onSourceChange(newSource: ForecastSource) {+ setSource(newSource);+ if (newSource === 'tracking-budget') {+ setGranularity('Monthly');+ }+ }+const chartRange = isPlaceholderData? committedChartRange.current: { start, end };@@ -298,47 +330,85 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {const showsTodayReferenceLine = chartData.some(dataPoint => dataPoint.date === todayReferenceDate,);+ const headerInlineContent = (+ <View style={{ flexDirection: 'row', gap: 10 }}>+ {budgetType === 'tracking' && (+ <Select+ value={source}+ onChange={onSourceChange}+ options={[+ ['schedules', t('Scheduled transactions')],+ ['tracking-budget', t('Tracking budget')],+ ]}+ />+ )}+ <Select+ value={granularity}+ onChange={setGranularity}+ disabled={isTrackingBudgetForecast}+ options={[+ ['Monthly', t('Monthly')],+ ['Daily', t('Daily')],+ ]}+ />+ </View>+ );+ const headerChildren = widget ? (+ <Button variant="primary" onPress={onSaveWidget}>+ <Trans>Save widget</Trans>+ </Button>+ ) : null;return (<Pageheader={<PageHeader title={<Trans>Balance Forecast</Trans>} />}padding={0}>- <Header- allMonths={allMonths}- start={start}- end={end}- earliestTransaction={earliestTransaction}- latestTransaction={- allMonths[0]?.name ?? monthUtils.addMonths(currentMonth, 24)- }- mode={mode}- onChangeDates={onChangeDates}- filters={conditions}- onApply={onApplyFilter}- onUpdateFilter={onUpdateFilter}- onDeleteFilter={onDeleteFilter}- conditionsOp={conditionsOp}- onConditionsOpChange={onConditionsOpChange}- showFutureRange- hideModeToggle- inlineContent={- <Select- value={granularity}- onChange={setGranularity}- options={[- ['Monthly', t('Monthly')],- ['Daily', t('Daily')],- ]}- />- }- >- {widget && (- <Button variant="primary" onPress={onSaveWidget}>- <Trans>Save widget</Trans>- </Button>- )}- </Header>+ {isTrackingBudgetForecast ? (+ <Header+ allMonths={allMonths}+ start={start}+ end={end}+ earliestTransaction={earliestTransaction}+ latestTransaction={+ forecastData?.forecastEndDate+ ? monthUtils.monthFromDate(forecastData.forecastEndDate)+ : (allMonths[0]?.name ?? monthUtils.addMonths(currentMonth, 24))+ }+ mode={mode}+ onChangeDates={onChangeDates}+ showFutureRange+ hideModeToggle+ inlineContent={headerInlineContent}+ >+ {headerChildren}+ </Header>+ ) : (+ <Header+ allMonths={allMonths}+ start={start}+ end={end}+ earliestTransaction={earliestTransaction}+ latestTransaction={+ forecastData?.forecastEndDate+ ? monthUtils.monthFromDate(forecastData.forecastEndDate)+ : (allMonths[0]?.name ?? monthUtils.addMonths(currentMonth, 24))+ }+ mode={mode}+ onChangeDates={onChangeDates}+ filters={conditions}+ onApply={onApplyFilter}+ onUpdateFilter={onUpdateFilter}+ onDeleteFilter={onDeleteFilter}+ conditionsOp={conditionsOp}+ onConditionsOpChange={onConditionsOpChange}+ showFutureRange+ hideModeToggle+ inlineContent={headerInlineContent}+ >+ {headerChildren}+ </Header>+ )}<Viewstyle={{@@ -538,7 +608,12 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {color: theme.pageTextLight,}}>- {scheduledOccurrenceCount === 0 ? (+ {isTrackingBudgetForecast ? (+ <Trans>+ Tracking budget forecast uses on-budget balance plus monthly+ budgeted income minus budgeted expenses.+ </Trans>+ ) : scheduledOccurrenceCount === 0 ? (<Trans>This range shows posted transactions only; no scheduledoccurrences fall in it.@@ -577,7 +652,7 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {)}</div>- {!errorMessage && (+ {!errorMessage && !isTrackingBudgetForecast && (<divstyle={{ marginTop: 20, fontSize: 12, color: theme.pageTextLight }}>diff --git a/packages/desktop-client/src/components/reports/reports/BalanceForecastCard.tsx b/packages/desktop-client/src/components/reports/reports/BalanceForecastCard.tsxindex 93ecf646d3..3a2c2f14b4 100644--- a/packages/desktop-client/src/components/reports/reports/BalanceForecastCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/BalanceForecastCard.tsx@@ -29,6 +29,7 @@ import { calculateTimeRange } from '#components/reports/reportRanges';import { useDashboardWidgetCopyMenu } from '#components/reports/useDashboardWidgetCopyMenu';import { useBalanceForecast } from '#hooks/useBalanceForecast';import { useFormat } from '#hooks/useFormat';+import { useSyncedPref } from '#hooks/useSyncedPref';import {buildBalanceForecastChartData,@@ -58,6 +59,13 @@ export function BalanceForecastCard({}: BalanceForecastCardProps) {const { t } = useTranslation();const format = useFormat();+ const [budgetTypePref] = useSyncedPref('budgetType');+ const budgetType = budgetTypePref === 'tracking' ? 'tracking' : 'envelope';+ const source =+ meta?.source === 'tracking-budget' && budgetType === 'tracking'+ ? 'tracking-budget'+ : 'schedules';+ const isTrackingBudgetForecast = source === 'tracking-budget';const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =useDashboardWidgetCopyMenu(onCopy);@@ -88,12 +96,15 @@ export function BalanceForecastCard({isPlaceholderData,isPending: isLoading,} = useBalanceForecast({- accountIds: selectedAccountIds,- conditions: meta?.conditions,- conditionsOp: meta?.conditionsOp,+ accountIds: isTrackingBudgetForecast ? undefined : selectedAccountIds,+ conditions: isTrackingBudgetForecast ? undefined : meta?.conditions,+ conditionsOp: isTrackingBudgetForecast ? undefined : meta?.conditionsOp,startDate,endDate,- includeAccountlessSchedules: meta?.accounts === undefined,+ includeAccountlessSchedules: isTrackingBudgetForecast+ ? undefined+ : meta?.accounts === undefined,+ source,});const errorMessage =error instanceof Error@@ -137,7 +148,8 @@ export function BalanceForecastCard({const scheduledOccurrenceCount = countForecastScheduledOccurrences(normalizedForecastData,);- const hasFilters = (meta?.conditions?.length ?? 0) > 0;+ const hasFilters =+ !isTrackingBudgetForecast && (meta?.conditions?.length ?? 0) > 0;return (<ReportCard@@ -347,7 +359,12 @@ export function BalanceForecastCard({color: theme.pageTextLight,}}>- {scheduledOccurrenceCount === 0 ? (+ {isTrackingBudgetForecast ? (+ <Trans>+ Forecast = starting balance + budgeted income - budgeted+ expenses+ </Trans>+ ) : scheduledOccurrenceCount === 0 ? (hasFilters ? (<Trans>Filtered running total only; no scheduled occurrences indiff --git a/packages/desktop-client/src/hooks/useBalanceForecast.test.ts b/packages/desktop-client/src/hooks/useBalanceForecast.test.tsnew file mode 100644index 0000000000..2955ca9f55--- /dev/null+++ b/packages/desktop-client/src/hooks/useBalanceForecast.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest';++import { buildBalanceForecastRequest } from './useBalanceForecast';++describe('buildBalanceForecastRequest', () => {+ it('keeps schedule forecast filters and account selection', () => {+ expect(+ buildBalanceForecastRequest({+ accountIds: ['acct'],+ conditions: [{ field: 'account', op: 'is', value: 'acct' }],+ conditionsOp: 'and',+ startDate: '2024-03-01',+ endDate: '2024-03-31',+ includeAccountlessSchedules: true,+ source: 'schedules',+ }),+ ).toEqual({+ accountIds: ['acct'],+ conditions: [{ field: 'account', op: 'is', value: 'acct' }],+ conditionsOp: 'and',+ startDate: '2024-03-01',+ endDate: '2024-03-31',+ includeAccountlessSchedules: true,+ source: 'schedules',+ });+ });++ it('omits tracking budget filters and account selection when undefined', () => {+ expect(+ buildBalanceForecastRequest({+ startDate: '2024-03-01',+ endDate: '2024-03-31',+ source: 'tracking-budget',+ }),+ ).toEqual({+ startDate: '2024-03-01',+ endDate: '2024-03-31',+ source: 'tracking-budget',+ });+ });++ it('defaults to schedules when source is omitted', () => {+ expect(+ buildBalanceForecastRequest({+ startDate: '2024-03-01',+ endDate: '2024-03-31',+ }),+ ).toEqual({+ startDate: '2024-03-01',+ endDate: '2024-03-31',+ source: 'schedules',+ });+ });+});diff --git a/packages/desktop-client/src/hooks/useBalanceForecast.ts b/packages/desktop-client/src/hooks/useBalanceForecast.tsindex 82636836f5..96f9bca5da 100644--- a/packages/desktop-client/src/hooks/useBalanceForecast.ts+++ b/packages/desktop-client/src/hooks/useBalanceForecast.ts@@ -1,6 +1,9 @@import { send } from '@actual-app/core/platform/client/connection';import type { RuleConditionEntity } from '@actual-app/core/types/models';-import type { ForecastResult } from '@actual-app/core/types/models/forecast';+import type {+ ForecastResult,+ ForecastSource,+} from '@actual-app/core/types/models/forecast';import { keepPreviousData, useQuery } from '@tanstack/react-query';type UseBalanceForecastParams = {@@ -10,9 +13,32 @@ type UseBalanceForecastParams = {startDate: string;endDate: string;includeAccountlessSchedules?: boolean;+ source?: ForecastSource;enabled?: boolean;};+export function buildBalanceForecastRequest({+ accountIds,+ conditions,+ conditionsOp,+ startDate,+ endDate,+ includeAccountlessSchedules,+ source = 'schedules',+}: UseBalanceForecastParams) {+ return Object.fromEntries(+ Object.entries({+ accountIds,+ conditions,+ conditionsOp,+ startDate,+ endDate,+ includeAccountlessSchedules,+ source,+ }).filter(([, value]) => value !== undefined),+ );+}+export function useBalanceForecast({accountIds,conditions,@@ -20,6 +46,7 @@ export function useBalanceForecast({startDate,endDate,includeAccountlessSchedules,+ source = 'schedules',enabled = true,}: UseBalanceForecastParams) {return useQuery({@@ -32,17 +59,22 @@ export function useBalanceForecast({startDate,endDate,includeAccountlessSchedules: includeAccountlessSchedules ?? false,+ source,},],queryFn: async (): Promise<ForecastResult> =>- send('forecast/generate', {- accountIds,- conditions,- conditionsOp,- startDate,- endDate,- includeAccountlessSchedules,- }),+ send(+ 'forecast/generate',+ buildBalanceForecastRequest({+ accountIds,+ conditions,+ conditionsOp,+ startDate,+ endDate,+ includeAccountlessSchedules,+ source,+ }),+ ),placeholderData: keepPreviousData,enabled,});diff --git a/packages/docs/docs/experimental/balance-forecast-report.md b/packages/docs/docs/experimental/balance-forecast-report.mdindex 70f1ed39f0..d9504dc893 100644--- a/packages/docs/docs/experimental/balance-forecast-report.md+++ b/packages/docs/docs/experimental/balance-forecast-report.md@@ -4,7 +4,7 @@## What it is-The Balance Forecast report projects future account balances from your posted transaction history and upcoming scheduled transactions. Use it to spot possible shortfalls, compare date ranges, and see how scheduled income, bills, and transfers may affect your balances over time.+The Balance Forecast report projects future balances from posted transaction history, upcoming scheduled transactions, or Tracking Budget plans. Use it to spot possible shortfalls, compare date ranges, and see how planned income and expenses may affect your balances over time.@@ -12,15 +12,19 @@ The Balance Forecast report projects future account balances from your posted trThe report starts by resolving the selected accounts, filters, and forecast date range. It then calculates a starting balance from posted transactions before the forecast begins.-For future dates, Actual expands scheduled transactions into simulated occurrences up to the forecast end date. Schedule rules are applied to those simulated transactions, and transfer schedules generate matching transfer legs when both sides can be assigned to accounts.+By default, Actual expands scheduled transactions into simulated occurrences up to the forecast end date. Schedule rules are applied to those simulated transactions, and transfer schedules generate matching transfer legs when both sides can be assigned to accounts.For each forecast day, Actual updates the running balance with posted transactions on that day plus simulated scheduled transactions on that day. Monthly granularity shows the same running balance grouped by month.+Tracking Budget files can also use **Tracking budget** as the forecast source. This mode starts from the current on-budget balance and projects each month by adding budgeted income and subtracting budgeted expenses. It does not use schedules, account filters, or report filters, and it always uses monthly granularity.+## Important information- The forecast is only as accurate as your schedules and the assumptions they represent.- Account filters limit the forecast to the selected accounts.- Report filters affect which posted transactions and scheduled transactions are included.+- Tracking Budget forecasts are on-budget and non-account-specific.+- Planning beyond 12 months in Tracking Budget mode is future product scope.- Schedules without an account can be included when forecasting the total budget balance without an explicit account filter. They cannot be assigned to a specific real account.- Transfers are included when the forecast can resolve the relevant account information.@@ -29,7 +33,8 @@ For each forecast day, Actual updates the running balance with posted transactio- **Start / End**: pick the forecast date range.- **Quick ranges**: choose future presets from the report header.- **Granularity**: switch between monthly and daily views.-- **Filters**: use the Filter button to narrow the transactions and schedules included in the forecast.+- **Forecast source**: choose scheduled transactions, or choose Tracking Budget in Tracking Budget files.+- **Filters**: use the Filter button to narrow the transactions and schedules included in scheduled transaction forecasts. Filters are ignored when the forecast source is Tracking Budget.- **Save widget**: save the current report settings back to the dashboard widget.## Quick troubleshootingdiff --git a/packages/loot-core/src/server/forecast/app.test.ts b/packages/loot-core/src/server/forecast/app.test.tsindex 242ddad1d3..49a346fbb5 100644--- a/packages/loot-core/src/server/forecast/app.test.ts+++ b/packages/loot-core/src/server/forecast/app.test.ts@@ -1,12 +1,14 @@import MockDate from 'mockdate';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createAllBudgets } from '#server/budget/base';import * as db from '#server/db';import { loadMappings } from '#server/db/mappings';import {createSchedule as createScheduleBase,getRuleForSchedule,} from '#server/schedules/app';+import * as sheet from '#server/sheet';import { loadRules, updateRule } from '#server/transactions/transaction-rules';import type { RuleConditionEntity } from '#types/models';@@ -197,6 +199,52 @@ describe('forecast app', () => {});});+ it('generates tracking budget forecasts only for tracking budget files', async () => {+ await expect(+ generateForecast({+ source: 'tracking-budget',+ startDate: '2024-03-01',+ endDate: '2024-03-31',+ }),+ ).rejects.toThrow(+ 'Tracking budget forecasts require a Tracking Budget file.',+ );++ await sheet.loadSpreadsheet(db);+ sheet.get().meta().budgetType = 'tracking';+ await db.update('preferences', { id: 'budgetType', value: 'tracking' });+ await db.insertCategoryGroup({ id: 'expenses', name: 'Expenses' });+ await db.insertCategoryGroup({+ id: 'income',+ name: 'Income',+ is_income: 1,+ });+ await createAllBudgets();+ await db.insertAccount({ id: 'acct', name: 'Checking' });+ await db.insertTransaction({+ id: 'starting-deposit',+ account: 'acct',+ amount: 1000,+ date: '2024-01-05',+ });++ const result = await generateForecast({+ source: 'tracking-budget',+ startDate: '2024-03-01',+ endDate: '2024-03-31',+ });++ expect(result.dataPoints).toMatchObject([+ {+ date: '2024-03-31',+ balance: 1000,+ accountId: 'tracking-budget',+ accountName: 'Tracking Budget',+ transactions: [],+ },+ ]);+ });+it('ignores reconstructed schedule occurrences before today', async () => {const accountId = await db.insertAccount({ id: 'acct', name: 'Checking' });const scheduleConditions = [diff --git a/packages/loot-core/src/server/forecast/app.ts b/packages/loot-core/src/server/forecast/app.tsindex 6c5d2dfe67..8909f7e982 100644--- a/packages/loot-core/src/server/forecast/app.ts+++ b/packages/loot-core/src/server/forecast/app.ts@@ -1,7 +1,7 @@import { createApp } from '#server/app';import * as db from '#server/db';import type { RuleConditionEntity } from '#types/models';-import type { ForecastResult } from '#types/models/forecast';+import type { ForecastResult, ForecastSource } from '#types/models/forecast';import { resolveForecastAccounts } from './forecast-accounts';import type {@@ -19,6 +19,7 @@ import {FORECAST_UNASSIGNED_ACCOUNT_ID,getNormalizedSchedules,} from './forecast-schedules';+import { projectTrackingBudgetForecast } from './forecast-tracking-budget';export type ForecastRequestParams = {accountIds?: string[];@@ -27,6 +28,7 @@ export type ForecastRequestParams = {startDate?: string;endDate?: string;includeAccountlessSchedules?: boolean;+ source?: ForecastSource;};function createUnassignedForecastAccount(): AccountWithComputedBalance {@@ -59,9 +61,43 @@ export async function generateForecast({startDate,endDate,includeAccountlessSchedules,+ source = 'schedules',}: ForecastRequestParams): Promise<ForecastResult> {const includeUnassigned = includeAccountlessSchedules ?? false;const dateContext = buildForecastDateContext(startDate, endDate);++ if (source === 'tracking-budget') {+ const { value: budgetType = 'envelope' } =+ (await db.first<Pick<db.DbPreference, 'value'>>(+ `SELECT value FROM preferences WHERE id = ?`,+ ['budgetType'],+ )) ?? {};++ if (budgetType !== 'tracking') {+ throw new Error(+ 'Tracking budget forecasts require a Tracking Budget file.',+ );+ }++ const accounts = await resolveForecastAccounts({+ accountIds: undefined,+ plainConditions: [],+ resolvedConditionsOp: 'and',+ canRestrictAccounts: false,+ });+ const { dataPoints, lowestBalance } = projectTrackingBudgetForecast({+ accounts,+ dateContext,+ });++ return {+ dataPoints,+ lowestBalance,+ forecastStartDate: dateContext.forecastStartDate,+ forecastEndDate: dateContext.forecastEndDate,+ };+ }+const { filterInfo, plainConditions, resolvedConditionsOp } = buildFilterInfo(conditions,conditionsOp,@@ -141,6 +177,7 @@ export type ForecastHandlers = {startDate?: string;endDate?: string;includeAccountlessSchedules?: boolean;+ source?: ForecastSource;}) => Promise<ForecastResult>;};diff --git a/packages/loot-core/src/server/forecast/forecast-tracking-budget.test.ts b/packages/loot-core/src/server/forecast/forecast-tracking-budget.test.tsnew file mode 100644index 0000000000..705f8fc16a--- /dev/null+++ b/packages/loot-core/src/server/forecast/forecast-tracking-budget.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest';++import type { AccountWithComputedBalance } from './forecast-accounts';+import type { ForecastDateContext } from './forecast-projection';+import { projectTrackingBudgetForecast } from './forecast-tracking-budget';++const dateContext: ForecastDateContext = {+ forecastStartDate: '2024-03-01',+ forecastEndDate: '2024-05-31',+ forecastDays: [],+ firstForecastDate: '2024-03-10',+ endDateObj: new Date('2024-05-31T00:00:00'),+};++const accounts: AccountWithComputedBalance[] = [+ {+ id: 'checking',+ name: 'Checking',+ closed: 0,+ offbudget: 0,+ balance_current: 10000,+ },+ {+ id: 'investment',+ name: 'Investment',+ closed: 0,+ offbudget: 1,+ balance_current: 90000,+ },+];++describe('tracking budget forecast projection', () => {+ it('increases the forecast by budgeted income', () => {+ const result = projectTrackingBudgetForecast({+ accounts,+ dateContext: {+ ...dateContext,+ forecastEndDate: '2024-03-31',+ },+ months: [{ month: '2024-03', budgetedIncome: 5000, budgetedExpenses: 0 }],+ });++ expect(result.dataPoints).toMatchObject([+ {+ date: '2024-03-31',+ balance: 15000,+ accountId: 'tracking-budget',+ accountName: 'Tracking Budget',+ transactions: [],+ },+ ]);+ });++ it('decreases the forecast by budgeted expenses', () => {+ const result = projectTrackingBudgetForecast({+ accounts,+ dateContext: {+ ...dateContext,+ forecastEndDate: '2024-03-31',+ },+ months: [{ month: '2024-03', budgetedIncome: 0, budgetedExpenses: 3000 }],+ });++ expect(result.dataPoints[0]?.balance).toBe(7000);+ expect(result.lowestBalance).toEqual({+ date: '2024-03-31',+ balance: 7000,+ accountId: 'tracking-budget',+ accountName: 'Tracking Budget',+ });+ });++ it('accumulates income and expenses across multiple months', () => {+ const result = projectTrackingBudgetForecast({+ accounts,+ dateContext,+ months: [+ { month: '2024-03', budgetedIncome: 5000, budgetedExpenses: 3000 },+ { month: '2024-04', budgetedIncome: 4000, budgetedExpenses: 4500 },+ { month: '2024-05', budgetedIncome: 3000, budgetedExpenses: 2500 },+ ],+ });++ expect(result.dataPoints.map(point => point.balance)).toEqual([+ 12000, 11500, 12000,+ ]);+ });+});diff --git a/packages/loot-core/src/server/forecast/forecast-tracking-budget.ts b/packages/loot-core/src/server/forecast/forecast-tracking-budget.tsnew file mode 100644index 0000000000..049f5140da--- /dev/null+++ b/packages/loot-core/src/server/forecast/forecast-tracking-budget.ts@@ -0,0 +1,93 @@+import * as sheet from '#server/sheet';+import * as monthUtils from '#shared/months';+import type { ForecastDataPoint } from '#types/models/forecast';++import type { AccountWithComputedBalance } from './forecast-accounts';+import type { ForecastDateContext } from './forecast-projection';++const TRACKING_BUDGET_FORECAST_ACCOUNT_ID = 'tracking-budget';+const TRACKING_BUDGET_FORECAST_ACCOUNT_NAME = 'Tracking Budget';++type TrackingBudgetMonth = {+ month: string;+ budgetedIncome: number;+ budgetedExpenses: number;+};++function numberOrZero(value: unknown) {+ return typeof value === 'number' ? value : 0;+}++function getTrackingBudgetMonth(month: string): TrackingBudgetMonth {+ const sheetName = monthUtils.sheetForMonth(month);++ return {+ month,+ budgetedIncome: numberOrZero(+ sheet.getCellValue(sheetName, 'total-budget-income'),+ ),+ budgetedExpenses: numberOrZero(+ sheet.getCellValue(sheetName, 'total-budgeted'),+ ),+ };+}++export function projectTrackingBudgetForecast({+ accounts,+ dateContext,+ months,+}: {+ accounts: AccountWithComputedBalance[];+ dateContext: ForecastDateContext;+ months?: TrackingBudgetMonth[];+}) {+ let runningBalance = accounts.reduce(+ (sum, account) =>+ account.offbudget === 0 ? sum + account.balance_current : sum,+ 0,+ );+ const forecastStartMonth = monthUtils.monthFromDate(+ dateContext.forecastStartDate,+ );+ const forecastEndMonth = monthUtils.monthFromDate(+ dateContext.forecastEndDate,+ );+ const forecastMonths =+ months ??+ monthUtils+ .rangeInclusive(forecastStartMonth, forecastEndMonth)+ .map(getTrackingBudgetMonth);++ const dataPoints: ForecastDataPoint[] = forecastMonths.map(month => {+ runningBalance += month.budgetedIncome - month.budgetedExpenses;++ return {+ date: monthUtils.lastDayOfMonth(month.month),+ balance: runningBalance,+ accountId: TRACKING_BUDGET_FORECAST_ACCOUNT_ID,+ accountName: TRACKING_BUDGET_FORECAST_ACCOUNT_NAME,+ transactions: [],+ };+ });++ const lowestBalance = dataPoints.reduce(+ (lowest, point) => (point.balance < lowest.balance ? point : lowest),+ dataPoints[0] ?? {+ date: dateContext.forecastStartDate,+ balance: runningBalance,+ accountId: TRACKING_BUDGET_FORECAST_ACCOUNT_ID,+ accountName: TRACKING_BUDGET_FORECAST_ACCOUNT_NAME,+ transactions: [],+ },+ );++ return {+ dataPoints,+ lowestBalance: {+ date: lowestBalance.date,+ balance: lowestBalance.balance,+ accountId: lowestBalance.accountId,+ accountName: lowestBalance.accountName,+ },+ };+}diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex e374ebbb5c..20287764fb 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -1,3 +1,4 @@+import type { ForecastSource } from './forecast';import type { CustomReportEntity } from './reports';import type { RuleConditionEntity } from './rule';@@ -255,5 +256,6 @@ export type BalanceForecastWidget = AbstractWidget<conditionsOp?: 'and' | 'or';timeFrame?: TimeFrame;granularity?: 'Daily' | 'Monthly';+ source?: ForecastSource;} | null>;diff --git a/packages/loot-core/src/types/models/forecast.ts b/packages/loot-core/src/types/models/forecast.tsindex f15796214d..5269d8949f 100644--- a/packages/loot-core/src/types/models/forecast.ts+++ b/packages/loot-core/src/types/models/forecast.ts@@ -1,3 +1,5 @@+export type ForecastSource = 'schedules' | 'tracking-budget';+export type ForecastDataPoint = {date: string;balance: number;@@ -20,6 +22,7 @@ export type BalanceForecastConfig = {selectedAccounts: string[];showCombined: boolean;showIndividual: boolean;+ source?: ForecastSource;tombstone?: boolean;};diff --git a/upcoming-release-notes/7884.md b/upcoming-release-notes/7884.mdnew file mode 100644index 0000000000..f43f540977--- /dev/null+++ b/upcoming-release-notes/7884.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [samaluk]+---++Balance Forecast can now use future tracking budget entries to project balances without relying on schedules.