A local-first personal finance app
[AI] Show a category's goal as soon as its automations are saved (#9304)
Matty Ice21c2b3f70314
diff --git a/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx b/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsxindex 46e37b41c8..4afd3053f9 100644--- a/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx+++ b/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx@@ -13,6 +13,7 @@ import { css } from '@emotion/css';import { CellValue, CellValueText } from '#components/spreadsheet/CellValue';import { useFeatureFlag } from '#hooks/useFeatureFlag';+import { useFormat } from '#hooks/useFormat';import { useSheetValue } from '#hooks/useSheetValue';import type { Binding } from '#spreadsheet';@@ -93,14 +94,22 @@ export function BalanceWithCarryover({const budgetedValue = useSheetValue(budgeted);const longGoalValue = useSheetValue(longGoal);const isGoalTemplatesEnabled = useFeatureFlag('goalTemplatesEnabled');+ const { decimalPlaces } = useFormat().currency;const getBalanceAmountStyle = useCallback((balanceValue: number) =>makeBalanceAmountStyle(balanceValue,isGoalTemplatesEnabled ? goalValue : null,longGoalValue === 1 ? balanceValue : budgetedValue,+ decimalPlaces,),- [budgetedValue, goalValue, isGoalTemplatesEnabled, longGoalValue],+ [+ budgetedValue,+ decimalPlaces,+ goalValue,+ isGoalTemplatesEnabled,+ longGoalValue,+ ],);const getDefaultClassName = useCallback(diff --git a/packages/desktop-client/src/components/budget/GoalStatus.tsx b/packages/desktop-client/src/components/budget/GoalStatus.tsxindex e84a8829c8..b546bb8b6e 100644--- a/packages/desktop-client/src/components/budget/GoalStatus.tsx+++ b/packages/desktop-client/src/components/budget/GoalStatus.tsx@@ -13,6 +13,8 @@ import { useFormat } from '#hooks/useFormat';import { useSheetValue } from '#hooks/useSheetValue';import type { Binding } from '#spreadsheet';+import { getGoalDifference } from './util';+type GoalStatusProps = {balance: Binding<'envelope-budget' | 'tracking-budget',@@ -44,7 +46,12 @@ export function GoalStatus({}const have = longGoalValue === 1 ? balanceValue : budgetedValue;- const diff = have - goalValue;+ // Compare as displayed, like the balance colour+ const diff = getGoalDifference(+ have,+ goalValue,+ format.currency.decimalPlaces,+ );// Round down while underfunded so the bar only reads 100% once the goal is metconst progress =diff < 0 ? Math.floor(Math.max(0, have / goalValue) * 100) : 100;diff --git a/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsx b/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsxindex e31a739686..3c68dd28d6 100644--- a/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsx+++ b/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsx@@ -6,7 +6,9 @@ import { Menu } from '@actual-app/components/menu';import type { MenuItemObject } from '@actual-app/components/menu';import type { IntegerAmount } from '@actual-app/core/shared/util';+import { getGoalDifference } from '#components/budget/util';import { useFeatureFlag } from '#hooks/useFeatureFlag';+import { useFormat } from '#hooks/useFormat';import { envelopeBudget } from '#spreadsheet/bindings';import { useEnvelopeSheetValue } from './EnvelopeBudgetComponents';@@ -28,6 +30,7 @@ export function useBalanceMenu({}: BalanceMenuActions) {const { t } = useTranslation();const isGoalTemplatesEnabled = useFeatureFlag('goalTemplatesEnabled');+ const format = useFormat();const carryover = useEnvelopeSheetValue(envelopeBudget.catCarryover(categoryId),@@ -43,7 +46,11 @@ export function useBalanceMenu({const toBudget = useEnvelopeSheetValue(envelopeBudget.toBudget) ?? 0;const fundAmount =- isGoalTemplatesEnabled && onFundGoal && goal != null && longGoal !== 1+ isGoalTemplatesEnabled &&+ onFundGoal &&+ goal != null &&+ longGoal !== 1 &&+ getGoalDifference(budgeted, goal, format.currency.decimalPlaces) < 0? Math.min(goal - budgeted, toBudget): 0;diff --git a/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.test.tsx b/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.test.tsxindex 7923f7d43b..bea40bee38 100644--- a/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.test.tsx+++ b/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.test.tsx@@ -1,4 +1,5 @@import { initServer } from '@actual-app/core/platform/client/connection';+import { setNumberFormat } from '@actual-app/core/shared/util';import { render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';@@ -31,13 +32,15 @@ vi.mock('#hooks/useSheetValue', async () => {};});-function renderMenu() {+function renderMenu(prefs: Record<string, string> = {}) {const onBudgetAction =vi.fn<(month: string, action: string, arg?: unknown) => void>();const onClose = vi.fn<() => void>();const client = createTestQueryClient();const store = configureTestAppStore({ queryClient: client });- store.dispatch(mergeSyncedPrefs({ 'flags.goalTemplatesEnabled': 'true' }));+ store.dispatch(+ mergeSyncedPrefs({ 'flags.goalTemplatesEnabled': 'true', ...prefs }),+ );initServer({'get-categories': async () => ({ grouped: [], list: [] }),query: async () => ({ data: [], dependencies: [] }),@@ -84,6 +87,35 @@ describe('BalanceMovementMenu', () => {expect(onClose).toHaveBeenCalledOnce();});+ it('counts a shortfall that rounds away as funded when decimals are hidden', async () => {+ setNumberFormat({ format: 'comma-dot', hideFraction: true });+ sheetValues['budget202401!goal-groceries'] = 40040;+ try {+ renderMenu({ hideFraction: 'true' });++ expect(await screen.findByText('Fully funded')).toBeInTheDocument();+ expect(+ screen.queryByText('Fund goal from To Budget'),+ ).not.toBeInTheDocument();+ } finally {+ setNumberFormat({ format: 'comma-dot', hideFraction: false });+ }+ });++ it('shows the shortfall between the displayed amounts when decimals are hidden', async () => {+ setNumberFormat({ format: 'comma-dot', hideFraction: true });+ sheetValues['budget202401!goal-groceries'] = 40051;+ sheetValues['budget202401!budget-groceries'] = 40049;+ try {+ renderMenu({ hideFraction: 'true' });++ expect(await screen.findByText('Underfunded (-1)')).toBeInTheDocument();+ expect(screen.getByText('Fund goal from To Budget')).toBeInTheDocument();+ } finally {+ setNumberFormat({ format: 'comma-dot', hideFraction: false });+ }+ });+it('does not offer funding when To Budget is empty', async () => {sheetValues['budget202401!to-budget'] = 0;renderMenu();diff --git a/packages/desktop-client/src/components/budget/util.test.ts b/packages/desktop-client/src/components/budget/util.test.tsnew file mode 100644index 0000000000..36743193da--- /dev/null+++ b/packages/desktop-client/src/components/budget/util.test.ts@@ -0,0 +1,37 @@+import { theme } from '@actual-app/components/theme';+import { setNumberFormat } from '@actual-app/core/shared/util';++import { getGoalDifference, makeBalanceAmountStyle } from './util';++describe('getGoalDifference', () => {+ afterEach(() => {+ setNumberFormat({ format: 'comma-dot', hideFraction: false });+ });++ it('measures what a category has against its goal', () => {+ expect(getGoalDifference(10000, 10040)).toBe(-40);+ expect(getGoalDifference(10040, 10040)).toBe(0);+ expect(getGoalDifference(10100, 10040)).toBe(60);+ expect(getGoalDifference(null, 10040)).toBe(-10040);+ });++ it('measures the displayed amounts when decimals are hidden', () => {+ setNumberFormat({ format: 'comma-dot', hideFraction: true });+ expect(getGoalDifference(10000, 10040)).toBe(0);+ expect(getGoalDifference(10000, 10060)).toBe(-100);+ // 100 against 101, not the one cent between them+ expect(getGoalDifference(10049, 10050)).toBe(-100);+ expect(makeBalanceAmountStyle(10000, 10040, 10000)).toEqual({+ color: theme.templateNumberFunded,+ });+ });++ it('measures whole units for currencies without decimals', () => {+ setNumberFormat({ format: 'comma-dot', hideFraction: true });+ expect(getGoalDifference(39950, 40049, 0)).toBe(-99);+ expect(getGoalDifference(40049, 40049, 0)).toBe(0);+ expect(makeBalanceAmountStyle(39950, 40049, 39950, 0)).toEqual({+ color: theme.templateNumberUnderFunded,+ });+ });+});diff --git a/packages/desktop-client/src/components/budget/util.ts b/packages/desktop-client/src/components/budget/util.tsindex 398a28efbb..d0a3fd2a88 100644--- a/packages/desktop-client/src/components/budget/util.ts+++ b/packages/desktop-client/src/components/budget/util.ts@@ -5,6 +5,7 @@ import { theme } from '@actual-app/components/theme';import { send } from '@actual-app/core/platform/client/connection';import * as monthUtils from '@actual-app/core/shared/months';import {+ amountToInteger,currencyToAmount,integerToCurrency,} from '@actual-app/core/shared/util';@@ -68,19 +69,44 @@ export function makeAmountGrey(value: number | string | null): CSSProperties {: null;}+// Converts an integer currency value to a normalized decimal amount.+// First converts the integer to currency format, then to a decimal amount.+// Uses integerToCurrency to display the value correctly according to user prefs+// and the currency's decimal places.+function normalizeIntegerValue(+ val: number | null | undefined,+ decimalPlaces = 2,+) {+ return typeof val === 'number'+ ? currencyToAmount(integerToCurrency(val, undefined, decimalPlaces))+ : 0;+}++/**+ * How far what a category has towards its goal is from the goal, as the+ * amounts are displayed: negative when short of it, 0 when they match and+ * positive when over it. With hidden decimals, amounts that round to the same+ * number count as equal.+ */+export function getGoalDifference(+ have: number | null | undefined,+ goalValue: number,+ decimalPlaces = 2,+): number {+ return amountToInteger(+ normalizeIntegerValue(have, decimalPlaces) -+ normalizeIntegerValue(goalValue, decimalPlaces),+ decimalPlaces,+ );+}+export function makeBalanceAmountStyle(value: number,goalValue?: number | null,budgetedValue?: number | null,+ decimalPlaces = 2,) {- // Converts an integer currency value to a normalized decimal amount.- // First converts the integer to currency format, then to a decimal amount.- // Uses integerToCurrency to display the value correctly according to user prefs.-- const normalizeIntegerValue = (val: number | null | undefined) =>- typeof val === 'number' ? currencyToAmount(integerToCurrency(val)) : 0;-- const currencyValue = normalizeIntegerValue(value);+ const currencyValue = normalizeIntegerValue(value, decimalPlaces);if (currencyValue < 0) {return { color: theme.budgetNumberNegative };@@ -93,10 +119,7 @@ export function makeBalanceAmountStyle(}return { color: theme.budgetNumberPositive };} else {- const budgetedAmount = normalizeIntegerValue(budgetedValue);- const goalAmount = normalizeIntegerValue(goalValue);-- if (budgetedAmount < goalAmount) {+ if (getGoalDifference(budgetedValue, goalValue, decimalPlaces) < 0) {return { color: theme.templateNumberUnderFunded };}return { color: theme.templateNumberFunded };diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.ts b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.tsindex 6218cdb7e5..b5b2749f91 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.ts+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.ts@@ -172,6 +172,7 @@ export function useBudgetAutomationsEditor({},],source: 'ui',+ month,});onClose();} finally {diff --git a/packages/docs/docs/experimental/budget-automation.md b/packages/docs/docs/experimental/budget-automation.mdindex 2e3bbdf137..115892c1b1 100644--- a/packages/docs/docs/experimental/budget-automation.md+++ b/packages/docs/docs/experimental/budget-automation.md@@ -65,6 +65,8 @@ The projected amount to be budgeted will be shown in the top right of the automaDon't forget to **Save** your work when you are finished adding and editing automations.+Saving also sets the category's goal for the month the projected amount is shown for (the month furthest to the left in your budget view, or the month you are viewing on mobile), so the [budget indicator](#budget-indicator) and goal status appear right away, and **Fund goal from To Budget** can be used without running the automations first. Saving never changes how much is budgeted. Other months get their goal when you apply automations to them.+:::### Priorities {#priorities}@@ -321,7 +323,7 @@ Once you hit your goal, the balance will turn green. Note that if you remove fun:::tip- The long-term goal does not automatically add funds or stop funds from being added after the goal has been hit. To stop automated funds from being added after you reach the goal, add a _Balance cap_ to the category.-- You can have a long-term goal without any other automations and budget manually toward your goal. You will still need to run the automations on the category to see the indicator and goal status.+- You can have a long-term goal without any other automations and budget manually toward your goal. Saving the long-term goal shows the indicator and goal status for the month the automations editor is showing; for other months, you will still need to run the automations on the category.:::The goal status shows your progress:diff --git a/packages/loot-core/src/server/budget/goal-template.test.ts b/packages/loot-core/src/server/budget/goal-template.test.tsindex d495e12e1d..d8ab719cc4 100644--- a/packages/loot-core/src/server/budget/goal-template.test.ts+++ b/packages/loot-core/src/server/budget/goal-template.test.ts@@ -1,5 +1,6 @@import { vi } from 'vitest';+import { logger } from '#platform/server/log';import * as aql from '#server/aql';import * as db from '#server/db';import type { DbCategory } from '#server/db';@@ -11,6 +12,7 @@ import {applyMultipleCategoryTemplates,applyTemplate,dryRunCategoryTemplate,+ storeTemplates,} from './goal-template';import * as statements from './statements';@@ -25,6 +27,7 @@ vi.mock('./actions', () => ({vi.mock('#server/db', () => ({getCategories: vi.fn(),first: vi.fn(),+ updateWithSchema: vi.fn(),}));vi.mock('#server/aql', () => ({@@ -216,7 +219,12 @@ describe('dryRunCategoryTemplate', () => {categoryId: 'missing',templates,});- expect(result).toEqual({ budgeted: 0, perTemplate: [0] });+ expect(result).toEqual({+ budgeted: 0,+ perTemplate: [0],+ goal: null,+ longGoal: false,+ });});it('shows full demand even when To Budget cannot cover it', async () => {@@ -255,6 +263,117 @@ describe('dryRunCategoryTemplate', () => {});});+describe('storeTemplates with a month', () => {+ const monthly: Template = {+ type: 'periodic',+ amount: 100,+ period: { period: 'month', amount: 1 },+ starting: '2024-01-01',+ directive: 'template',+ priority: 1,+ };++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(statements.getActiveSchedules).mockResolvedValue([]);+ vi.mocked(db.getCategories).mockResolvedValue([]);+ setupAqlForCategoryLookup(category);+ });++ it('records the goal without changing what is budgeted', async () => {+ setupSheetMock({ 'to-budget': 100000, [`budget-${category.id}`]: 3000 });++ await storeTemplates({+ categoriesWithTemplates: [{ id: category.id, templates: [monthly] }],+ source: 'ui',+ month: '2024-01',+ });++ expect(db.updateWithSchema).toHaveBeenCalledWith(+ 'categories',+ expect.objectContaining({ id: category.id }),+ );+ expect(actions.setGoal).toHaveBeenCalledWith({+ month: '2024-01',+ category: category.id,+ goal: 10000,+ long_goal: null,+ });+ expect(actions.setBudget).not.toHaveBeenCalled();+ });++ it('records a long-term goal', async () => {+ setupSheetMock({ 'to-budget': 100000 });++ await storeTemplates({+ categoriesWithTemplates: [+ {+ id: category.id,+ templates: [{ type: 'goal', amount: 1500, directive: 'goal' }],+ },+ ],+ source: 'ui',+ month: '2024-01',+ });++ expect(actions.setGoal).toHaveBeenCalledWith({+ month: '2024-01',+ category: category.id,+ goal: 150000,+ long_goal: 1,+ });+ });++ it('clears the goal when every automation is removed', async () => {+ setupSheetMock({});++ await storeTemplates({+ categoriesWithTemplates: [{ id: category.id, templates: [] }],+ source: 'ui',+ month: '2024-01',+ });++ expect(actions.setGoal).toHaveBeenCalledWith({+ month: '2024-01',+ category: category.id,+ goal: null,+ long_goal: null,+ });+ });++ it('clears the goal instead of failing the save when it cannot be worked out', async () => {+ vi.mocked(actions.getSheetValue).mockRejectedValue(new Error('no sheet'));+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => undefined);++ await storeTemplates({+ categoriesWithTemplates: [{ id: category.id, templates: [monthly] }],+ source: 'ui',+ month: '2024-01',+ });++ expect(db.updateWithSchema).toHaveBeenCalled();+ expect(warn).toHaveBeenCalled();+ expect(actions.setGoal).toHaveBeenCalledWith({+ month: '2024-01',+ category: category.id,+ goal: null,+ long_goal: null,+ });+ });++ it('leaves goals alone without a month', async () => {+ setupSheetMock({ 'to-budget': 100000 });++ await storeTemplates({+ categoriesWithTemplates: [{ id: category.id, templates: [monthly] }],+ source: 'notes',+ });++ expect(db.updateWithSchema).toHaveBeenCalled();+ expect(actions.setGoal).not.toHaveBeenCalled();+ });+});+describe('applyMultipleCategoryTemplates', () => {const cat1: CategoryEntity = {id: 'cat-1',diff --git a/packages/loot-core/src/server/budget/goal-template.ts b/packages/loot-core/src/server/budget/goal-template.tsindex 979a56e63e..36e9983f11 100644--- a/packages/loot-core/src/server/budget/goal-template.ts+++ b/packages/loot-core/src/server/budget/goal-template.ts@@ -1,3 +1,4 @@+import { logger } from '#platform/server/log';import { aqlQuery } from '#server/aql';import * as db from '#server/db';import { batchMessages } from '#server/sync';@@ -38,6 +39,7 @@ export function distributeRemainder(export async function storeTemplates({categoriesWithTemplates,source,+ month,}: {categoriesWithTemplates: {id: string;@@ -45,6 +47,8 @@ export async function storeTemplates({cleanup?: CleanupTemplate[];}[];source: 'notes' | 'ui';+ /** Also record each category's goal for this month, without budgeting it */+ month?: string;}): Promise<void> {let touchedCleanup = false;await batchMessages(async () => {@@ -66,6 +70,13 @@ export async function storeTemplates({if (touchedCleanup) {await tombstoneOrphanCleanupGroups();}+ if (month) {+ const goals: TemplateGoal[] = [];+ for (const { id, templates } of categoriesWithTemplates) {+ goals.push(await getMonthGoal(month, id, templates));+ }+ await setGoals(month, goals);+ }}export async function applyTemplate({@@ -356,6 +367,8 @@ async function processTemplate(export type DryRunCategoryResult = {budgeted: number;perTemplate: number[];+ goal: number | null;+ longGoal: boolean;};export async function dryRunCategoryTemplate({@@ -370,12 +383,16 @@ export async function dryRunCategoryTemplate({// The projection answers "how much do these templates demand" — it// skips the priority clamp so future months (where To Budget is empty)// still show the templates' intended amount instead of 0.+ const empty: DryRunCategoryResult = {+ budgeted: 0,+ perTemplate: templates.map(() => 0),+ goal: null,+ longGoal: false,+ };const { data: categoryData }: { data: CategoryEntity[] } = await aqlQuery(q('categories').filter({ id: categoryId }).select('*'),);- if (categoryData.length === 0) {- return { budgeted: 0, perTemplate: templates.map(() => 0) };- }+ if (categoryData.length === 0) return empty;const { contexts } = await computeTemplates(month,true,@@ -384,10 +401,34 @@ export async function dryRunCategoryTemplate({true,);const ctx = contexts.find(c => c.category.id === categoryId);- if (!ctx) return { budgeted: 0, perTemplate: templates.map(() => 0) };+ if (!ctx) return empty;const values = ctx.getValues();return {budgeted: values.budgeted,perTemplate: templates.map(t => values.perTemplateContribution.get(t) ?? 0),+ goal: values.goal,+ longGoal: !!values.longGoal,};}++// Records the goal the automations editor projects for the month, so it+// shows up without running the templates+async function getMonthGoal(+ month: string,+ categoryId: CategoryEntity['id'],+ templates: Template[],+): Promise<TemplateGoal> {+ const noGoal = { category: categoryId, goal: null, longGoal: null };+ if (templates.length === 0) return noGoal;+ try {+ const { goal, longGoal } = await dryRunCategoryTemplate({+ month,+ categoryId,+ templates,+ });+ return { category: categoryId, goal, longGoal: longGoal ? 1 : null };+ } catch (e) {+ logger.warn(`Could not work out the goal for category ${categoryId}`, e);+ return noGoal;+ }+}diff --git a/packages/loot-core/src/server/undo.ts b/packages/loot-core/src/server/undo.tsindex 2b0e4592bc..299ccc2e47 100644--- a/packages/loot-core/src/server/undo.ts+++ b/packages/loot-core/src/server/undo.ts@@ -192,6 +192,9 @@ function undoMessage(message, oldData) {if (['buffered', 'amount', 'carryover'].includes(message.column)) {return { ...message, value: 0 };}+ if (['goal', 'long_goal'].includes(message.column)) {+ return { ...message, value: null };+ }return null;} else if (message.dataset === 'notes') {return { ...message, value: null };diff --git a/upcoming-release-notes/goal-on-automation-save.md b/upcoming-release-notes/goal-on-automation-save.mdnew file mode 100644index 0000000000..3260244a6c--- /dev/null+++ b/upcoming-release-notes/goal-on-automation-save.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [mattm4444]+---++Show a category's goal as soon as you save its budget automations, without changing the budgeted amount