Skip to content

A local-first personal finance app

[AI] Automatically extend budget planning range in Tracking and Envelope modes (#9293)

Manaf3cb52596340a
diff --git a/packages/desktop-client/e2e/automatic-budget-range.test.ts b/packages/desktop-client/e2e/automatic-budget-range.test.ts
new file mode 100644
index 0000000000..9ae3bb74f5
--- /dev/null
+++ b/packages/desktop-client/e2e/automatic-budget-range.test.ts
@@ -0,0 +1,108 @@
+import type { Page } from '@playwright/test';
+
+import { expect, test } from './fixtures';
+import { BudgetPage } from './page-models/budget-page';
+import { ConfigurationPage } from './page-models/configuration-page';
+import type { MobileBudgetPage } from './page-models/mobile-budget-page';
+import { MobileNavigation } from './page-models/mobile-navigation';
+import { Navigation } from './page-models/navigation';
+
+async function setBudgetAmount(page: Page, month: string, amount: number) {
+ await page.evaluate(
+ async ({ month, amount }) => {
+ const { list } = await window.$send('get-categories');
+ const category = list.find(item => !item.is_income && !item.hidden);
+ if (!category) {
+ throw new Error('Demo budget has no expense category');
+ }
+ await window.$send('budget/budget-amount', {
+ category: category.id,
+ month,
+ amount,
+ });
+ },
+ { month, amount },
+ );
+}
+
+for (const viewport of [
+ { name: 'desktop', width: 1280, height: 900 },
+ { name: 'mobile', width: 350, height: 600 },
+]) {
+ test.describe(`Automatic budget range (${viewport.name})`, () => {
+ let page: Page;
+ let budgetPage: BudgetPage | MobileBudgetPage;
+
+ test.beforeEach(async ({ browser }) => {
+ page = await browser.newPage({ viewport });
+ await page.goto('/');
+ await new ConfigurationPage(page).createTestFile();
+ const navigation =
+ viewport.name === 'desktop'
+ ? new Navigation(page)
+ : new MobileNavigation(page);
+ budgetPage = await navigation.goToBudgetPage();
+ });
+
+ test.afterEach(async () => page.close());
+
+ test('extends after budgeting the last month and shrinks on reload', async () => {
+ const selected =
+ budgetPage instanceof BudgetPage
+ ? budgetPage.selectedMonthButton
+ : budgetPage.selectedBudgetMonthButton;
+
+ async function expectLastMonth(month: string) {
+ if (budgetPage instanceof BudgetPage) {
+ await budgetPage.nextMonthButton.click();
+ } else {
+ await expect(budgetPage.nextMonthButton).toBeDisabled();
+ }
+ await expect(selected).toHaveAttribute('data-month', month);
+ }
+
+ // The test clock is January 2017, so the default range ends 12 months later
+ for (let index = 0; index < 12; index++) {
+ await budgetPage.goToNextMonth();
+ }
+ await expectLastMonth('2018-01');
+
+ await setBudgetAmount(page, '2018-01', 200);
+ for (let index = 0; index < 3; index++) {
+ await budgetPage.goToNextMonth();
+ }
+ await expectLastMonth('2018-04');
+
+ // Clearing the amount keeps the range while the budget is open...
+ await setBudgetAmount(page, '2018-01', 0);
+ await expect(selected).toHaveAttribute('data-month', '2018-04');
+
+ // ...and shrinks it the next time the budget loads
+ await page.reload();
+ await expect(selected).toHaveAttribute('data-month', '2018-01');
+ });
+
+ if (viewport.name === 'desktop') {
+ test('keeps every displayed column inside the range', async () => {
+ await page.setViewportSize({ width: 1800, height: 900 });
+ await page.evaluate(() =>
+ window.$send('save-global-prefs', { maxMonths: 3 }),
+ );
+ await setBudgetAmount(page, '2018-01', 200);
+ await page.reload();
+
+ const selected = page.getByTestId('selected-budget-month');
+ await expect(selected).toHaveCount(3);
+ for (let index = 0; index < 14; index++) {
+ await page.getByTitle('Next month').click();
+ }
+ await expect(selected.last()).toHaveAttribute('data-month', '2018-04');
+
+ await setBudgetAmount(page, '2018-01', 0);
+ await page.reload();
+ await expect(selected.first()).toHaveAttribute('data-month', '2017-11');
+ await expect(selected.last()).toHaveAttribute('data-month', '2018-01');
+ });
+ }
+ });
+}
diff --git a/packages/desktop-client/src/budget/queries.ts b/packages/desktop-client/src/budget/queries.ts
index b5953c5dd4..215a6a6688 100644
--- a/packages/desktop-client/src/budget/queries.ts
+++ b/packages/desktop-client/src/budget/queries.ts
@@ -11,6 +11,16 @@ type CategoryViews = {
list: CategoryEntity[];
};
+export const budgetBoundsQueries = {
+ all: () => ['budget-bounds'],
+ bounds: () =>
+ queryOptions({
+ queryKey: budgetBoundsQueries.all(),
+ queryFn: () => send('get-budget-bounds'),
+ throwOnError: true,
+ }),
+};
+
export const categoryQueries = {
all: () => ['categories'],
lists: () => [...categoryQueries.all(), 'lists'],
diff --git a/packages/desktop-client/src/components/budget/DynamicBudgetTable.tsx b/packages/desktop-client/src/components/budget/DynamicBudgetTable.tsx
index 21ac27bef3..d7d0e60dc7 100644
--- a/packages/desktop-client/src/components/budget/DynamicBudgetTable.tsx
+++ b/packages/desktop-client/src/components/budget/DynamicBudgetTable.tsx
@@ -15,6 +15,7 @@ import { useGlobalPref } from '#hooks/useGlobalPref';
import { useBudgetMonthCount } from './BudgetMonthCountContext';
import { BudgetPageHeader } from './BudgetPageHeader';
import { BudgetTable } from './BudgetTable';
+import { clampMonth } from './MonthsContext';
function getNumPossibleMonths(width: number, categoryWidth: number) {
const estimatedTableWidth = width - categoryWidth;
@@ -63,21 +64,38 @@ const DynamicBudgetTable = ({
const numMonths = Math.min(numPossible, maxMonths);
const maxWidth = 200 + 100 * categoryExpandedState + 500 * numMonths;
- useEffect(() => {
- setDisplayMax(numPossible);
- }, [setDisplayMax, numPossible]);
+ // Every displayed column must stay inside the bounds, so the first
+ // column can go no later than `numMonths - 1` months before the end.
+ const latestStartMonth = monthUtils.subMonths(monthBounds.end, numMonths - 1);
- function getValidMonth(month) {
- const start = monthBounds.start;
- const end = monthUtils.subMonths(monthBounds.end, numMonths - 1);
+ function getValidMonth(month: string) {
+ return clampMonth(month, {
+ start: monthBounds.start,
+ end: latestStartMonth,
+ });
+ }
- if (month < start) {
- return start;
- } else if (month > end) {
- return end;
+ // Keep the last column in range when the bounds change (e.g. switching
+ // budget type) or more columns fit on screen.
+ useEffect(() => {
+ const validMonth = clampMonth(startMonth, {
+ start: monthBounds.start,
+ end: latestStartMonth,
+ });
+ if (validMonth !== startMonth) {
+ onMonthSelect(validMonth, numMonths);
}
- return month;
- }
+ }, [
+ monthBounds.start,
+ latestStartMonth,
+ numMonths,
+ onMonthSelect,
+ startMonth,
+ ]);
+
+ useEffect(() => {
+ setDisplayMax(numPossible);
+ }, [setDisplayMax, numPossible]);
function _onMonthSelect(month) {
onMonthSelect(getValidMonth(month), numMonths);
diff --git a/packages/desktop-client/src/components/budget/MonthsContext.tsx b/packages/desktop-client/src/components/budget/MonthsContext.tsx
index ea9bcbc011..e77b328ac7 100644
--- a/packages/desktop-client/src/components/budget/MonthsContext.tsx
+++ b/packages/desktop-client/src/components/budget/MonthsContext.tsx
@@ -20,6 +20,16 @@ export function getValidMonthBounds(
};
}
+export function clampMonth(month: string, bounds: MonthBounds) {
+ if (month < bounds.start) {
+ return bounds.start;
+ }
+ if (month > bounds.end) {
+ return bounds.end;
+ }
+ return month;
+}
+
type MonthsContextProps = {
months: string[];
type: string;
diff --git a/packages/desktop-client/src/components/budget/index.tsx b/packages/desktop-client/src/components/budget/index.tsx
index 96478614f0..845ea90b47 100644
--- a/packages/desktop-client/src/components/budget/index.tsx
+++ b/packages/desktop-client/src/components/budget/index.tsx
@@ -4,14 +4,15 @@ import type { ComponentType } from 'react';
import { styles } from '@actual-app/components/styles';
import { View } from '@actual-app/components/view';
-import { send } from '@actual-app/core/platform/client/connection';
import * as monthUtils from '@actual-app/core/shared/months';
import type {
CategoryEntity,
CategoryGroupEntity,
} from '@actual-app/core/types/models';
+import { useQuery } from '@tanstack/react-query';
import {
+ budgetBoundsQueries,
useBudgetActions,
useDeleteCategoryGroupMutation,
useDeleteCategoryMutation,
@@ -32,6 +33,7 @@ import { useSyncedPref } from '#hooks/useSyncedPref';
import { AutoSizingBudgetTable } from './DynamicBudgetTable';
import * as envelopeBudget from './envelope/EnvelopeBudgetComponents';
import { EnvelopeBudgetProvider } from './envelope/EnvelopeBudgetContext';
+import { clampMonth } from './MonthsContext';
import * as trackingBudget from './tracking/TrackingBudgetComponents';
import { TrackingBudgetProvider } from './tracking/TrackingBudgetContext';
import { prewarmAllMonths, prewarmMonth } from './util';
@@ -45,10 +47,11 @@ export function Budget() {
);
const [startMonthPref, setStartMonthPref] = useLocalPref('budget.startMonth');
const startMonth = startMonthPref || currentMonth;
- const [bounds, setBounds] = useState({
+ const { data: loadedBounds } = useQuery(budgetBoundsQueries.bounds());
+ const bounds = loadedBounds ?? {
start: startMonth,
end: startMonth,
- });
+ };
const [budgetType = 'envelope'] = useSyncedPref('budgetType');
const [maxMonthsPref] = useGlobalPref('maxMonths');
const maxMonths = maxMonthsPref || 1;
@@ -56,33 +59,28 @@ export function Budget() {
const { data: { grouped: categoryGroups } = { grouped: [] } } =
useCategories();
- const init = useEffectEvent(() => {
- async function run() {
- const { start, end } = await send('get-budget-bounds');
- setBounds({ start, end });
-
- await prewarmAllMonths(
- budgetType,
- spreadsheet,
- { start, end },
- startMonth,
- );
-
- setInitialized(true);
- }
+ // Re-runs whenever the bounds change so newly available months get warmed.
+ const init = useEffectEvent(
+ (type: typeof budgetType, monthBounds: typeof loadedBounds) => {
+ async function run() {
+ if (!monthBounds) {
+ return;
+ }
- void run();
- });
- useEffect(() => init(), []);
+ await prewarmAllMonths(
+ type,
+ spreadsheet,
+ monthBounds,
+ clampMonth(startMonth, monthBounds),
+ );
- const loadBoundBudgets = useEffectEvent(() => {
- void send('get-budget-bounds').then(({ start, end }) => {
- if (bounds.start !== start || bounds.end !== end) {
- setBounds({ start, end });
+ setInitialized(true);
}
- });
- });
- useEffect(() => loadBoundBudgets(), []);
+
+ void run();
+ },
+ );
+ useEffect(() => init(budgetType, loadedBounds), [budgetType, loadedBounds]);
const onMonthSelect = async (month, numDisplayed) => {
setStartMonthPref(month);
diff --git a/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsx b/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsx
index 073c102dfb..64510e8a95 100644
--- a/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsx
@@ -30,9 +30,11 @@ import { send } from '@actual-app/core/platform/client/connection';
import * as monthUtils from '@actual-app/core/shared/months';
import { groupById } from '@actual-app/core/shared/util';
import type { TransObjectLiteral } from '@actual-app/core/types/util';
+import { useQuery } from '@tanstack/react-query';
import { sync } from '#app/appSlice';
import {
+ budgetBoundsQueries,
useBudgetActions,
useCreateCategoryGroupMutation,
useCreateCategoryMutation,
@@ -43,6 +45,7 @@ import {
useSortCategoriesMutation,
} from '#budget';
import { closeBudget } from '#budgetfiles/budgetfilesSlice';
+import { clampMonth } from '#components/budget/MonthsContext';
import { prewarmMonth } from '#components/budget/util';
import { FinancialText } from '#components/FinancialText';
import { MobilePageHeader, Page } from '#components/Page';
@@ -89,10 +92,11 @@ export function BudgetPage() {
const currMonth = monthUtils.currentMonth();
const [startMonth = currMonth, setStartMonthPref] =
useLocalPref('budget.startMonth');
- const [monthBounds, setMonthBounds] = useState({
+ const { data: loadedBounds } = useQuery(budgetBoundsQueries.bounds());
+ const monthBounds = loadedBounds ?? {
start: startMonth,
end: startMonth,
- });
+ };
// const [editMode, setEditMode] = useState(false);
const [initialized, setInitialized] = useState(false);
const [_numberFormat] = useSyncedPref('numberFormat');
@@ -110,16 +114,23 @@ export function BudgetPage() {
useEffect(() => {
async function init() {
- const { start, end } = await send('get-budget-bounds');
- setMonthBounds({ start, end });
+ if (!loadedBounds) {
+ return;
+ }
+ // Reopening the budget or switching budget type can leave the selected
+ // month out of range.
+ const validMonth = clampMonth(startMonth, loadedBounds);
+ if (validMonth !== startMonth) {
+ setStartMonthPref(validMonth);
+ }
- await prewarmMonth(budgetType, spreadsheet, startMonth);
+ await prewarmMonth(budgetType, spreadsheet, validMonth);
setInitialized(true);
}
void init();
- }, [budgetType, startMonth, dispatch, spreadsheet]);
+ }, [budgetType, startMonth, spreadsheet, loadedBounds, setStartMonthPref]);
const onBudgetAction = useCallback(
async (month, type, args) => {
@@ -958,7 +969,7 @@ function MonthSelector({
const locale = useLocale();
const { t } = useTranslation();
const prevEnabled = month > monthBounds.start;
- const nextEnabled = month < monthUtils.subMonths(monthBounds.end, 1);
+ const nextEnabled = month < monthBounds.end;
const arrowButtonStyle = {
padding: 10,
diff --git a/packages/desktop-client/src/sync-events.test.ts b/packages/desktop-client/src/sync-events.test.ts
index e115542d43..105cc13c60 100644
--- a/packages/desktop-client/src/sync-events.test.ts
+++ b/packages/desktop-client/src/sync-events.test.ts
@@ -3,6 +3,7 @@ import type { ServerEvents } from '@actual-app/core/types/server-events';
import type { QueryClient } from '@tanstack/react-query';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { budgetBoundsQueries } from './budget';
import type { AppStore } from './redux/store';
import { dashboardQueries, reportQueries } from './reports';
import { listenForSyncEvent } from './sync-events';
@@ -60,6 +61,28 @@ describe('listenForSyncEvent', () => {
vi.clearAllMocks();
});
+ it.each([
+ 'zero_budgets',
+ 'reflect_budgets',
+ 'transactions',
+ 'categories',
+ 'preferences',
+ ])('refreshes budget bounds after %s changes', table => {
+ const { invalidateQueries } = setup();
+ publishSyncEvent(appliedEvent([table]));
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: budgetBoundsQueries.all(),
+ });
+ });
+
+ it('leaves budget bounds alone for unrelated changes', () => {
+ const { invalidateQueries } = setup();
+ publishSyncEvent(appliedEvent(['payees']));
+ expect(invalidateQueries).not.toHaveBeenCalledWith({
+ queryKey: budgetBoundsQueries.all(),
+ });
+ });
+
it('invalidates the dashboard queries when widgets sync', () => {
const { invalidateQueries } = setup();
diff --git a/packages/desktop-client/src/sync-events.ts b/packages/desktop-client/src/sync-events.ts
index fc8f0bc9ee..0769d5b5ba 100644
--- a/packages/desktop-client/src/sync-events.ts
+++ b/packages/desktop-client/src/sync-events.ts
@@ -6,7 +6,7 @@ import { t } from 'i18next';
import { accountGroupQueries } from './account-groups';
import { accountQueries } from './accounts';
import { resetSync, sync } from './app/appSlice';
-import { categoryQueries } from './budget';
+import { budgetBoundsQueries, categoryQueries } from './budget';
import {
closeAndDownloadBudget,
uploadBudget,
@@ -20,6 +20,16 @@ import type { AppStore } from './redux/store';
import { dashboardQueries, reportQueries } from './reports';
import { signOut } from './users/usersSlice';
+// Tables whose changes can move the budget's month bounds. `preferences`
+// holds the synced budget type.
+const BUDGET_BOUNDS_TABLES = [
+ 'zero_budgets',
+ 'reflect_budgets',
+ 'transactions',
+ 'categories',
+ 'preferences',
+];
+
// Notifications for sync events that can fire during budget load
const syncNotifications: Partial<
Record<ServerEvents['sync-event']['type'], () => Notification>
@@ -108,6 +118,15 @@ export function listenForSyncEvent(store: AppStore, queryClient: QueryClient) {
void store.dispatch(loadPrefs());
}
+ // Budget amounts, transactions, deleted categories and the budget type
+ // all change which months are available. Covers local edits, undo and
+ // incoming sync.
+ if (tables.some(table => BUDGET_BOUNDS_TABLES.includes(table))) {
+ void queryClient.invalidateQueries({
+ queryKey: budgetBoundsQueries.all(),
+ });
+ }
+
if (
tables.includes('categories') ||
tables.includes('category_groups') ||
diff --git a/packages/loot-core/src/server/budget/base.test.ts b/packages/loot-core/src/server/budget/base.test.ts
index 72f47286bc..83ee8394c6 100644
--- a/packages/loot-core/src/server/budget/base.test.ts
+++ b/packages/loot-core/src/server/budget/base.test.ts
@@ -3,13 +3,127 @@ import * as sheet from '#server/sheet';
// @ts-strict-ignore
import * as monthUtils from '#shared/months';
-import { createAllBudgets } from './base';
+import { setBudget, setCategoryCarryover } from './actions';
+import { createAllBudgets, getBudgetRange } from './base';
beforeEach(() => {
return global.emptyDatabase()();
});
+describe('getBudgetRange', () => {
+ it('keeps 3 months before the start and 12 months after the end', () => {
+ const { start, end } = getBudgetRange('2026-01', '2026-10');
+ expect(start).toBe('2025-10');
+ expect(end).toBe('2027-10');
+ });
+
+ it('ignores allocations inside the minimum range', () => {
+ expect(getBudgetRange('2026-10', '2026-10', '2027-05').end).toBe('2027-10');
+ });
+
+ it('extends 3 months past the latest allocation', () => {
+ expect(getBudgetRange('2026-10', '2026-10', '2028-12').end).toBe('2029-03');
+ });
+
+ it('never extends more than 5 years ahead', () => {
+ expect(getBudgetRange('2026-10', '2026-10', '2099-01').end).toBe('2031-10');
+ });
+});
+
describe('Base budget', () => {
+ describe.each(['tracking', 'envelope'] as const)(
+ 'automatic range (%s)',
+ budgetType => {
+ const table =
+ budgetType === 'tracking' ? 'reflect_budgets' : 'zero_budgets';
+ const otherTable =
+ budgetType === 'tracking' ? 'zero_budgets' : 'reflect_budgets';
+ const minEnd = () => monthUtils.addMonths(monthUtils.currentMonth(), 12);
+
+ async function loadBudget() {
+ await sheet.loadSpreadsheet(db);
+ sheet.get().meta().budgetType = budgetType;
+ }
+
+ beforeEach(async () => {
+ await db.insertCategoryGroup({
+ id: 'income',
+ name: 'Income',
+ is_income: 1,
+ });
+ await db.insertCategoryGroup({ id: 'expenses', name: 'Expenses' });
+ await db.insertCategory({
+ id: 'planned',
+ name: 'Planned',
+ cat_group: 'expenses',
+ });
+ db.runQuery(
+ "INSERT INTO preferences (id, value) VALUES ('budgetType', ?)",
+ [budgetType],
+ );
+ await loadBudget();
+ });
+
+ it('extends from saved allocations without rebuilding existing months', async () => {
+ const initial = await createAllBudgets();
+ expect(initial.end).toBe(minEnd());
+ const cell = sheet.getCell('budget201701', 'total-budgeted');
+
+ await setBudget({ category: 'planned', month: minEnd(), amount: 200 });
+ const extended = await createAllBudgets();
+ expect(extended.end).toBe(monthUtils.addMonths(minEnd(), 3));
+ expect(sheet.getCell('budget201701', 'total-budgeted')).toBe(cell);
+
+ // Negative amounts are allocations too
+ await setBudget({
+ category: 'planned',
+ month: extended.end,
+ amount: -100,
+ });
+ expect((await createAllBudgets()).end).toBe(
+ monthUtils.addMonths(extended.end, 3),
+ );
+ });
+
+ it('ignores amounts saved for the other budget type', async () => {
+ db.runQuery(
+ `INSERT INTO ${otherTable} (id, month, category, amount) VALUES (?, ?, ?, ?)`,
+ ['202812-planned', 202812, 'planned', 200],
+ );
+ expect((await createAllBudgets()).end).toBe(minEnd());
+ });
+
+ it('stays extended while open and shrinks on the next load', async () => {
+ await setBudget({ category: 'planned', month: minEnd(), amount: 200 });
+ const { end: extendedEnd } = await createAllBudgets();
+ await setBudget({ category: 'planned', month: minEnd(), amount: 0 });
+ expect((await createAllBudgets()).end).toBe(extendedEnd);
+
+ sheet.unloadSpreadsheet();
+ await loadBudget();
+ expect((await createAllBudgets()).end).toBe(minEnd());
+ });
+
+ it('applies bulk changes to every visible month', async () => {
+ await setBudget({ category: 'planned', month: minEnd(), amount: 200 });
+ await createAllBudgets();
+ await setBudget({ category: 'planned', month: minEnd(), amount: 0 });
+ const { end } = await createAllBudgets();
+
+ await setCategoryCarryover({
+ startMonth: monthUtils.currentMonth(),
+ category: 'planned',
+ flag: true,
+ });
+ const row = db.firstSync<{ carryover: number }>(
+ `SELECT carryover FROM ${table} WHERE month = ? AND category = ?`,
+ [parseInt(end.replace('-', '')), 'planned'],
+ );
+ expect(row?.carryover).toBe(1);
+ });
+ },
+ );
+
it('Recomputes budget cells when account fields change', async () => {
await sheet.loadSpreadsheet(db);
diff --git a/packages/loot-core/src/server/budget/base.ts b/packages/loot-core/src/server/budget/base.ts
index b2215dfef6..efb8a3520f 100644
--- a/packages/loot-core/src/server/budget/base.ts
+++ b/packages/loot-core/src/server/budget/base.ts
@@ -12,12 +12,23 @@ import * as budgetActions from './actions';
import * as envelopeBudget from './envelope';
import * as trackingBudget from './tracking';
+// How far ahead budget months are available. Planning past the minimum
+// keeps a few empty months after the latest allocation, up to a hard cap
+// so stray far-future data can't create an unbounded number of months.
+const MIN_MONTHS_AHEAD = 12;
+const MONTHS_AFTER_LATEST_ALLOCATION = 3;
+const MAX_MONTHS_AHEAD = 60;
+
export function getBudgetType() {
const meta = sheet.get().meta();
return meta.budgetType || 'envelope';
}
-export function getBudgetRange(start: string, end: string) {
+export function getBudgetRange(
+ start: string,
+ end: string,
+ latestAllocatedMonth?: string | null,
+) {
start = monthUtils.getMonth(start);
end = monthUtils.getMonth(end);
@@ -28,16 +39,45 @@ export function getBudgetRange(start: string, end: string) {
start = end;
}
+ const maxEnd = monthUtils.addMonths(end, MAX_MONTHS_AHEAD);
+
// Budgets should exist 3 months before the earliest needed date
// (either the oldest transaction or the current month if no
- // transactions yet), and a year from the current date. There's no
- // need to ever have budgets outside that range.
+ // transactions yet), and at least a year from the current date.
start = monthUtils.subMonths(start, 3);
- end = monthUtils.addMonths(end, 12);
+ end = monthUtils.addMonths(end, MIN_MONTHS_AHEAD);
+
+ if (latestAllocatedMonth) {
+ const plannedEnd = monthUtils.addMonths(
+ latestAllocatedMonth,
+ MONTHS_AFTER_LATEST_ALLOCATION,
+ );
+ if (plannedEnd > end) {
+ end = plannedEnd < maxEnd ? plannedEnd : maxEnd;
+ }
+ }
return { start, end, range: monthUtils.rangeInclusive(start, end) };
}
+// The latest month with a non-zero amount in the active budget type.
+// Envelope and tracking amounts are stored separately, so each type
+// extends its own range.
+async function getLatestAllocatedMonth(): Promise<string | null> {
+ const table =
+ getBudgetType() === 'tracking' ? 'reflect_budgets' : 'zero_budgets';
+ const row = await db.first<{ month: number | null }>(
+ `SELECT MAX(b.month) AS month FROM ${table} b
+ JOIN categories c ON c.id = b.category
+ WHERE c.tombstone = 0 AND b.amount != 0`,
+ );
+ if (!row?.month) {
+ return null;
+ }
+ const month = String(row.month);
+ return `${month.slice(0, 4)}-${month.slice(4)}`;
+}
+
// The day range spanning the given months. They aren't guaranteed to be
// sorted, so find the first and last explicitly ('YYYY-MM' strings compare
// chronologically).
@@ -433,6 +473,7 @@ export async function createAllBudgets() {
const { start, end, range } = getBudgetRange(
earliestDate || currentMonth,
currentMonth,
+ await getLatestAllocatedMonth(),
);
const meta = sheet.get().meta();
@@ -443,7 +484,16 @@ export async function createAllBudgets() {
await createBudget(range);
}
- return { start, end };
+ // The range only grows while the budget is open, so every created month
+ // stays reachable. Clearing allocations shrinks it on the next load.
+ let lastMonth = end;
+ for (const month of sheet.get().meta().createdMonths) {
+ if (month > lastMonth) {
+ lastMonth = month;
+ }
+ }
+
+ return { start, end: lastMonth };
}
export async function setType(type) {
diff --git a/upcoming-release-notes/automatic-budget-range.md b/upcoming-release-notes/automatic-budget-range.md
new file mode 100644
index 0000000000..6004b2007b
--- /dev/null
+++ b/upcoming-release-notes/automatic-budget-range.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [x-rous]
+---
+
+Automatically extend budget planning beyond 12 months, up to 5 years ahead, in Envelope and Tracking modes.