A local-first personal finance app
[AI] Show goal progress in the balance menu and fund goals from To Budget (#9281)
Matty Ice6ef6d303d47a
diff --git a/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx b/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsxindex 3d63ca031b..46e37b41c8 100644--- a/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx+++ b/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx@@ -5,23 +5,18 @@ import type {ComponentType,CSSProperties,} from 'react';-import { Trans, useTranslation } from 'react-i18next';-import { useResponsive } from '@actual-app/components/hooks/useResponsive';import { SvgArrowThinRight } from '@actual-app/components/icons/v1';-import { styles } from '@actual-app/components/styles';import { theme } from '@actual-app/components/theme';-import { Tooltip } from '@actual-app/components/tooltip';import { View } from '@actual-app/components/view';-import type { TransObjectLiteral } from '@actual-app/core/types/util';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';+import { GoalStatus } from './GoalStatus';import { makeBalanceAmountStyle } from './util';type CarryoverIndicatorProps = {@@ -51,21 +46,6 @@ export function CarryoverIndicator({ style }: CarryoverIndicatorProps) {);}-function GoalTooltipRow({ children }) {- return (- <div- style={{- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- gap: 10,- }}- >- {children}- </div>- );-}-type CellValueChildren = ComponentPropsWithoutRef<typeof CellValue>['children'];type ChildrenWithClassName = (@@ -94,7 +74,6 @@ type BalanceWithCarryoverProps = Omit<isDisabled?: boolean;shouldInlineGoalStatus?: boolean;CarryoverIndicator?: ComponentType<CarryoverIndicatorProps>;- tooltipDisabled?: boolean;};export function BalanceWithCarryover({@@ -106,12 +85,9 @@ export function BalanceWithCarryover({isDisabled,shouldInlineGoalStatus,CarryoverIndicator: CarryoverIndicatorComponent = CarryoverIndicator,- tooltipDisabled,children,...props}: BalanceWithCarryoverProps) {- const { t } = useTranslation();- const { isNarrowWidth } = useResponsive();const carryoverValue = useSheetValue(carryover);const goalValue = useSheetValue(goal);const budgetedValue = useSheetValue(budgeted);@@ -126,15 +102,6 @@ export function BalanceWithCarryover({),[budgetedValue, goalValue, isGoalTemplatesEnabled, longGoalValue],);- const format = useFormat();-- const getDifferenceToGoal = useCallback(- (balanceValue: number) =>- longGoalValue === 1- ? balanceValue - goalValue- : budgetedValue - goalValue,- [budgetedValue, goalValue, longGoalValue],- );const getDefaultClassName = useCallback((balanceValue: number) =>@@ -150,119 +117,12 @@ export function BalanceWithCarryover({}),[getBalanceAmountStyle, isDisabled],);- const GoalStatusDisplay = useCallback(- (balanceValue, type) => {- return (- <>- <span style={{ fontWeight: 'bold' }}>- {getDifferenceToGoal(balanceValue) === 0 ? (- <span style={{ color: theme.templateNumberFunded }}>- <Trans>Fully funded</Trans>- </span>- ) : getDifferenceToGoal(balanceValue) > 0 ? (- <span style={{ color: theme.templateNumberFunded }}>- <Trans>- Overfunded (- {{- amount: format(- getDifferenceToGoal(balanceValue),- 'financial',- ),- }}- )- </Trans>- </span>- ) : (- <span style={{ color: theme.templateNumberUnderFunded }}>- <Trans>- Underfunded (- {{- amount: format(- getDifferenceToGoal(balanceValue),- 'financial',- ),- }}- )- </Trans>- </span>- )}- </span>- <GoalTooltipRow>- <Trans>- <div>Goal Type:</div>- <div>- {- {- type: longGoalValue === 1 ? t('Goal') : t('Automation'),- } as TransObjectLiteral- }- </div>- </Trans>- </GoalTooltipRow>- <GoalTooltipRow>- <Trans>- <div>Goal:</div>- <div>- {- {- amount: format(goalValue, 'financial'),- } as TransObjectLiteral- }- </div>- </Trans>- </GoalTooltipRow>- <GoalTooltipRow>- {longGoalValue !== 1 ? (- <Trans>- <div>Budgeted:</div>- <div>- {- {- amount: format(budgetedValue, 'financial'),- } as TransObjectLiteral- }- </div>- </Trans>- ) : (- <Trans>- <div>Balance:</div>- <div>- {- {- amount: format(balanceValue, type),- } as TransObjectLiteral- }- </div>- </Trans>- )}- </GoalTooltipRow>- </>- );- },- [budgetedValue, format, getDifferenceToGoal, goalValue, longGoalValue, t],- );return (<CellValue binding={balance} type="financial" {...props}>{({ type, name, value: balanceValue }) => (<>- <Tooltip- content={- <View style={{ padding: 10 }}>- {GoalStatusDisplay(balanceValue, type)}- </View>- }- style={{ ...styles.tooltip, borderRadius: '0px 5px 5px 0px' }}- placement="bottom"- triggerProps={{- delay: 750,- isDisabled:- !isGoalTemplatesEnabled ||- goalValue == null ||- isNarrowWidth ||- tooltipDisabled,- }}- >+ <View style={{ minHeight: 'auto', flexShrink: 0, maxWidth: '100%' }}>{children ? (children({type,@@ -278,7 +138,7 @@ export function BalanceWithCarryover({className={getDefaultClassName(balanceValue)}/>)}- </Tooltip>+ </View>{carryoverValue && (<CarryoverIndicatorComponent@@ -287,7 +147,7 @@ export function BalanceWithCarryover({)}{shouldInlineGoalStatus &&isGoalTemplatesEnabled &&- goalValue !== null && (+ goalValue != null && (<><Viewstyle={{@@ -296,7 +156,12 @@ export function BalanceWithCarryover({margin: '3px 0px',}}/>- <View>{GoalStatusDisplay(balanceValue, type)}</View>+ <GoalStatus+ balance={balance}+ goal={goal}+ budgeted={budgeted}+ longGoal={longGoal}+ /></>)}</>diff --git a/packages/desktop-client/src/components/budget/GoalStatus.tsx b/packages/desktop-client/src/components/budget/GoalStatus.tsxnew file mode 100644index 0000000000..e84a8829c8--- /dev/null+++ b/packages/desktop-client/src/components/budget/GoalStatus.tsx@@ -0,0 +1,179 @@+import React from 'react';+import type { CSSProperties, ReactNode } from 'react';+import { ProgressBar } from 'react-aria-components';+import { Trans, useTranslation } from 'react-i18next';++import { styles } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import type { TransObjectLiteral } from '@actual-app/core/types/util';++import { useFeatureFlag } from '#hooks/useFeatureFlag';+import { useFormat } from '#hooks/useFormat';+import { useSheetValue } from '#hooks/useSheetValue';+import type { Binding } from '#spreadsheet';++type GoalStatusProps = {+ balance: Binding<+ 'envelope-budget' | 'tracking-budget',+ 'leftover' | 'sum-amount'+ >;+ goal: Binding<'envelope-budget' | 'tracking-budget', 'goal'>;+ budgeted: Binding<'envelope-budget' | 'tracking-budget', 'budget'>;+ longGoal: Binding<'envelope-budget' | 'tracking-budget', 'long-goal'>;+ style?: CSSProperties;+};++export function GoalStatus({+ balance,+ goal,+ budgeted,+ longGoal,+ style,+}: GoalStatusProps) {+ const { t } = useTranslation();+ const format = useFormat();+ const isGoalTemplatesEnabled = useFeatureFlag('goalTemplatesEnabled');+ const balanceValue = useSheetValue(balance) ?? 0;+ const goalValue = useSheetValue(goal);+ const budgetedValue = useSheetValue(budgeted) ?? 0;+ const longGoalValue = useSheetValue(longGoal);++ if (!isGoalTemplatesEnabled || goalValue == null) {+ return null;+ }++ const have = longGoalValue === 1 ? balanceValue : budgetedValue;+ const diff = have - goalValue;+ // Round down while underfunded so the bar only reads 100% once the goal is met+ const progress =+ diff < 0 ? Math.floor(Math.max(0, have / goalValue) * 100) : 100;++ return (+ <View style={{ minWidth: 160, ...style }}>+ <span style={{ fontWeight: 'bold' }}>+ {diff === 0 ? (+ <span style={{ color: theme.templateNumberFunded }}>+ <Trans>Fully funded</Trans>+ </span>+ ) : diff > 0 ? (+ <span style={{ color: theme.templateNumberFunded }}>+ <Trans>+ Overfunded (+ {{+ amount: format(diff, 'financial'),+ }}+ )+ </Trans>+ </span>+ ) : (+ <span style={{ color: theme.templateNumberUnderFunded }}>+ <Trans>+ Underfunded (+ {{+ amount: format(diff, 'financial'),+ }}+ )+ </Trans>+ </span>+ )}+ </span>+ {goalValue > 0 && (+ <ProgressBar+ value={progress}+ aria-label={t('Goal progress')}+ style={{ alignSelf: 'stretch', margin: '6px 0' }}+ >+ <View+ style={{+ height: 4,+ borderRadius: 2,+ backgroundColor: theme.tableBorder,+ overflow: 'hidden',+ }}+ >+ <View+ style={{+ height: '100%',+ width: `${progress}%`,+ backgroundColor:+ diff >= 0+ ? theme.templateNumberFunded+ : theme.templateNumberUnderFunded,+ }}+ />+ </View>+ </ProgressBar>+ )}+ <GoalStatusRow>+ <Trans>+ <div>Goal Type:</div>+ <div>+ {+ {+ type: longGoalValue === 1 ? t('Goal') : t('Automation'),+ } as TransObjectLiteral+ }+ </div>+ </Trans>+ </GoalStatusRow>+ <GoalStatusRow>+ <Trans>+ <div>Goal:</div>+ <div>+ {+ {+ amount: format(goalValue, 'financial'),+ } as TransObjectLiteral+ }+ </div>+ </Trans>+ </GoalStatusRow>+ <GoalStatusRow>+ {longGoalValue !== 1 ? (+ <Trans>+ <div>Budgeted:</div>+ <div>+ {+ {+ amount: format(budgetedValue, 'financial'),+ } as TransObjectLiteral+ }+ </div>+ </Trans>+ ) : (+ <Trans>+ <div>Balance:</div>+ <div>+ {+ {+ amount: format(balanceValue, 'financial'),+ } as TransObjectLiteral+ }+ </div>+ </Trans>+ )}+ </GoalStatusRow>+ </View>+ );+}++type GoalStatusRowProps = {+ children: ReactNode;+};++function GoalStatusRow({ children }: GoalStatusRowProps) {+ return (+ <div+ style={{+ ...styles.tnum,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ gap: 10,+ }}+ >+ {children}+ </div>+ );+}diff --git a/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsx b/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsxindex 56249c3a02..e31a739686 100644--- a/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsx+++ b/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsx@@ -4,7 +4,9 @@ import { useTranslation } from 'react-i18next';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 { useFeatureFlag } from '#hooks/useFeatureFlag';import { envelopeBudget } from '#spreadsheet/bindings';import { useEnvelopeSheetValue } from './EnvelopeBudgetComponents';@@ -14,6 +16,7 @@ export type BalanceMenuActions = {onTransfer?: () => void;onCarryover?: (carryOver: boolean) => void;onCover?: () => void;+ onFundGoal?: (amount: IntegerAmount) => void;};export function useBalanceMenu({@@ -21,14 +24,28 @@ export function useBalanceMenu({onTransfer,onCarryover,onCover,+ onFundGoal,}: BalanceMenuActions) {const { t } = useTranslation();+ const isGoalTemplatesEnabled = useFeatureFlag('goalTemplatesEnabled');const carryover = useEnvelopeSheetValue(envelopeBudget.catCarryover(categoryId),);const balance =useEnvelopeSheetValue(envelopeBudget.catBalance(categoryId)) ?? 0;+ const goal = useEnvelopeSheetValue(envelopeBudget.catGoal(categoryId));+ const longGoal = useEnvelopeSheetValue(+ envelopeBudget.catLongGoal(categoryId),+ );+ const budgeted =+ useEnvelopeSheetValue(envelopeBudget.catBudgeted(categoryId)) ?? 0;+ const toBudget = useEnvelopeSheetValue(envelopeBudget.toBudget) ?? 0;++ const fundAmount =+ isGoalTemplatesEnabled && onFundGoal && goal != null && longGoal !== 1+ ? Math.min(goal - budgeted, toBudget)+ : 0;const onMenuSelect = (name: string) => {switch (name) {@@ -41,6 +58,9 @@ export function useBalanceMenu({case 'cover':onCover?.();break;+ case 'fund-goal':+ onFundGoal?.(fundAmount);+ break;default:throw new Error(`Unrecognized menu option: ${name}`);}@@ -63,6 +83,14 @@ export function useBalanceMenu({},]: []),+ ...(fundAmount > 0+ ? [+ {+ name: 'fund-goal',+ text: t('Fund goal from To Budget'),+ },+ ]+ : []),{name: 'carryover',text: carryover@@ -85,6 +113,7 @@ export function BalanceMenu({onTransfer,onCarryover,onCover,+ onFundGoal,...props}: BalanceMenuProps) {const { items, onMenuSelect } = useBalanceMenu({@@ -92,6 +121,7 @@ export function BalanceMenu({onTransfer,onCarryover,onCover,+ onFundGoal,});return <Menu {...props} onMenuSelect={onMenuSelect} items={items} />;diff --git a/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.test.tsx b/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.test.tsxnew file mode 100644index 0000000000..7923f7d43b--- /dev/null+++ b/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.test.tsx@@ -0,0 +1,98 @@+import { initServer } from '@actual-app/core/platform/client/connection';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++import { SheetNameProvider } from '#hooks/useSheetName';+import {+ configureTestAppStore,+ createTestQueryClient,+ TestProviders,+} from '#mocks';+import { mergeSyncedPrefs } from '#prefs/prefsSlice';++import { BalanceMovementMenu } from './BalanceMovementMenu';++vi.mock(+ '@actual-app/core/platform/client/connection',+ () => import('#mocks/connection'),+);++// Values are keyed by the fully qualified cell name, so a menu that reads+// another month's sheet than the one it acts on would find nothing+let sheetValues: Record<string, number | null> = {};++vi.mock('#hooks/useSheetValue', async () => {+ const { useSheetName } = await import('#hooks/useSheetName');+ return {+ useSheetValue: (binding: Parameters<typeof useSheetName>[0]) => {+ const { fullSheetName } = useSheetName(binding);+ return sheetValues[fullSheetName] ?? null;+ },+ };+});++function renderMenu() {+ 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' }));+ initServer({+ 'get-categories': async () => ({ grouped: [], list: [] }),+ query: async () => ({ data: [], dependencies: [] }),+ });+ render(+ <TestProviders queryClient={client} store={store}>+ <SheetNameProvider name="budget202401">+ <BalanceMovementMenu+ categoryId="groceries"+ month="2024-01"+ onBudgetAction={onBudgetAction}+ onClose={onClose}+ />+ </SheetNameProvider>+ </TestProviders>,+ );+ return { onBudgetAction, onClose };+}++describe('BalanceMovementMenu', () => {+ beforeEach(() => {+ sheetValues = {+ 'budget202401!goal-groceries': 65000,+ 'budget202401!budget-groceries': 40000,+ 'budget202401!leftover-groceries': 40000,+ 'budget202401!long-goal-groceries': null,+ 'budget202401!to-budget': 50000,+ };+ });++ it('shows the goal status and funds the goal from To Budget for that month', async () => {+ const { onBudgetAction, onClose } = renderMenu();++ expect(+ await screen.findByText('Underfunded (-250.00)'),+ ).toBeInTheDocument();+ await userEvent.click(screen.getByText('Fund goal from To Budget'));++ expect(onBudgetAction).toHaveBeenCalledExactlyOnceWith(+ '2024-01',+ 'transfer-available',+ { amount: 25000, category: 'groceries' },+ );+ expect(onClose).toHaveBeenCalledOnce();+ });++ it('does not offer funding when To Budget is empty', async () => {+ sheetValues['budget202401!to-budget'] = 0;+ renderMenu();++ expect(+ await screen.findByText('Underfunded (-250.00)'),+ ).toBeInTheDocument();+ expect(+ screen.queryByText('Fund goal from To Budget'),+ ).not.toBeInTheDocument();+ });+});diff --git a/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.tsx b/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.tsxindex cff42b85e4..081e32bdca 100644--- a/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.tsx+++ b/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.tsx@@ -1,5 +1,8 @@import React, { useCallback, useRef, useState } from 'react';+import { theme } from '@actual-app/components/theme';++import { GoalStatus } from '#components/budget/GoalStatus';import { useFormat } from '#hooks/useFormat';import { envelopeBudget } from '#spreadsheet/bindings';@@ -43,6 +46,18 @@ export function BalanceMovementMenu({{menu === 'menu' && (<BalanceMenucategoryId={categoryId}+ header={+ <GoalStatus+ balance={envelopeBudget.catBalance(categoryId)}+ goal={envelopeBudget.catGoal(categoryId)}+ budgeted={envelopeBudget.catBudgeted(categoryId)}+ longGoal={envelopeBudget.catLongGoal(categoryId)}+ style={{+ padding: 10,+ borderBottom: '1px solid ' + theme.menuBorder,+ }}+ />+ }onCarryover={carryover => {onBudgetAction(month, 'carryover', {category: categoryId,@@ -52,6 +67,13 @@ export function BalanceMovementMenu({}}onTransfer={() => setMenu('transfer')}onCover={() => setMenu('cover')}+ onFundGoal={amount => {+ onBudgetAction(month, 'transfer-available', {+ amount,+ category: categoryId,+ });+ onClose();+ }}/>)}diff --git a/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx b/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsxindex 472b8f6b29..5331a6ffa1 100644--- a/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx+++ b/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx@@ -523,7 +523,6 @@ export const ExpenseCategoryMonth = memo(function ExpenseCategoryMonth({goal={envelopeBudget.catGoal(category.id)}budgeted={envelopeBudget.catBudgeted(category.id)}longGoal={envelopeBudget.catLongGoal(category.id)}- tooltipDisabled={balanceMenuOpen}/></Button>diff --git a/packages/desktop-client/src/components/budget/tracking/TrackingBudgetComponents.tsx b/packages/desktop-client/src/components/budget/tracking/TrackingBudgetComponents.tsxindex 4980feebd4..2c873eec29 100644--- a/packages/desktop-client/src/components/budget/tracking/TrackingBudgetComponents.tsx+++ b/packages/desktop-client/src/components/budget/tracking/TrackingBudgetComponents.tsx@@ -19,6 +19,7 @@ import { css } from '@emotion/css';import { t } from 'i18next';import { BalanceWithCarryover } from '#components/budget/BalanceWithCarryover';+import { GoalStatus } from '#components/budget/GoalStatus';import { makeAmountGrey } from '#components/budget/util';import { NotesButton } from '#components/NotesButton';import { CellValue, CellValueText } from '#components/spreadsheet/CellValue';@@ -492,6 +493,18 @@ export const CategoryMonth = memo(function CategoryMonth({><BalanceMenucategoryId={category.id}+ header={+ <GoalStatus+ balance={trackingBudget.catBalance(category.id)}+ goal={trackingBudget.catGoal(category.id)}+ budgeted={trackingBudget.catBudgeted(category.id)}+ longGoal={trackingBudget.catLongGoal(category.id)}+ style={{+ padding: 10,+ borderBottom: '1px solid ' + theme.menuBorder,+ }}+ />+ }onCarryover={carryover => {onMenuAction(month, 'carryover', {category: category.id,diff --git a/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.test.tsx b/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.test.tsxnew file mode 100644index 0000000000..29d38c7e40--- /dev/null+++ b/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.test.tsx@@ -0,0 +1,102 @@+import { GridList } from 'react-aria-components';+import { MemoryRouter } from 'react-router';++import { initServer } from '@actual-app/core/platform/client/connection';+import type { CategoryEntity } from '@actual-app/core/types/models';+import { act, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++import { SheetNameProvider } from '#hooks/useSheetName';+import {+ configureTestAppStore,+ createTestQueryClient,+ TestProviders,+} from '#mocks';++import { ExpenseCategoryListItem } from './ExpenseCategoryListItem';++vi.mock(+ '@actual-app/core/platform/client/connection',+ () => import('#mocks/connection'),+);+vi.mock('@actual-app/components/hooks/useResponsive', () => ({+ useResponsive: () => ({ isNarrowWidth: true }),+}));+vi.mock('#hooks/useSheetValue', () => ({+ useSheetValue: () => null,+}));+// Only the balance cell matters here; the other cells need schedule and+// spreadsheet providers that are unrelated to the balance menu+vi.mock('./BudgetCell', () => ({ BudgetCell: () => null }));+vi.mock('./SpentCell', () => ({ SpentCell: () => null }));++const category: CategoryEntity = {+ id: 'groceries',+ name: 'Groceries',+ group: 'usual',+ is_income: false,+};++function renderItem() {+ const onBudgetAction =+ vi.fn<(month: string, action: string, args: unknown) => void>();+ const client = createTestQueryClient();+ const store = configureTestAppStore({ queryClient: client });+ initServer({+ 'get-categories': async () => ({ grouped: [], list: [category] }),+ query: async () => ({ data: [], dependencies: [] }),+ });+ render(+ <TestProviders queryClient={client} store={store}>+ <MemoryRouter>+ <SheetNameProvider name="budget202401">+ <GridList aria-label="Categories" items={[category]}>+ {item => (+ <ExpenseCategoryListItem+ value={item}+ month="2024-01"+ isHidden={false}+ show3Columns+ showBudgetedColumn+ onEditCategory={vi.fn()}+ onBudgetAction={onBudgetAction}+ />+ )}+ </GridList>+ </SheetNameProvider>+ </MemoryRouter>+ </TestProviders>,+ );+ return { onBudgetAction, store };+}++describe('ExpenseCategoryListItem', () => {+ it('funds the goal from To Budget through the envelope balance menu', async () => {+ const { onBudgetAction, store } = renderItem();++ await userEvent.click(+ await screen.findByRole('button', {+ name: 'Open balance menu for Groceries category',+ }),+ );++ const [modal] = store.getState().modals.modalStack;+ if (modal?.name !== 'envelope-balance-menu') {+ throw new Error(`Expected the envelope balance menu, got ${modal?.name}`);+ }+ const { options } = modal;+ expect(options.month).toBe('2024-01');++ act(() => options.onFundGoal?.(25000));++ expect(onBudgetAction).toHaveBeenCalledExactlyOnceWith(+ '2024-01',+ 'transfer-available',+ { amount: 25000, category: 'groceries' },+ );+ expect(store.getState().modals.modalStack).toEqual([]);+ expect(store.getState().notifications.notifications).toEqual([+ expect.objectContaining({ message: 'Transferred 250.00 to Groceries' }),+ ]);+ });+});diff --git a/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.tsx b/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.tsxindex 30ccbfa1bf..56b282b492 100644--- a/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.tsx+++ b/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.tsx@@ -12,6 +12,7 @@ import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';import type { BudgetType } from '@actual-app/core/server/prefs';import * as monthUtils from '@actual-app/core/shared/months';+import type { IntegerAmount } from '@actual-app/core/shared/util';import type { CategoryEntity } from '@actual-app/core/types/models';import { useCategoriesById } from '#hooks/useCategories';@@ -360,6 +361,35 @@ export function ExpenseCategoryListItem({format,]);+ const onFundGoal = useCallback(+ (amount: IntegerAmount) => {+ if (!category) {+ return;+ }+ onBudgetAction(month, 'transfer-available', {+ amount,+ category: category.id,+ });+ dispatch(collapseModals({ rootModalName: balanceMenuModalName }));+ showUndoNotification({+ message: t('Transferred {{amount}} to {{categoryName}}', {+ amount: format(amount, 'financial'),+ categoryName: category.name,+ }),+ });+ },+ [+ category,+ dispatch,+ month,+ onBudgetAction,+ balanceMenuModalName,+ showUndoNotification,+ t,+ format,+ ],+ );+const onOpenBalanceMenu = useCallback(() => {if (!category) {return;@@ -375,6 +405,7 @@ export function ExpenseCategoryListItem({onCarryover,onTransfer,onCover,+ onFundGoal,},},}),@@ -401,6 +432,7 @@ export function ExpenseCategoryListItem({onCarryover,onTransfer,onCover,+ onFundGoal,]);const navigate = useNavigate();diff --git a/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.test.tsx b/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.test.tsxnew file mode 100644index 0000000000..5883cc6b72--- /dev/null+++ b/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.test.tsx@@ -0,0 +1,191 @@+import { initServer } from '@actual-app/core/platform/client/connection';+import type { CategoryEntity } from '@actual-app/core/types/models';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++import { SheetNameProvider } from '#hooks/useSheetName';+import {+ configureTestAppStore,+ createTestQueryClient,+ TestProviders,+} from '#mocks';+import { mergeSyncedPrefs } from '#prefs/prefsSlice';++import { EnvelopeBalanceMenuModal } from './EnvelopeBalanceMenuModal';++vi.mock(+ '@actual-app/core/platform/client/connection',+ () => import('#mocks/connection'),+);+vi.mock('@actual-app/components/hooks/useResponsive', () => ({+ useResponsive: () => ({ isNarrowWidth: true }),+}));++let sheetValues: Record<string, number | null> = {};++vi.mock('#hooks/useSheetValue', () => ({+ useSheetValue: (binding: string | { name: string }) => {+ const name = typeof binding === 'string' ? binding : binding.name;+ return sheetValues[name] ?? null;+ },+}));++const category: CategoryEntity = {+ id: 'groceries',+ name: 'Groceries',+ group: 'usual',+ is_income: false,+};++function setSheetValues({+ goal = 65000,+ budget = 40000,+ leftover = 40000,+ longGoal = null,+ toBudget = 50000,+}: {+ goal?: number | null;+ budget?: number;+ leftover?: number;+ longGoal?: number | null;+ toBudget?: number;+} = {}) {+ sheetValues = {+ 'goal-groceries': goal,+ 'budget-groceries': budget,+ 'leftover-groceries': leftover,+ 'long-goal-groceries': longGoal,+ 'to-budget': toBudget,+ };+}++function renderModal({+ isGoalTemplatesEnabled = true,+}: { isGoalTemplatesEnabled?: boolean } = {}) {+ const onFundGoal = vi.fn<(amount: number) => void>();+ const client = createTestQueryClient();+ const store = configureTestAppStore({ queryClient: client });+ if (isGoalTemplatesEnabled) {+ store.dispatch(mergeSyncedPrefs({ 'flags.goalTemplatesEnabled': 'true' }));+ }+ initServer({+ 'get-categories': async () => ({ grouped: [], list: [category] }),+ query: async () => ({ data: [], dependencies: [] }),+ });+ render(+ <TestProviders queryClient={client} store={store}>+ <SheetNameProvider name="budget202401">+ <EnvelopeBalanceMenuModal+ categoryId={category.id}+ onFundGoal={onFundGoal}+ />+ </SheetNameProvider>+ </TestProviders>,+ );+ return { onFundGoal };+}++const fundGoalLabel = 'Fund goal from To Budget';++describe('EnvelopeBalanceMenuModal', () => {+ beforeEach(() => {+ setSheetValues();+ });++ it('shows the goal status, progress and funds the shortfall', async () => {+ const { onFundGoal } = renderModal();++ expect(+ await screen.findByText('Underfunded (-250.00)'),+ ).toBeInTheDocument();+ expect(screen.getByRole('progressbar')).toHaveAttribute(+ 'aria-valuenow',+ '61',+ );++ await userEvent.click(screen.getByText(fundGoalLabel));+ expect(onFundGoal).toHaveBeenCalledWith(25000);+ });++ it('never shows a full bar while the goal is underfunded', async () => {+ setSheetValues({ goal: 100000, budget: 99600 });+ renderModal();++ expect(await screen.findByText('Underfunded (-4.00)')).toBeInTheDocument();+ expect(screen.getByRole('progressbar')).toHaveAttribute(+ 'aria-valuenow',+ '99',+ );+ });++ it('funds only what is left in To Budget', async () => {+ setSheetValues({ toBudget: 10000 });+ const { onFundGoal } = renderModal();++ await userEvent.click(await screen.findByText(fundGoalLabel));+ expect(onFundGoal).toHaveBeenCalledWith(10000);+ });++ it.each([0, -5000])(+ 'hides the fund item when To Budget is %d',+ async toBudget => {+ setSheetValues({ toBudget });+ renderModal();++ expect(+ await screen.findByText('Underfunded (-250.00)'),+ ).toBeInTheDocument();+ expect(screen.queryByText(fundGoalLabel)).not.toBeInTheDocument();+ },+ );++ it('hides the fund item when the goal is fully funded', async () => {+ setSheetValues({ budget: 65000 });+ renderModal();++ expect(await screen.findByText('Fully funded')).toBeInTheDocument();+ expect(screen.queryByText(fundGoalLabel)).not.toBeInTheDocument();+ });++ it('uses the balance for long goals and does not offer funding', async () => {+ setSheetValues({ goal: 100000, leftover: 50000, longGoal: 1 });+ renderModal();++ expect(+ await screen.findByText('Underfunded (-500.00)'),+ ).toBeInTheDocument();+ expect(screen.getByRole('progressbar')).toHaveAttribute(+ 'aria-valuenow',+ '50',+ );+ expect(screen.queryByText(fundGoalLabel)).not.toBeInTheDocument();+ });++ it('shows nothing goal related without a stored goal', async () => {+ setSheetValues({ goal: null });+ renderModal();++ expect(await screen.findByText('Groceries')).toBeInTheDocument();+ expect(screen.queryByText(/funded/)).not.toBeInTheDocument();+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();+ expect(screen.queryByText(fundGoalLabel)).not.toBeInTheDocument();+ });++ it('shows nothing goal related when goal templates are disabled', async () => {+ renderModal({ isGoalTemplatesEnabled: false });++ expect(await screen.findByText('Groceries')).toBeInTheDocument();+ expect(screen.queryByText(/funded/)).not.toBeInTheDocument();+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();+ expect(screen.queryByText(fundGoalLabel)).not.toBeInTheDocument();+ });++ it('shows the status without a progress bar for a zero goal', async () => {+ setSheetValues({ goal: 0 });+ renderModal();++ expect(await screen.findByText('Overfunded (400.00)')).toBeInTheDocument();+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();+ expect(screen.queryByText(fundGoalLabel)).not.toBeInTheDocument();+ });+});diff --git a/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.tsx b/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.tsxindex 957b837e17..b6ba4c7076 100644--- a/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.tsx+++ b/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.tsx@@ -19,6 +19,7 @@ export function EnvelopeBalanceMenuModal({onCarryover,onTransfer,onCover,+ onFundGoal,}: EnvelopeBalanceMenuModalProps) {const { data: category } = useCategory(categoryId);const { items, onMenuSelect } = useBalanceMenu({@@ -26,6 +27,7 @@ export function EnvelopeBalanceMenuModal({onCarryover,onTransfer,onCover,+ onFundGoal,});if (!category) {diff --git a/packages/desktop-client/src/modals/modalsSlice.ts b/packages/desktop-client/src/modals/modalsSlice.tsindex d84b7b698a..bad2b28ae9 100644--- a/packages/desktop-client/src/modals/modalsSlice.ts+++ b/packages/desktop-client/src/modals/modalsSlice.ts@@ -487,6 +487,7 @@ export type Modal =onCarryover?: (carryover: boolean) => void;onTransfer?: () => void;onCover?: () => void;+ onFundGoal?: (amount: IntegerAmount) => void;};}| {diff --git a/packages/docs/docs/experimental/budget-automation.md b/packages/docs/docs/experimental/budget-automation.mdindex 85db6a4362..2e3bbdf137 100644--- a/packages/docs/docs/experimental/budget-automation.md+++ b/packages/docs/docs/experimental/budget-automation.md@@ -298,17 +298,17 @@ There are 3 Fridays in July, but the Balance cap holds our grocery budget at 600### Budget Indicator {#budget-indicator}-After automations run, each category’s budget indicator appears as the color of its balance text. Hover over a balance to see the matching tooltip.+After automations run, each category’s budget indicator appears as the color of its balance text. Click a balance to see its goal status at the top of the balance menu.The example below shows these states: normal (no automation), empty (no automation), projected budget met (green), projected budget not met (orange), and negative balance (red).<img width="724" alt="Category balances in the normal, empty, green, orange and red states" src="/img/experimental/[email protected]" />-The tooltip will give you more information about your budget and balance:+The goal status gives you more information about your budget and balance, including a progress bar:-<img width="243" alt="The balance tooltip for a fully funded category" src="/img/experimental/[email protected]" />+<img width="228" alt="The balance menu showing the goal status for a fully funded category" src="/img/experimental/[email protected]" />-<img width="247" alt="The balance tooltip for an underfunded category" src="/img/experimental/[email protected]" />+<img width="228" alt="The balance menu showing the goal status for an underfunded category" src="/img/experimental/[email protected]" />### Long-term Goal {#long-term-goal}@@ -321,16 +321,16 @@ 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 tooltip.+- 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.:::-The tooltip will give you information regarding your progress:+The goal status shows your progress:-<img width="239" alt="The long-term goal tooltip for an underfunded category" src="/img/experimental/[email protected]" />+<img width="228" alt="The balance menu showing the long-term goal status for an underfunded category" src="/img/experimental/[email protected]" />-<img width="222" alt="The long-term goal tooltip for a fully funded category" src="/img/experimental/[email protected]" />+<img width="228" alt="The balance menu showing the long-term goal status for a fully funded category" src="/img/experimental/[email protected]" />-<img width="230" alt="The long-term goal tooltip for an overfunded category" src="/img/experimental/[email protected]" />+<img width="228" alt="The balance menu showing the long-term goal status for an overfunded category" src="/img/experimental/[email protected]" />---@@ -360,6 +360,8 @@ In the budget header menu you will see the following options:<img width="724" alt="The category group menu with Overwrite with templates highlighted" src="/img/experimental/[email protected]" />+- **Fund a single goal from To Budget** (envelope budgeting only): If a category is underfunded and you have money left in To Budget, click the category balance and choose "Fund goal from To Budget". This adds the missing amount to the category's budget, but never more than what is left in To Budget for that month. Unlike "Overwrite with template", it never lowers the budgeted amount. It is not offered for long-term goals. This normally also reduces To Budget in the following months. If the category is overspent and does not use rollover, the added budget can offset the overspending carry-forward, so the following month's To Budget can remain unchanged for that amount.+---## End of Month Cleanup {#month-end-cleanup}diff --git a/packages/docs/docs/experimental/goal-templates.md b/packages/docs/docs/experimental/goal-templates.mdindex c1567ba2e8..c15dc15a6e 100644--- a/packages/docs/docs/experimental/goal-templates.md+++ b/packages/docs/docs/experimental/goal-templates.md@@ -74,7 +74,7 @@ This goal value is based on the maximum amount that the templates in a category#### Goal Indicator Information-If you hover over the balance value in a templated category, a tooltip will appear with info on the status of that category with respect to its templates.+Click the balance value in a templated category to see its goal status at the top of the balance menu. It shows the status of that category with respect to its templates, including a progress bar.#### Long term goals@@ -83,7 +83,7 @@ By default, the goal information displayed in the goal indicator is shown on a mIf you would like the goal and associated indication color to be based on the category `Balance` instead of the budgeted amount, see the [Goal Directive option](#goal-directive).This is a special template that overrides the goal amount and bases the goal indicator on category balance.-<img width="222" alt="The balance tooltip for a long-term goal" src="/img/experimental/[email protected]" />+<img width="228" alt="The balance menu showing the goal status for a long-term goal" src="/img/experimental/[email protected]" />### Multiple Template Linesdiff --git a/packages/docs/static/img/experimental/[email protected] b/packages/docs/static/img/experimental/[email protected]index 0302d7963c..5f402b7db5 100644Binary files a/packages/docs/static/img/experimental/[email protected] and b/packages/docs/static/img/experimental/[email protected] differdiff --git a/packages/docs/static/img/experimental/[email protected] b/packages/docs/static/img/experimental/[email protected]index 4e1d122139..b845a2ebec 100644Binary files a/packages/docs/static/img/experimental/[email protected] and b/packages/docs/static/img/experimental/[email protected] differdiff --git a/packages/docs/static/img/experimental/[email protected] b/packages/docs/static/img/experimental/[email protected]index fd4e7c2da7..646a2b9521 100644Binary files a/packages/docs/static/img/experimental/[email protected] and b/packages/docs/static/img/experimental/[email protected] differdiff --git a/packages/docs/static/img/experimental/[email protected] b/packages/docs/static/img/experimental/[email protected]index 05779cd3ac..d7dee69b95 100644Binary files a/packages/docs/static/img/experimental/[email protected] and b/packages/docs/static/img/experimental/[email protected] differdiff --git a/packages/docs/static/img/experimental/[email protected] b/packages/docs/static/img/experimental/[email protected]index 67f66b113a..4d7195ebff 100644Binary files a/packages/docs/static/img/experimental/[email protected] and b/packages/docs/static/img/experimental/[email protected] differdiff --git a/packages/docs/static/img/experimental/[email protected] b/packages/docs/static/img/experimental/[email protected]index 4af176a925..b845a2ebec 100644Binary files a/packages/docs/static/img/experimental/[email protected] and b/packages/docs/static/img/experimental/[email protected] differdiff --git a/packages/loot-core/src/server/budget/actions.test.ts b/packages/loot-core/src/server/budget/actions.test.tsindex cea172c248..639fe8f193 100644--- a/packages/loot-core/src/server/budget/actions.test.ts+++ b/packages/loot-core/src/server/budget/actions.test.ts@@ -12,6 +12,7 @@ import {setBudget,setCategoryCarryover,setNMonthAvg,+ transferAvailable,} from './actions';import * as budget from './base';@@ -231,6 +232,108 @@ describe('coverOverbudgeted', () => {});});+describe('transferAvailable', () => {+ beforeEach(global.emptyDatabase());+ afterEach(global.emptyDatabase());++ // Setup: 2024-01 with 100.00 income, cat1 budgeted 10.00, so 90.00 to budget+ async function setupFundedDatabase() {+ await db.insertAccount({ id: 'account1', name: 'Account 1' });+ await db.insertCategoryGroup({+ id: 'income-group',+ name: 'Income',+ is_income: 1,+ });+ await db.insertCategory({+ id: 'income-cat',+ name: 'Income',+ cat_group: 'income-group',+ is_income: 1,+ });+ await db.insertCategoryGroup({+ id: 'group1',+ name: 'group1',+ is_income: 0,+ });+ await db.insertCategory({+ id: 'cat1',+ name: 'cat1',+ cat_group: 'group1',+ is_income: 0,+ });++ await sheet.loadSpreadsheet(db);+ await budget.createBudget(['2024-01']);++ await db.insertTransaction({+ date: '2024-01-15',+ amount: 10000,+ account: 'account1',+ category: 'income-cat',+ });+ await setBudget({ category: 'cat1', month: '2024-01', amount: 1000 });+ await sheet.waitOnSpreadsheet();+ }++ it('adds the full amount when it is within To Budget', async () => {+ await setupFundedDatabase();+ expect(await getSheetValue('budget202401', 'to-budget')).toBe(9000);++ await transferAvailable({+ month: '2024-01',+ amount: 3000,+ category: 'cat1',+ });+ await sheet.waitOnSpreadsheet();++ expect(await getSheetValue('budget202401', 'budget-cat1')).toBe(4000);+ expect(await getSheetValue('budget202401', 'to-budget')).toBe(6000);+ });++ it('caps the amount at To Budget so it never goes negative', async () => {+ await setupFundedDatabase();++ await transferAvailable({+ month: '2024-01',+ amount: 20000,+ category: 'cat1',+ });+ await sheet.waitOnSpreadsheet();++ expect(await getSheetValue('budget202401', 'budget-cat1')).toBe(10000);+ expect(await getSheetValue('budget202401', 'to-budget')).toBe(0);+ });++ it('does not change the budget when To Budget is not positive', async () => {+ // Setup: 2024-02 is 90 overbudgeted+ await prepareDatabase();++ await transferAvailable({+ month: '2024-02',+ amount: 50,+ category: 'cat1',+ });+ await sheet.waitOnSpreadsheet();++ expect(await getSheetValue('budget202402', 'budget-cat1')).toBe(0);+ expect(await getSheetValue('budget202402', 'to-budget')).toBe(-90);+ });++ it('never lowers the budget for a negative amount', async () => {+ await setupFundedDatabase();++ await transferAvailable({+ month: '2024-01',+ amount: -500,+ category: 'cat1',+ });+ await sheet.waitOnSpreadsheet();++ expect(await getSheetValue('budget202401', 'budget-cat1')).toBe(1000);+ expect(await getSheetValue('budget202401', 'to-budget')).toBe(9000);+ });+});+// Setup: 2024-02, is 90 overbudgeted// with balances of cat1 = 100, cat2 = -20, cat3 = 10async function prepareDatabase() {diff --git a/upcoming-release-notes/category-funding.md b/upcoming-release-notes/category-funding.mdnew file mode 100644index 0000000000..4ee883b163--- /dev/null+++ b/upcoming-release-notes/category-funding.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [mattm4444]+---++Show budget goal progress in the category balance menu, and add an option to fund an underfunded goal from To Budget, up to what is left to budget that month