A local-first personal finance app
[AI] Explain the largest contributors to balance forecasts (#9208)
Sebastián Maluk4ad77e451725
diff --git a/packages/desktop-client/e2e/reports.test.ts b/packages/desktop-client/e2e/reports.test.tsindex 6286645cfd..0ebc86f57d 100644--- a/packages/desktop-client/e2e/reports.test.ts+++ b/packages/desktop-client/e2e/reports.test.ts@@ -6,6 +6,7 @@ import { ConfigurationPage } from './page-models/configuration-page';import type { CustomReportPage } from './page-models/custom-report-page';import { Navigation } from './page-models/navigation';import type { ReportsPage } from './page-models/reports-page';+import { ScheduleEditModal } from './page-models/schedule-edit-modal';test.describe('Reports', () => {test.describe.configure({ mode: 'serial' });@@ -16,7 +17,9 @@ test.describe('Reports', () => {let configurationPage: ConfigurationPage;test.beforeEach(async ({ browser }) => {- page = await browser.newPage();+ // browser.newPage does not inherit the configured context's user agent.+ // Use Actual's fixed demo dates so report screenshots remain reproducible.+ page = await browser.newPage({ userAgent: 'playwright' });navigation = new Navigation(page);configurationPage = new ConfigurationPage(page);@@ -174,6 +177,7 @@ test.describe('Reports', () => {).toBeVisible();}+ await expect(page.getByTestId('forecast-contributors')).toHaveCount(0);await selectAccounts(1, ['Capital One Checking']);await page.getByRole('button', { name: 'Add line', exact: true }).click();await page@@ -251,6 +255,73 @@ test.describe('Reports', () => {).toHaveValue('Card');});+ test('explains forecast contributors and refreshes after editing a schedule', async () => {+ test.setTimeout(120_000);+ const forecastUrl = page.url();+ const schedulesPage = await navigation.goToSchedulesPage();+ for (const [name, amount] of [+ ['Insurance', 180],+ ['Transport', 120],+ ['Gym', 50],+ ['Subscriptions', 20],+ ] satisfies Array<[string, number]>) {+ const modal = await schedulesPage.addNewSchedule();+ await modal.fill({+ scheduleName: name,+ account: 'Capital One Checking',+ amount,+ });+ await modal.add();+ await expect(modal.locator).not.toBeVisible();+ }+ await page.goto(forecastUrl);++ const breakdown = page.getByTestId('forecast-contributors');+ const outflows = breakdown.getByRole('table', {+ name: 'Scheduled outflows',+ });+ await expect(outflows.getByRole('button')).toHaveCount(5);+ await expect(+ outflows.getByRole('row').filter({ hasText: 'Wedding' }),+ ).toContainText('No account assigned');+ await expect(outflows).toContainText('Other 2 schedules');+ await expect(breakdown).toMatchThemeScreenshots();++ await breakdown+ .getByRole('button', { name: 'Show all', exact: true })+ .click();+ await expect(outflows.getByRole('button')).toHaveCount(7);+ await expect(+ outflows.getByRole('button', { name: 'Subscriptions', exact: true }),+ ).toBeVisible();+ await breakdown.getByRole('button', { name: 'Show top five' }).click();++ const wedding = outflows.getByRole('row').filter({ hasText: 'Wedding' });+ const occurrenceCount = Number(+ await wedding.getByRole('cell').nth(1).innerText(),+ );+ const originalTotal = await wedding.getByRole('cell').last().innerText();+ await wedding+ .getByRole('button', { name: 'Wedding', exact: true })+ .click();+ const editModal = new ScheduleEditModal(+ page.getByTestId('schedule-edit-modal'),+ );+ await expect(editModal.scheduleNameInput).toHaveValue('Wedding');+ await editModal.fill({ amount: 100 });+ await editModal.save();+ await expect(editModal.locator).not.toBeVisible();+ await expect(wedding.getByRole('cell').last()).not.toHaveText(+ originalTotal,+ );+ await expect(wedding.getByRole('cell').last()).toHaveText(+ (-100 * occurrenceCount).toLocaleString('en-US', {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ }),+ );+ });+test('loads tracking budget forecast report', async () => {const settingsPage = await navigation.goToSettingsPage();await settingsPage.useBudgetType('Tracking');diff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-explains-forecast-contributors-and-refreshes-after-editing-a-schedule-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-explains-forecast-contributors-and-refreshes-after-editing-a-schedule-1-chromium-linux.pngnew file mode 100644index 0000000000..3c7fc63231Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-explains-forecast-contributors-and-refreshes-after-editing-a-schedule-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-explains-forecast-contributors-and-refreshes-after-editing-a-schedule-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-explains-forecast-contributors-and-refreshes-after-editing-a-schedule-2-chromium-linux.pngnew file mode 100644index 0000000000..d182d54c3bBinary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-explains-forecast-contributors-and-refreshes-after-editing-a-schedule-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-explains-forecast-contributors-and-refreshes-after-editing-a-schedule-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-explains-forecast-contributors-and-refreshes-after-editing-a-schedule-3-chromium-linux.pngnew file mode 100644index 0000000000..73f89e6f01Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-explains-forecast-contributors-and-refreshes-after-editing-a-schedule-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-1-chromium-linux.pngindex f7c56e5c3a..c3729b1df9 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-2-chromium-linux.pngindex 33fe61d861..0d47058fb9 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-3-chromium-linux.pngindex 0d51765b0d..cf3fb2ecbe 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-1-chromium-linux.pngindex b0e315a6a7..e85dcc5a08 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-2-chromium-linux.pngindex 4fcdbe710b..a0901a1621 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-3-chromium-linux.pngindex 74630bcfaa..56f2ad088d 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-Zero-Based-Y-Axis-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-1-chromium-linux.pngindex 901e38ee2e..c164a73fd3 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-2-chromium-linux.pngindex c911548d5e..bf825180ba 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-3-chromium-linux.pngindex cffc13af46..0b1327acfc 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-1-chromium-linux.pngindex e276e33702..134031d587 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-2-chromium-linux.pngindex ad33ec12e9..75eafe795e 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-3-chromium-linux.pngindex 6987dd650d..71aed3427d 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-and-Zero-Based-Y-Axis-3-chromium-linux.png differdiff --git a/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsx b/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsxindex 45b2e4da85..7a97d187fe 100644--- a/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsx+++ b/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsx@@ -41,6 +41,7 @@ import { getCustomTick } from '#components/reports/getCustomTick';import { computePadding } from '#components/reports/graphs/util/computePadding';import { Header } from '#components/reports/Header';import { LoadingIndicator } from '#components/reports/LoadingIndicator';+import { BalanceForecastContributors } from '#components/reports/reports/BalanceForecastContributors';import { useAccounts } from '#hooks/useAccounts';import { useBalanceForecastSeries } from '#hooks/useBalanceForecast';import { useDashboardWidget } from '#hooks/useDashboardWidget';@@ -767,6 +768,17 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {</>) : null}</div>+ {!isTrackingBudgetForecast &&+ !activeSeries &&+ normalizedForecastData && (+ <BalanceForecastContributors+ forecast={normalizedForecastData}+ start={chartRange.start}+ end={chartRange.end}+ granularity={granularity}+ isUpdating={isUpdatingForecast}+ />+ )}</>) : (<divdiff --git a/packages/desktop-client/src/components/reports/reports/BalanceForecastContributors.tsx b/packages/desktop-client/src/components/reports/reports/BalanceForecastContributors.tsxnew file mode 100644index 0000000000..eb558b4225--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/BalanceForecastContributors.tsx@@ -0,0 +1,138 @@+import { Trans } from 'react-i18next';++import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import {+ getForecastRange,+ summarizeForecastContributors,+} from '@actual-app/core/shared/forecast-contributors';+import type { ForecastResult } from '@actual-app/core/types/models/forecast';++import { ForecastAmount } from '#components/reports/reports/ForecastAmount';+import { ForecastContributorsTable } from '#components/reports/reports/ForecastContributorsTable';+import { pushModal } from '#modals/modalsSlice';+import { useDispatch } from '#redux';++type BalanceForecastContributorsProps = {+ forecast: ForecastResult;+ start: string;+ end: string;+ granularity: 'Daily' | 'Monthly';+ isUpdating: boolean;+};++export function BalanceForecastContributors({+ forecast,+ start,+ end,+ granularity,+ isUpdating,+}: BalanceForecastContributorsProps) {+ const dispatch = useDispatch();+ const { startDate, endDate } = getForecastRange(start, end, granularity);+ const summary = summarizeForecastContributors(+ forecast.dataPoints,+ startDate,+ endDate,+ );+ if (!summary) {+ return null;+ }++ function onEditSchedule(id: string) {+ dispatch(pushModal({ modal: { name: 'schedule-edit', options: { id } } }));+ }++ return (+ <section+ aria-labelledby="forecast-contributors-heading"+ aria-busy={isUpdating}+ data-testid="forecast-contributors"+ style={{ marginTop: 24, opacity: isUpdating ? 0.45 : 1 }}+ >+ <h2+ id="forecast-contributors-heading"+ style={{ fontSize: 16, margin: '0 0 8px' }}+ >+ <Trans>What drives this forecast?</Trans>+ </h2>+ <View+ style={{ color: theme.pageTextLight, fontSize: 12, marginBottom: 12 }}+ >+ <Trans>+ Upcoming schedules follow this report's range and filters. Select a+ schedule to edit it. Recorded occurrences are excluded from scheduled+ changes; transfers between included accounts cancel out.+ </Trans>+ </View>+ <dl+ style={{+ display: 'flex',+ flexWrap: 'wrap',+ gap: '12px 32px',+ margin: '0 0 16px',+ }}+ >+ {[+ {+ label: <Trans>Opening balance</Trans>,+ amount: summary.openingBalance,+ },+ {+ label: <Trans>Recorded transactions (net)</Trans>,+ amount: summary.recordedNet,+ },+ {+ label: <Trans>Scheduled changes (net)</Trans>,+ amount: summary.scheduledNet,+ },+ {+ label: <Trans>Ending balance</Trans>,+ amount: summary.endingBalance,+ },+ ].map(({ label, amount }, index) => (+ <div key={index}>+ <dt+ style={{+ color: theme.pageTextLight,+ fontSize: 12,+ marginBottom: 4,+ }}+ >+ {label}+ </dt>+ <dd style={{ margin: 0 }}>+ <ForecastAmount amount={amount} />+ </dd>+ </div>+ ))}+ </dl>+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 24 }}>+ <ForecastContributorsTable+ key={`inflow-${startDate}-${endDate}`}+ direction="inflow"+ contributors={summary.inflows}+ onEditSchedule={onEditSchedule}+ isUpdating={isUpdating}+ />+ <ForecastContributorsTable+ key={`outflow-${startDate}-${endDate}`}+ direction="outflow"+ contributors={summary.outflows}+ onEditSchedule={onEditSchedule}+ isUpdating={isUpdating}+ />+ </View>+ {summary.internalTransferCount > 0 && (+ <View+ style={{ color: theme.pageTextLight, fontSize: 12, marginTop: 8 }}+ >+ <Trans count={summary.internalTransferCount}>+ {{ count: summary.internalTransferCount }} internal transfer+ occurrences have no net effect.+ </Trans>+ </View>+ )}+ </section>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/ForecastAmount.tsx b/packages/desktop-client/src/components/reports/reports/ForecastAmount.tsxnew file mode 100644index 0000000000..bc4a785b04--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/ForecastAmount.tsx@@ -0,0 +1,12 @@+import { FinancialText } from '#components/FinancialText';+import { PrivacyFilter } from '#components/PrivacyFilter';+import { useFormat } from '#hooks/useFormat';++export function ForecastAmount({ amount }: { amount: number }) {+ const format = useFormat();+ return (+ <FinancialText style={{ whiteSpace: 'nowrap' }}>+ <PrivacyFilter>{format(amount, 'financial-with-sign')}</PrivacyFilter>+ </FinancialText>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/ForecastContributorsTable.tsx b/packages/desktop-client/src/components/reports/reports/ForecastContributorsTable.tsxnew file mode 100644index 0000000000..e3606c007e--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/ForecastContributorsTable.tsx@@ -0,0 +1,188 @@+import { useState } from 'react';+import { Trans } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import type { ForecastContributor } from '@actual-app/core/shared/forecast-contributors';++import { PrivacyFilter } from '#components/PrivacyFilter';+import { ForecastAmount } from '#components/reports/reports/ForecastAmount';++type ForecastContributorsTableProps = {+ contributors: ForecastContributor[];+ direction: 'inflow' | 'outflow';+ onEditSchedule: (id: string) => void;+ isUpdating: boolean;+};++export function ForecastContributorsTable({+ contributors,+ direction,+ onEditSchedule,+ isUpdating,+}: ForecastContributorsTableProps) {+ const [showAll, setShowAll] = useState(false);+ const { isNarrowWidth } = useResponsive();+ const visible = showAll ? contributors : contributors.slice(0, 5);+ const remaining = contributors.slice(visible.length);+ const total = contributors.reduce(+ (sum, contributor) => sum + contributor.amount,+ 0,+ );++ return (+ <View style={{ minWidth: 0, flex: '1 1 360px' }}>+ <table+ style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left' }}+ >+ <caption+ style={{ textAlign: 'left', fontWeight: 600, marginBottom: 8 }}+ >+ {direction === 'inflow' ? (+ <Trans>Scheduled inflows</Trans>+ ) : (+ <Trans>Scheduled outflows</Trans>+ )}+ </caption>+ <thead>+ <tr style={{ color: theme.pageTextLight, fontSize: 12 }}>+ <th scope="col" style={{ fontWeight: 400, padding: '4px 0' }}>+ <Trans>Schedule</Trans>+ </th>+ <th+ scope="col"+ style={{+ fontWeight: 400,+ padding: '4px 8px',+ textAlign: 'right',+ }}+ >+ <Trans>Occurrences</Trans>+ </th>+ <th+ scope="col"+ style={{ fontWeight: 400, padding: '4px 0', textAlign: 'right' }}+ >+ <Trans>Net amount</Trans>+ </th>+ </tr>+ </thead>+ <tbody>+ {visible.map(contributor => (+ <tr+ key={contributor.scheduleId}+ style={{ borderTop: `1px solid ${theme.tableBorder}` }}+ >+ <td style={{ padding: '2px 0', overflowWrap: 'anywhere' }}>+ <Button+ variant="bare"+ style={{+ fontWeight: 500,+ textDecoration: 'underline',+ textUnderlineOffset: 2,+ textAlign: 'left',+ whiteSpace: 'normal',+ minHeight: isNarrowWidth ? 40 : undefined,+ }}+ isDisabled={isUpdating}+ onPress={() => onEditSchedule(contributor.scheduleId)}+ >+ <PrivacyFilter>+ {contributor.scheduleName || (+ <Trans>Unnamed schedule</Trans>+ )}+ </PrivacyFilter>+ </Button>+ {contributor.isAccountless && (+ <View style={{ color: theme.pageTextLight, fontSize: 12 }}>+ <Trans>No account assigned</Trans>+ </View>+ )}+ {contributor.isTransfer && (+ <View style={{ color: theme.pageTextLight, fontSize: 12 }}>+ <Trans>Transfer</Trans>+ </View>+ )}+ </td>+ <td style={{ textAlign: 'right', padding: '5px 8px' }}>+ {contributor.count}+ </td>+ <td style={{ textAlign: 'right', padding: '5px 0' }}>+ <ForecastAmount amount={contributor.amount} />+ </td>+ </tr>+ ))}+ {remaining.length > 0 && (+ <tr+ style={{+ borderTop: `1px solid ${theme.tableBorder}`,+ color: theme.pageTextLight,+ }}+ >+ <td style={{ padding: '8px 5px' }}>+ <Trans count={remaining.length}>+ Other {{ count: remaining.length }} schedules+ </Trans>+ </td>+ <td style={{ textAlign: 'right', padding: '8px' }}>+ {remaining.reduce(+ (sum, contributor) => sum + contributor.count,+ 0,+ )}+ </td>+ <td style={{ textAlign: 'right' }}>+ <ForecastAmount+ amount={remaining.reduce(+ (sum, contributor) => sum + contributor.amount,+ 0,+ )}+ />+ </td>+ </tr>+ )}+ {contributors.length === 0 && (+ <tr>+ <td+ colSpan={3}+ style={{ padding: '12px 0', color: theme.pageTextLight }}+ >+ <Trans>No scheduled contributions in this direction.</Trans>+ </td>+ </tr>+ )}+ </tbody>+ <tfoot>+ <tr+ style={{+ borderTop: `1px solid ${theme.tableBorder}`,+ fontWeight: 600,+ }}+ >+ <th scope="row" colSpan={2} style={{ padding: '8px 0' }}>+ <Trans>Total</Trans>+ </th>+ <td style={{ textAlign: 'right' }}>+ <ForecastAmount amount={total} />+ </td>+ </tr>+ </tfoot>+ </table>+ {contributors.length > 5 && (+ <Button+ variant="bare"+ style={{+ alignSelf: 'flex-start',+ color: theme.pageTextLink,+ minHeight: isNarrowWidth ? 40 : undefined,+ }}+ aria-expanded={showAll}+ onPress={() => setShowAll(!showAll)}+ >+ {showAll ? <Trans>Show top five</Trans> : <Trans>Show all</Trans>}+ </Button>+ )}+ </View>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.test.ts b/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.test.tsindex e4ccd0890d..dab9b8cb3b 100644--- a/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.test.ts+++ b/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.test.ts@@ -276,7 +276,7 @@ describe('buildBalanceForecastChartData', () => {});describe('countForecastScheduledOccurrences', () => {- it('counts a transfer schedule once across both account legs', () => {+ it('counts a transfer occurrence once even when rules move one account leg', () => {const forecastData = {dataPoints: [{@@ -290,11 +290,12 @@ describe('countForecastScheduledOccurrences', () => {payee: 'Transfer to savings',scheduleId: 'schedule-transfer',scheduleName: 'Transfer to savings',+ occurrenceDate: '2024-03-20',},],},{- date: '2024-03-20',+ date: '2024-03-21',balance: 250,accountId: 'savings',accountName: 'Savings',@@ -304,6 +305,7 @@ describe('countForecastScheduledOccurrences', () => {payee: 'Transfer from checking',scheduleId: 'schedule-transfer',scheduleName: 'Transfer to savings',+ occurrenceDate: '2024-03-20',},],},diff --git a/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.ts b/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.tsindex f0abcc27ca..b0ec70d146 100644--- a/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.ts+++ b/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.ts@@ -1,3 +1,4 @@+import { getForecastRange } from '@actual-app/core/shared/forecast-contributors';import * as monthUtils from '@actual-app/core/shared/months';import type { ForecastResult } from '@actual-app/core/types/models/forecast';import * as d from 'date-fns';@@ -76,12 +77,11 @@ export function buildBalanceForecastChartData({const combinedBalanceByDate = getCombinedBalanceByDate(forecastData);// Expand month-shaped bounds to full months; keep day-shaped bounds exact.- const startDay = monthUtils.isValidYearMonth(start)- ? monthUtils.firstDayOfMonth(start)- : start;- const endDay = monthUtils.isValidYearMonth(end)- ? monthUtils.lastDayOfMonth(end)- : end;+ const { startDate: startDay, endDate: endDay } = getForecastRange(+ start,+ end,+ granularity,+ );// Carry the balance forward from the latest point before the visible// range, so a day-shaped start doesn't begin the chart at zero.@@ -147,14 +147,11 @@ export function countForecastScheduledOccurrences({// The forecast query always covers whole months; only count occurrences the// chart actually shows. Daily keeps day-shaped bounds exact, Monthly widens// to full months (mirrors buildBalanceForecastChartData).- const startDay =- granularity === 'Daily' && !monthUtils.isValidYearMonth(start)- ? start- : monthUtils.firstDayOfMonth(start);- const endDay =- granularity === 'Daily' && !monthUtils.isValidYearMonth(end)- ? end- : monthUtils.lastDayOfMonth(end);+ const { startDate: startDay, endDate: endDay } = getForecastRange(+ start,+ end,+ granularity,+ );const occurrenceKeys = new Set<string>();@@ -163,7 +160,9 @@ export function countForecastScheduledOccurrences({continue;}for (const transaction of dataPoint.transactions) {- occurrenceKeys.add(`${dataPoint.date}:${transaction.scheduleId}`);+ occurrenceKeys.add(+ `${transaction.occurrenceDate ?? dataPoint.date}:${transaction.scheduleId}`,+ );}}diff --git a/packages/desktop-client/src/hooks/useBalanceForecast.ts b/packages/desktop-client/src/hooks/useBalanceForecast.tsindex b8ef5b1c88..804a6c54e9 100644--- a/packages/desktop-client/src/hooks/useBalanceForecast.ts+++ b/packages/desktop-client/src/hooks/useBalanceForecast.ts@@ -1,9 +1,12 @@-import { send } from '@actual-app/core/platform/client/connection';+import { useEffect, useEffectEvent } from 'react';++import { listen, send } from '@actual-app/core/platform/client/connection';import type { RuleConditionEntity } from '@actual-app/core/types/models';import type {ForecastSeries,ForecastSource,} from '@actual-app/core/types/models/forecast';+import type { ServerEvents } from '@actual-app/core/types/server-events';import { useQuery } from '@tanstack/react-query';type UseBalanceForecastParams = {@@ -46,7 +49,7 @@ export function useBalanceForecastSeries({}: UseBalanceForecastParams & { series?: ForecastSeries[] }) {const requests = buildBalanceForecastSeriesRequests(series, params);- return useQuery({+ const result = useQuery({queryKey: ['balance-forecast-series', requests],queryFn: () =>Promise.all(@@ -69,6 +72,31 @@ export function useBalanceForecastSeries({},enabled,});+ const onSyncEvent = useEffectEvent((event: ServerEvents['sync-event']) => {+ if (+ enabled &&+ (event.type === 'applied' || event.type === 'success') &&+ event.tables.some(table =>+ [+ 'schedules',+ 'schedules_next_date',+ 'rules',+ 'transactions',+ 'accounts',+ 'payees',+ 'payee_mapping',+ 'categories',+ 'category_groups',+ 'category_mapping',+ ].includes(table),+ )+ ) {+ void result.refetch();+ }+ });+ useEffect(() => listen('sync-event', onSyncEvent), []);++ return result;}export function buildBalanceForecastSeriesRequests(diff --git a/packages/loot-core/src/server/forecast/app.test.ts b/packages/loot-core/src/server/forecast/app.test.tsindex 49a346fbb5..c7ebee4f4c 100644--- a/packages/loot-core/src/server/forecast/app.test.ts+++ b/packages/loot-core/src/server/forecast/app.test.ts@@ -10,6 +10,7 @@ import {} from '#server/schedules/app';import * as sheet from '#server/sheet';import { loadRules, updateRule } from '#server/transactions/transaction-rules';+import { summarizeForecastContributors } from '#shared/forecast-contributors';import type { RuleConditionEntity } from '#types/models';import { generateForecast } from './app';@@ -134,6 +135,144 @@ afterEach(() => {});describe('forecast app', () => {+ it('does not project a recorded occurrence that report filters exclude', async () => {+ const account = await db.insertAccount({ id: 'acct', name: 'Checking' });+ const scheduleId = await createSchedule({+ conditions: [+ { op: 'is', field: 'account', value: account },+ { op: 'is', field: 'amount', value: -10_000 },+ {+ op: 'is',+ field: 'date',+ value: { start: '2024-03-10', frequency: 'monthly' },+ },+ ],+ });+ await db.insertTransaction({+ id: 'recorded',+ account,+ amount: -10_000,+ date: '2024-03-10',+ schedule: scheduleId,+ cleared: true,+ });+ const result = await generateForecast({+ accountIds: [account],+ startDate: '2024-03-01',+ endDate: '2024-04-30',+ conditions: [{ op: 'is', field: 'cleared', value: false }],+ });+ expect(+ summarizeForecastContributors(+ result.dataPoints,+ '2024-03-01',+ '2024-04-30',+ ),+ ).toMatchObject({+ recordedNet: 0,+ scheduledNet: -10_000,+ endingBalance: -10_000,+ outflows: [{ scheduleId, amount: -10_000, count: 1 }],+ });+ });++ it('reconciles projected and recorded occurrences without double counting', async () => {+ const account = await db.insertAccount({ id: 'acct', name: 'Checking' });+ const scheduleId = await createSchedule({+ conditions: [+ { op: 'is', field: 'account', value: account },+ { op: 'is', field: 'amount', value: 500_000 },+ {+ op: 'is',+ field: 'date',+ value: { start: '2024-03-10', frequency: 'monthly' },+ },+ ],+ });+ await db.insertTransaction({+ id: 'opening',+ account,+ amount: 100_000,+ date: '2024-02-01',+ });+ await db.insertTransaction({+ id: 'recorded',+ account,+ amount: 500_000,+ date: '2024-03-10',+ schedule: scheduleId,+ });+ const result = await generateForecast({+ accountIds: [account],+ startDate: '2024-03-01',+ endDate: '2024-04-30',+ });+ expect(+ summarizeForecastContributors(+ result.dataPoints,+ '2024-03-01',+ '2024-04-30',+ ),+ ).toMatchObject({+ openingBalance: 100_000,+ recordedNet: 500_000,+ scheduledNet: 500_000,+ endingBalance: 1_100_000,+ inflows: [{ scheduleId, amount: 500_000, count: 1 }],+ });+ });++ it('recognizes a schedule recorded on a split parent', async () => {+ const account = await db.insertAccount({ id: 'acct', name: 'Checking' });+ const scheduleId = await createSchedule({+ conditions: [+ { op: 'is', field: 'account', value: account },+ { op: 'is', field: 'amount', value: -100 },+ { op: 'is', field: 'date', value: '2024-03-10' },+ ],+ });+ await db.insertTransaction({+ id: 'parent',+ account,+ amount: -100,+ date: '2024-03-10',+ schedule: scheduleId,+ is_parent: true,+ });+ await db.insertTransaction({+ id: 'child-1',+ account,+ amount: -60,+ date: '2024-03-10',+ is_child: true,+ parent_id: 'parent',+ });+ await db.insertTransaction({+ id: 'child-2',+ account,+ amount: -40,+ date: '2024-03-10',+ is_child: true,+ parent_id: 'parent',+ });+ const result = await generateForecast({+ accountIds: [account],+ startDate: '2024-03-01',+ endDate: '2024-03-31',+ });+ expect(+ summarizeForecastContributors(+ result.dataPoints,+ '2024-03-01',+ '2024-03-31',+ ),+ ).toMatchObject({+ recordedNet: -100,+ scheduledNet: 0,+ endingBalance: -100,+ outflows: [],+ });+ });it('shows the real running balance for historical months', async () => {const accountId = await db.insertAccount({ id: 'acct', name: 'Checking' });diff --git a/packages/loot-core/src/server/forecast/app.ts b/packages/loot-core/src/server/forecast/app.tsindex 8909f7e982..4d9d99aba1 100644--- a/packages/loot-core/src/server/forecast/app.ts+++ b/packages/loot-core/src/server/forecast/app.ts@@ -18,6 +18,7 @@ import {buildFutureScheduleOccurrences,FORECAST_UNASSIGNED_ACCOUNT_ID,getNormalizedSchedules,+ getPostedScheduleTransactions,} from './forecast-schedules';import { projectTrackingBudgetForecast } from './forecast-tracking-budget';@@ -151,7 +152,7 @@ export async function generateForecast({dateContext.endDateObj,accountsById,ruleAccountsById,- transactions,+ await getPostedScheduleTransactions(schedules),);const { dataPoints, lowestBalance } = projectForecastData({accounts,diff --git a/packages/loot-core/src/server/forecast/forecast-projection.test.ts b/packages/loot-core/src/server/forecast/forecast-projection.test.tsindex 345b44a5be..aa0a31af25 100644--- a/packages/loot-core/src/server/forecast/forecast-projection.test.ts+++ b/packages/loot-core/src/server/forecast/forecast-projection.test.ts@@ -59,6 +59,7 @@ describe('forecast projection', () => {payee: 'Paycheck',scheduleId: 'sched-1',scheduleName: 'Paycheck',+ occurrenceDate: '2024-03-02',},];const filterInfo: ForecastFilterInfo = {@@ -86,7 +87,10 @@ describe('forecast projection', () => {110, 70, 70,]);expect(result.dataPoints[0].transactions).toMatchObject([- { amount: 10, scheduleId: 'sched-1' },+ { amount: 10, scheduleId: 'sched-1', occurrenceDate: '2024-03-02' },+ ]);+ expect(result.dataPoints.map(point => point.recordedAmount)).toEqual([+ 0, -40, 0,]);expect(result.lowestBalance).toEqual({date: '2024-03-03',diff --git a/packages/loot-core/src/server/forecast/forecast-projection.ts b/packages/loot-core/src/server/forecast/forecast-projection.tsindex 4ac73ab00b..755f0abeef 100644--- a/packages/loot-core/src/server/forecast/forecast-projection.ts+++ b/packages/loot-core/src/server/forecast/forecast-projection.ts@@ -2,19 +2,19 @@ import { addMonths, format } from 'date-fns';import * as monthUtils from '#shared/months';import type { TransactionEntity } from '#types/models';-import type { ForecastDataPoint, ForecastResult } from '#types/models/forecast';+import type {+ ForecastDataPoint,+ ForecastResult,+ ForecastTransaction,+} from '#types/models/forecast';import type { AccountWithComputedBalance } from './forecast-accounts';import { matchesForecastFilters } from './forecast-filters';import type { ForecastFilterInfo } from './forecast-filters';import type { ForecastScheduleOccurrence } from './forecast-schedules';+import { FORECAST_UNASSIGNED_ACCOUNT_ID } from './forecast-schedules';-type ScheduleOccurrenceSummary = {- amount: number;- payee: string;- scheduleId: string;- scheduleName: string;-};+type ScheduleOccurrenceSummary = ForecastTransaction;type ScheduleOccurrencesByAccount = Record<string,@@ -134,6 +134,10 @@ export function indexScheduleOccurrences(payee: occurrence.payee,scheduleId: occurrence.scheduleId,scheduleName: occurrence.scheduleName,+ occurrenceDate: occurrence.occurrenceDate,+ isTransfer: occurrence.transaction.transfer_id != null,+ isAccountless:+ occurrence.transaction.account === FORECAST_UNASSIGNED_ACCOUNT_ID,},);}@@ -201,12 +205,8 @@ function buildAccountForecastDataPoints(balance: runningBalance,accountId: account.id,accountName: account.name,- transactions: scheduleTxns.map(scheduleTxn => ({- amount: scheduleTxn.amount,- payee: scheduleTxn.payee,- scheduleId: scheduleTxn.scheduleId,- scheduleName: scheduleTxn.scheduleName,- })),+ recordedAmount: txDelta,+ transactions: scheduleTxns,};});}diff --git a/packages/loot-core/src/server/forecast/forecast-schedules.ts b/packages/loot-core/src/server/forecast/forecast-schedules.tsindex 0ecd7da23c..98e564404b 100644--- a/packages/loot-core/src/server/forecast/forecast-schedules.ts+++ b/packages/loot-core/src/server/forecast/forecast-schedules.ts@@ -12,6 +12,7 @@ import {indexPostedScheduleTransactions,isScheduleOccurrencePosted,} from '#shared/schedules';+import type { PostedScheduleTransaction } from '#shared/schedules';import type { RuleConditionEntity, TransactionEntity } from '#types/models';import type { RecurConfig } from '#types/models/schedule';@@ -67,6 +68,7 @@ export type ForecastScheduleOccurrence = {payee: string;scheduleId: string;scheduleName: string;+ occurrenceDate: string;};async function getSchedules() {@@ -117,6 +119,24 @@ export async function getNormalizedSchedules() {});}+export async function getPostedScheduleTransactions(schedules: ScheduleData[]) {+ if (schedules.length === 0) {+ return [];+ }+ // Posting is independent of the report filters or which transfer leg is visible.+ // Include split parents because they can hold the schedule link.+ const { data } = await aqlQuery(+ q('transactions')+ .filter({+ tombstone: false,+ schedule: { $oneof: schedules.map(schedule => schedule.id) },+ })+ .select(['schedule', 'date'])+ .options({ splits: 'all' }),+ );+ return data;+}+async function getTransferPayeesByAccountIds(accountIds: string[]) {if (accountIds.length === 0) {return new Map<string, TransferPayee>();@@ -182,7 +202,7 @@ export async function buildFutureScheduleOccurrences(endDateObj: Date,accountsById: Map<string, AccountWithComputedBalance>,ruleAccountsById: Map<string, DbAccountForRules>,- postedTransactions: TransactionEntity[],+ postedTransactions: PostedScheduleTransaction[],) {const postedByScheduleId =indexPostedScheduleTransactions(postedTransactions);@@ -197,10 +217,11 @@ export async function buildFutureScheduleOccurrences(amount: number;scheduleId: string;scheduleName: string;+ occurrenceDate: string;}> = [];for (const schedule of schedules) {- const scheduleName = schedule.name ?? 'Unknown';+ const scheduleName = schedule.name ?? '';for (const date of getFutureOccurrenceDates(schedule, endDateObj)) {if (@@ -234,6 +255,7 @@ export async function buildFutureScheduleOccurrences(amount: sourceTransaction.amount,scheduleId: schedule.id,scheduleName,+ occurrenceDate: date,});if (sourceTransaction.account === FORECAST_UNASSIGNED_ACCOUNT_ID) {@@ -296,6 +318,7 @@ export async function buildFutureScheduleOccurrences(amount: transferTransaction.amount,scheduleId: schedule.id,scheduleName,+ occurrenceDate: date,});}}@@ -325,6 +348,7 @@ export async function buildFutureScheduleOccurrences(payee: filterObject.payee?.name ?? occurrence.scheduleName,scheduleId: occurrence.scheduleId,scheduleName: occurrence.scheduleName,+ occurrenceDate: occurrence.occurrenceDate,} satisfies ForecastScheduleOccurrence;});}diff --git a/packages/loot-core/src/shared/forecast-contributors.test.ts b/packages/loot-core/src/shared/forecast-contributors.test.tsnew file mode 100644index 0000000000..cb41a1d84a--- /dev/null+++ b/packages/loot-core/src/shared/forecast-contributors.test.ts@@ -0,0 +1,277 @@+import { describe, expect, it } from 'vitest';++import type {+ ForecastDataPoint,+ ForecastTransaction,+} from '#types/models/forecast';++import {+ getForecastRange,+ summarizeForecastContributors,+} from './forecast-contributors';++function scheduled(+ scheduleId: string,+ amount: number,+ extra: Partial<ForecastTransaction> = {},+): ForecastTransaction {+ return {+ scheduleId,+ scheduleName: scheduleId,+ payee: null,+ amount,+ ...extra,+ };+}++function point(+ date: string,+ balance: number,+ transactions: ForecastTransaction[] = [],+ recordedAmount = 0,+ accountId = 'checking',+): ForecastDataPoint {+ return {+ date,+ balance,+ accountId,+ accountName: accountId,+ transactions,+ recordedAmount,+ };+}++describe('forecast contributors', () => {+ it('ranks all schedules by their total impact and reconciles first-day activity', () => {+ const summary = summarizeForecastContributors(+ [+ point(+ '2024-03-01',+ 130_000,+ [scheduled('salary', 50_000), scheduled('rent', -30_000)],+ 10_000,+ ),+ point('2024-03-15', 144_000, [+ scheduled('salary', 50_000),+ scheduled('rent', -30_000),+ ...Array.from({ length: 6 }, (_, index) =>+ scheduled(`bill-${index}`, -1_000),+ ),+ ]),+ point('2024-03-31', 139_000, [], -5_000),+ ],+ '2024-03-01',+ '2024-03-31',+ );++ expect(summary).toMatchObject({+ openingBalance: 100_000,+ endingBalance: 139_000,+ recordedNet: 5_000,+ scheduledNet: 34_000,+ });+ expect(summary?.inflows).toMatchObject([+ { scheduleId: 'salary', amount: 100_000, count: 2 },+ ]);+ expect(summary?.outflows).toHaveLength(7);+ expect(summary?.outflows[0]).toMatchObject({+ scheduleId: 'rent',+ amount: -60_000,+ count: 2,+ });+ });++ it('nets transfer legs before ranking and counts each occurrence only once', () => {+ const points = [+ point('2024-03-01', -10_000, [+ scheduled('savings', -10_000, { isTransfer: true }),+ ]),+ point(+ '2024-03-01',+ 10_000,+ [scheduled('savings', 10_000, { isTransfer: true })],+ 0,+ 'savings',+ ),+ point('2024-03-02', -20_000, [+ scheduled('savings', -10_000, { isTransfer: true }),+ ]),+ point(+ '2024-03-02',+ 20_000,+ [scheduled('savings', 10_000, { isTransfer: true })],+ 0,+ 'savings',+ ),+ ];+ expect(+ summarizeForecastContributors(points, '2024-03-01', '2024-03-02'),+ ).toMatchObject({+ inflows: [],+ outflows: [],+ scheduledNet: 0,+ internalTransferCount: 2,+ endingBalance: 0,+ });+ // An account/payee filter can leave only one leg in the chart.+ expect(+ summarizeForecastContributors(+ points.filter(p => p.accountId === 'savings'),+ '2024-03-01',+ '2024-03-02',+ ),+ ).toMatchObject({+ inflows: [+ { scheduleId: 'savings', amount: 20_000, count: 2, isTransfer: true },+ ],+ scheduledNet: 20_000,+ endingBalance: 20_000,+ });+ });++ it('nets the original occurrence when rules move transfer legs to different dates', () => {+ const points = [+ point('2024-03-01', -100, [+ scheduled('transfer', -100, {+ isTransfer: true,+ occurrenceDate: '2024-03-01',+ }),+ ]),+ point('2024-03-02', -100),+ point('2024-03-01', 0, [], 0, 'savings'),+ point(+ '2024-03-02',+ 100,+ [+ scheduled('transfer', 100, {+ isTransfer: true,+ occurrenceDate: '2024-03-01',+ }),+ ],+ 0,+ 'savings',+ ),+ ];+ expect(+ summarizeForecastContributors(points, '2024-03-01', '2024-03-02'),+ ).toMatchObject({+ inflows: [],+ outflows: [],+ scheduledNet: 0,+ internalTransferCount: 1,+ endingBalance: 0,+ });+ // Only the leg inside the selected date range contributes to its change.+ expect(+ summarizeForecastContributors(points, '2024-03-02', '2024-03-02'),+ ).toMatchObject({+ openingBalance: -100,+ scheduledNet: 100,+ endingBalance: 0,+ inflows: [{ scheduleId: 'transfer', count: 1, amount: 100 }],+ });+ });++ it('keeps schedule identities and directions distinct, including accountless occurrences', () => {+ const summary = summarizeForecastContributors(+ [+ point('2024-03-01', 100, [+ scheduled('a', 100, { scheduleName: 'Same name' }),+ scheduled('b', -100, { scheduleName: 'Same name' }),+ scheduled('a', 100, {+ scheduleName: 'Same name',+ isAccountless: true,+ }),+ ]),+ point('2024-03-02', 50, [+ scheduled('a', -50, { scheduleName: 'Same name' }),+ ]),+ ],+ '2024-03-01',+ '2024-03-02',+ );+ expect(summary?.inflows).toMatchObject([+ { scheduleId: 'a', amount: 200, count: 1, isAccountless: true },+ ]);+ expect(summary?.outflows).toMatchObject([+ { scheduleId: 'b', amount: -100 },+ { scheduleId: 'a', amount: -50 },+ ]);+ expect(summary?.scheduledNet).toBe(50);+ });++ it('uses exact daily boundaries and carries the balance before the selected start', () => {+ const summary = summarizeForecastContributors(+ [+ point('2024-03-31', 175, [scheduled('bill', -25)]),+ point('2024-03-01', 100, [scheduled('salary', 100)]),+ point('2024-03-20', 200, [], 50),+ point('2024-03-15', 150, [scheduled('salary', 50)]),+ ],+ '2024-03-15',+ '2024-03-20',+ );+ expect(summary).toMatchObject({+ openingBalance: 100,+ recordedNet: 50,+ scheduledNet: 50,+ endingBalance: 200,+ outflows: [],+ });+ });++ it('reconciles a historical range without attributing recorded transactions to schedules', () => {+ expect(+ summarizeForecastContributors(+ [point('2024-01-10', 300, [], -200)],+ '2024-01-01',+ '2024-01-31',+ ),+ ).toMatchObject({+ openingBalance: 500,+ recordedNet: -200,+ scheduledNet: 0,+ endingBalance: 300,+ inflows: [],+ outflows: [],+ });+ });++ it('does not invent provenance for empty or older forecast responses', () => {+ expect(+ summarizeForecastContributors([], '2024-03-01', '2024-03-31'),+ ).toBeNull();+ expect(+ summarizeForecastContributors(+ [+ {+ date: '2024-03-01',+ balance: 100,+ accountId: 'a',+ accountName: 'A',+ transactions: [],+ },+ ],+ '2024-03-01',+ '2024-03-31',+ ),+ ).toBeNull();+ });+});++describe('forecast range', () => {+ it('widens monthly bounds and preserves daily bounds, including leap days', () => {+ expect(getForecastRange('2024-02-10', '2024-02-20', 'Monthly')).toEqual({+ startDate: '2024-02-01',+ endDate: '2024-02-29',+ });+ expect(getForecastRange('2024-02-10', '2024-02-20', 'Daily')).toEqual({+ startDate: '2024-02-10',+ endDate: '2024-02-20',+ });+ expect(getForecastRange('2024-02', '2024-02', 'Daily')).toEqual({+ startDate: '2024-02-01',+ endDate: '2024-02-29',+ });+ });+});diff --git a/packages/loot-core/src/shared/forecast-contributors.ts b/packages/loot-core/src/shared/forecast-contributors.tsnew file mode 100644index 0000000000..e73426d7a0--- /dev/null+++ b/packages/loot-core/src/shared/forecast-contributors.ts@@ -0,0 +1,144 @@+import * as monthUtils from '#shared/months';+import type { ForecastDataPoint } from '#types/models/forecast';++export type ForecastContributor = {+ scheduleId: string;+ scheduleName: string;+ amount: number;+ count: number;+ isTransfer: boolean;+ isAccountless: boolean;+};++/** Monthly points represent complete months; Daily preserves exact day bounds. */+export function getForecastRange(+ start: string,+ end: string,+ granularity: 'Daily' | 'Monthly',+) {+ return {+ startDate:+ granularity === 'Daily' && !monthUtils.isValidYearMonth(start)+ ? start+ : monthUtils.firstDayOfMonth(start),+ endDate:+ granularity === 'Daily' && !monthUtils.isValidYearMonth(end)+ ? end+ : monthUtils.lastDayOfMonth(end),+ };+}++/** Summarize the same filtered daily points used by the chart, in integer cents. */+export function summarizeForecastContributors(+ dataPoints: ForecastDataPoint[],+ startDate: string,+ endDate: string,+) {+ const points = dataPoints.filter(+ point => point.date >= startDate && point.date <= endDate,+ );+ if (+ points.length === 0 ||+ points.some(point => point.recordedAmount === undefined)+ ) {+ // Older results and tracking-budget forecasts have no recorded provenance.+ return null;+ }++ const openingByAccount = new Map<string, { date: string; balance: number }>();+ const endingByAccount = new Map<string, ForecastDataPoint>();+ const occurrences = new Map<string, ForecastContributor>();+ let recordedNet = 0;++ for (const point of points) {+ const recordedAmount = point.recordedAmount ?? 0;+ recordedNet += recordedAmount;+ const opening = openingByAccount.get(point.accountId);+ if (!opening || point.date < opening.date) {+ openingByAccount.set(point.accountId, {+ date: point.date,+ balance:+ point.balance -+ recordedAmount -+ point.transactions.reduce(+ (sum, transaction) => sum + transaction.amount,+ 0,+ ),+ });+ }+ const ending = endingByAccount.get(point.accountId);+ if (!ending || point.date > ending.date) {+ endingByAccount.set(point.accountId, point);+ }++ for (const transaction of point.transactions) {+ // Net transfer legs only after filtering, and count each occurrence once.+ const key = JSON.stringify([+ transaction.scheduleId,+ transaction.occurrenceDate ?? point.date,+ ]);+ const occurrence = occurrences.get(key);+ if (occurrence) {+ occurrence.amount += transaction.amount;+ occurrence.isTransfer ||= transaction.isTransfer ?? false;+ occurrence.isAccountless ||= transaction.isAccountless ?? false;+ } else {+ occurrences.set(key, {+ scheduleId: transaction.scheduleId,+ scheduleName: transaction.scheduleName,+ amount: transaction.amount,+ count: 1,+ isTransfer: transaction.isTransfer ?? false,+ isAccountless: transaction.isAccountless ?? false,+ });+ }+ }+ }++ const groups = new Map<string, ForecastContributor>();+ let internalTransferCount = 0;+ for (const occurrence of occurrences.values()) {+ if (occurrence.amount === 0) {+ if (occurrence.isTransfer) {+ internalTransferCount++;+ }+ continue;+ }+ // A schedule may change direction after rules run. Keep both sides visible.+ const key = JSON.stringify([occurrence.scheduleId, occurrence.amount > 0]);+ const group = groups.get(key);+ if (group) {+ group.amount += occurrence.amount;+ group.count++;+ group.isTransfer ||= occurrence.isTransfer;+ group.isAccountless ||= occurrence.isAccountless;+ } else {+ groups.set(key, { ...occurrence });+ }+ }++ const contributors = [...groups.values()].sort(+ (a, b) =>+ Math.abs(b.amount) - Math.abs(a.amount) ||+ a.scheduleName.localeCompare(b.scheduleName) ||+ a.scheduleId.localeCompare(b.scheduleId),+ );+ return {+ openingBalance: [...openingByAccount.values()].reduce(+ (sum, point) => sum + point.balance,+ 0,+ ),+ endingBalance: [...endingByAccount.values()].reduce(+ (sum, point) => sum + point.balance,+ 0,+ ),+ recordedNet,+ scheduledNet: contributors.reduce(+ (sum, contributor) => sum + contributor.amount,+ 0,+ ),+ inflows: contributors.filter(contributor => contributor.amount > 0),+ outflows: contributors.filter(contributor => contributor.amount < 0),+ internalTransferCount,+ };+}diff --git a/packages/loot-core/src/types/models/forecast.ts b/packages/loot-core/src/types/models/forecast.tsindex dc5f456ab5..146a2fdc71 100644--- a/packages/loot-core/src/types/models/forecast.ts+++ b/packages/loot-core/src/types/models/forecast.ts@@ -16,6 +16,8 @@ export type ForecastDataPoint = {accountId: string;accountName: string;transactions: ForecastTransaction[];+ /** Net recorded activity for this day; absent for tracking-budget forecasts. */+ recordedAmount?: number;};export type ForecastTransaction = {@@ -23,6 +25,10 @@ export type ForecastTransaction = {payee: string | null;scheduleId: string;scheduleName: string;+ /** Original scheduled date, before rules can move either transfer leg. */+ occurrenceDate?: string;+ isTransfer?: boolean;+ isAccountless?: boolean;};export type BalanceForecastConfig = {diff --git a/upcoming-release-notes/balance-forecast-contributors.md b/upcoming-release-notes/balance-forecast-contributors.mdnew file mode 100644index 0000000000..034cc5d323--- /dev/null+++ b/upcoming-release-notes/balance-forecast-contributors.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [samaluk]+---++Show the largest scheduled inflows and outflows behind a balance forecast, with links to review and edit each schedule.