A local-first personal finance app
improve experimental budget automation UI (#7597)
Matt Fiddaman6298f6a32481
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex ce4fb1d62a..ebfe9c7d91 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -37,9 +37,13 @@"#components/banksync/useBankSyncAccountSettings": "./src/components/banksync/useBankSyncAccountSettings.ts","#components/budget": "./src/components/budget/index.tsx","#components/budget/goals/actions": "./src/components/budget/goals/actions.ts",+ "#components/budget/goals/automationExamples": "./src/components/budget/goals/automationExamples.ts","#components/budget/goals/constants": "./src/components/budget/goals/constants.ts",+ "#components/budget/goals/displayTemplateMeta": "./src/components/budget/goals/displayTemplateMeta.ts",+ "#components/budget/goals/formatMonthLabel": "./src/components/budget/goals/formatMonthLabel.ts","#components/budget/goals/reducer": "./src/components/budget/goals/reducer.ts","#components/budget/goals/useBudgetAutomationCategories": "./src/components/budget/goals/useBudgetAutomationCategories.ts",+ "#components/budget/goals/validateAutomation": "./src/components/budget/goals/validateAutomation.ts","#components/budget/util": "./src/components/budget/util.ts","#components/codemirror/autocompleteTabAccept": "./src/components/codemirror/autocompleteTabAccept.ts","#components/mobile/utils": "./src/components/mobile/utils.ts",diff --git a/packages/desktop-client/src/components/budget/goals/ActiveEditor.tsx b/packages/desktop-client/src/components/budget/goals/ActiveEditor.tsxnew file mode 100644index 0000000000..ad122704f0--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/ActiveEditor.tsx@@ -0,0 +1,76 @@+import type {+ CategoryGroupEntity,+ ScheduleEntity,+} from '@actual-app/core/types/models';++import type { Action } from './actions';+import type { ReducerState } from './constants';+import { BySaveAutomation } from './editor/BySaveAutomation';+import { FixedAutomation } from './editor/FixedAutomation';+import { HistoricalAutomation } from './editor/HistoricalAutomation';+import { LimitAutomation } from './editor/LimitAutomation';+import { PercentageAutomation } from './editor/PercentageAutomation';+import { RefillAutomation } from './editor/RefillAutomation';+import { RemainderAutomation } from './editor/RemainderAutomation';+import { ScheduleAutomation } from './editor/ScheduleAutomation';++type ActiveEditorProps = {+ state: ReducerState;+ dispatch: (action: Action) => void;+ schedules: readonly ScheduleEntity[];+ categories: CategoryGroupEntity[];+ hasLimitAutomation: boolean;+ onAddLimitAutomation: () => void;+};++export function ActiveEditor({+ state,+ dispatch,+ schedules,+ categories,+ hasLimitAutomation,+ onAddLimitAutomation,+}: ActiveEditorProps) {+ switch (state.displayType) {+ case 'limit':+ return <LimitAutomation template={state.template} dispatch={dispatch} />;+ case 'refill':+ return (+ <RefillAutomation+ hasLimitAutomation={hasLimitAutomation}+ onAddLimitAutomation={onAddLimitAutomation}+ />+ );+ case 'fixed':+ return <FixedAutomation template={state.template} dispatch={dispatch} />;+ case 'schedule':+ return (+ <ScheduleAutomation+ schedules={schedules}+ template={state.template}+ dispatch={dispatch}+ />+ );+ case 'percentage':+ return (+ <PercentageAutomation+ dispatch={dispatch}+ template={state.template}+ categories={categories}+ />+ );+ case 'historical':+ return (+ <HistoricalAutomation template={state.template} dispatch={dispatch} />+ );+ case 'by':+ return <BySaveAutomation template={state.template} dispatch={dispatch} />;+ case 'remainder':+ return (+ <RemainderAutomation template={state.template} dispatch={dispatch} />+ );+ default:+ state satisfies never;+ return null;+ }+}diff --git a/packages/desktop-client/src/components/budget/goals/BudgetAutomationEditor.tsx b/packages/desktop-client/src/components/budget/goals/BudgetAutomationEditor.tsxindex 77f252188d..23c2d643d4 100644--- a/packages/desktop-client/src/components/budget/goals/BudgetAutomationEditor.tsx+++ b/packages/desktop-client/src/components/budget/goals/BudgetAutomationEditor.tsx@@ -16,14 +16,17 @@ import { FormField, FormLabel, FormTextLabel } from '#components/forms';import { setType } from './actions';import type { Action } from './actions';-import { displayTemplateTypes } from './constants';import type { ReducerState } from './constants';+import { displayTemplateTypes } from './constants';+import { getDisplayTemplateMeta } from './displayTemplateMeta';+import { BySaveAutomation } from './editor/BySaveAutomation';+import { FixedAutomation } from './editor/FixedAutomation';import { HistoricalAutomation } from './editor/HistoricalAutomation';import { LimitAutomation } from './editor/LimitAutomation';import { PercentageAutomation } from './editor/PercentageAutomation';import { RefillAutomation } from './editor/RefillAutomation';+import { RemainderAutomation } from './editor/RemainderAutomation';import { ScheduleAutomation } from './editor/ScheduleAutomation';-import { WeekAutomation } from './editor/WeekAutomation';type BudgetAutomationEditorProps = {inline: boolean;@@ -50,7 +53,7 @@ const displayTypeToDescription = {automation.</Trans>),- week: (+ fixed: (<Trans>Add a fixed amount to this category for each week in the month. Forexample, $100 per week would be $400 per month in a 4-week month.@@ -80,6 +83,18 @@ const displayTypeToDescription = {to account for seasonal changes.</Trans>),+ by: (+ <Trans>+ Spread a target amount across the months between now and a target date.+ Useful for annual goals or saving toward a one-off expense.+ </Trans>+ ),+ remainder: (+ <Trans>+ Split any remaining To Budget across categories using this automation.+ Higher weights take a larger share of the leftover funds.+ </Trans>+ ),};export function BudgetAutomationEditor({@@ -108,9 +123,9 @@ export function BudgetAutomationEditor({/>);break;- case 'week':+ case 'fixed':automationEditor = (- <WeekAutomation template={state.template} dispatch={dispatch} />+ <FixedAutomation template={state.template} dispatch={dispatch} />);break;case 'schedule':@@ -136,6 +151,16 @@ export function BudgetAutomationEditor({<HistoricalAutomation template={state.template} dispatch={dispatch} />);break;+ case 'by':+ automationEditor = (+ <BySaveAutomation template={state.template} dispatch={dispatch} />+ );+ break;+ case 'remainder':+ automationEditor = (+ <RemainderAutomation template={state.template} dispatch={dispatch} />+ );+ break;default:state satisfies never;automationEditor = (@@ -165,7 +190,10 @@ export function BudgetAutomationEditor({<InitialFocus><Selectid="type-field"- options={displayTemplateTypes}+ options={displayTemplateTypes.map(type => [+ type,+ getDisplayTemplateMeta(type).label,+ ])}defaultLabel={t('Select an option')}value={state.displayType}onChange={type => type && dispatch(setType(type))}diff --git a/packages/desktop-client/src/components/budget/goals/BudgetAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/BudgetAutomationReadOnly.tsxindex f5d46ebf3d..ec46d7da11 100644--- a/packages/desktop-client/src/components/budget/goals/BudgetAutomationReadOnly.tsx+++ b/packages/desktop-client/src/components/budget/goals/BudgetAutomationReadOnly.tsx@@ -14,12 +14,14 @@ import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';import type { ReducerState } from './constants';+import { BySaveAutomationReadOnly } from './editor/BySaveAutomationReadOnly';+import { FixedAutomationReadOnly } from './editor/FixedAutomationReadOnly';import { HistoricalAutomationReadOnly } from './editor/HistoricalAutomationReadOnly';import { LimitAutomationReadOnly } from './editor/LimitAutomationReadOnly';import { PercentageAutomationReadOnly } from './editor/PercentageAutomationReadOnly';import { RefillAutomationReadOnly } from './editor/RefillAutomationReadOnly';+import { RemainderAutomationReadOnly } from './editor/RemainderAutomationReadOnly';import { ScheduleAutomationReadOnly } from './editor/ScheduleAutomationReadOnly';-import { WeekAutomationReadOnly } from './editor/WeekAutomationReadOnly';type BudgetAutomationReadOnlyProps = {state: ReducerState;@@ -52,8 +54,10 @@ export function BudgetAutomationReadOnly({case 'refill':automationReadOnly = <RefillAutomationReadOnly />;break;- case 'week':- automationReadOnly = <WeekAutomationReadOnly template={state.template} />;+ case 'fixed':+ automationReadOnly = (+ <FixedAutomationReadOnly template={state.template} />+ );break;case 'schedule':automationReadOnly = (@@ -73,7 +77,18 @@ export function BudgetAutomationReadOnly({<HistoricalAutomationReadOnly template={state.template} />);break;+ case 'by':+ automationReadOnly = (+ <BySaveAutomationReadOnly template={state.template} />+ );+ break;+ case 'remainder':+ automationReadOnly = (+ <RemainderAutomationReadOnly template={state.template} />+ );+ break;default:+ state satisfies never;automationReadOnly = (<Text><Trans>Unrecognized automation type.</Trans>diff --git a/packages/desktop-client/src/components/budget/goals/CategoryAutomationButton.tsx b/packages/desktop-client/src/components/budget/goals/CategoryAutomationButton.tsxindex 36aac905c9..7b8fea5c2c 100644--- a/packages/desktop-client/src/components/budget/goals/CategoryAutomationButton.tsx+++ b/packages/desktop-client/src/components/budget/goals/CategoryAutomationButton.tsx@@ -1,4 +1,4 @@-import React from 'react';+import React, { useContext } from 'react';import { useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';@@ -8,7 +8,9 @@ import { theme } from '@actual-app/components/theme';import type { CategoryEntity } from '@actual-app/core/types/models';import { css, cx } from '@emotion/css';+import { MonthsContext } from '#components/budget/MonthsContext';import { useFeatureFlag } from '#hooks/useFeatureFlag';+import { useSyncedPref } from '#hooks/useSyncedPref';import { pushModal } from '#modals/modalsSlice';import { useDispatch } from '#redux';@@ -30,15 +32,24 @@ export function CategoryAutomationButton({}: CategoryAutomationButtonProps) {const { t } = useTranslation();const dispatch = useDispatch();+ const monthsContext = useContext(MonthsContext);+ const month = monthsContext?.months?.[0];const goalTemplatesEnabled = useFeatureFlag('goalTemplatesEnabled');const goalTemplatesUIEnabled = useFeatureFlag('goalTemplatesUIEnabled');+ const [budgetType = 'envelope'] = useSyncedPref('budgetType');const hasAutomations = !!category.goal_def?.length;if (!goalTemplatesEnabled || !goalTemplatesUIEnabled) {return null;}+ // Income categories don't accept templates in envelope budgets (only the+ // tracking budget runs templates against income categories).+ if (category.is_income && budgetType !== 'tracking') {+ return null;+ }+return (<Buttonvariant="bare"@@ -59,7 +70,7 @@ export function CategoryAutomationButton({pushModal({modal: {name: 'category-automations-edit',- options: { categoryId: category.id },+ options: { categoryId: category.id, month },},}),);diff --git a/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsx b/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsxnew file mode 100644index 0000000000..925c74af41--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsx@@ -0,0 +1,62 @@+import { Trans } from 'react-i18next';++import type { Template } from '@actual-app/core/types/models/templates';+import type { TransObjectLiteral } from '@actual-app/core/types/util';++import { BySaveAutomationReadOnly } from './editor/BySaveAutomationReadOnly';+import { FixedAutomationReadOnly } from './editor/FixedAutomationReadOnly';+import { HistoricalAutomationReadOnly } from './editor/HistoricalAutomationReadOnly';+import { LimitAutomationReadOnly } from './editor/LimitAutomationReadOnly';+import { PercentageAutomationReadOnly } from './editor/PercentageAutomationReadOnly';+import { RefillAutomationReadOnly } from './editor/RefillAutomationReadOnly';+import { RemainderAutomationReadOnly } from './editor/RemainderAutomationReadOnly';+import { ScheduleAutomationReadOnly } from './editor/ScheduleAutomationReadOnly';++type TemplateSentenceProps = {+ template: Template;+ categoryNameMap: Record<string, string>;+};++export function TemplateSentence({+ template,+ categoryNameMap,+}: TemplateSentenceProps) {+ switch (template.type) {+ case 'limit':+ return <LimitAutomationReadOnly template={template} />;+ case 'refill':+ return <RefillAutomationReadOnly />;+ case 'periodic':+ return <FixedAutomationReadOnly template={template} />;+ case 'schedule':+ return <ScheduleAutomationReadOnly template={template} />;+ case 'percentage':+ return (+ <PercentageAutomationReadOnly+ template={template}+ categoryNameMap={categoryNameMap}+ />+ );+ case 'average':+ case 'copy':+ return <HistoricalAutomationReadOnly template={template} />;+ case 'by':+ return <BySaveAutomationReadOnly template={template} />;+ case 'remainder':+ return <RemainderAutomationReadOnly template={template} />;+ case 'simple':+ case 'spend':+ case 'goal':+ case 'error': {+ const type = template.type;+ return (+ <Trans>+ Unsupported template type: {{ type } satisfies TransObjectLiteral}+ </Trans>+ );+ }+ default:+ template satisfies never;+ return null;+ }+}diff --git a/packages/desktop-client/src/components/budget/goals/automationExamples.ts b/packages/desktop-client/src/components/budget/goals/automationExamples.tsnew file mode 100644index 0000000000..9906bcaf2e--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/automationExamples.ts@@ -0,0 +1,84 @@+import {+ addMonths,+ dayFromDate,+ firstDayOfMonth,+ monthFromDate,+} from '@actual-app/core/shared/months';+import type { Template } from '@actual-app/core/types/models/templates';+import uniqueId from 'lodash/uniqueId';++import type { DisplayTemplateType } from './constants';+import { DEFAULT_PRIORITY } from './reducer';++export type AutomationEntry = {+ id: string;+ template: Template;+ displayType: DisplayTemplateType;+};++export function createAutomationEntry(+ template: Template,+ displayType: DisplayTemplateType,+): AutomationEntry {+ return {+ id: uniqueId('automation-'),+ template,+ displayType,+ };+}++export type AutomationExample = {+ displayType: DisplayTemplateType;+ create: () => AutomationEntry;+};++export function getAutomationExamples(): AutomationExample[] {+ return [+ {+ displayType: 'fixed',+ create: () =>+ createAutomationEntry(+ {+ directive: 'template',+ type: 'periodic',+ amount: 100,+ period: { period: 'month', amount: 1 },+ starting: dayFromDate(firstDayOfMonth(new Date())),+ priority: DEFAULT_PRIORITY,+ },+ 'fixed',+ ),+ },+ {+ displayType: 'by',+ create: () =>+ createAutomationEntry(+ {+ directive: 'template',+ type: 'by',+ amount: 1200,+ // Always 12 months out so users in late-year months don't get a+ // target that's already passed.+ month: addMonths(monthFromDate(new Date()), 12),+ annual: true,+ repeat: 1,+ priority: DEFAULT_PRIORITY,+ },+ 'by',+ ),+ },+ {+ displayType: 'schedule',+ create: () =>+ createAutomationEntry(+ {+ directive: 'template',+ type: 'schedule',+ name: '',+ priority: DEFAULT_PRIORITY,+ },+ 'schedule',+ ),+ },+ ];+}diff --git a/packages/desktop-client/src/components/budget/goals/automationMessages.tsx b/packages/desktop-client/src/components/budget/goals/automationMessages.tsxnew file mode 100644index 0000000000..e784b19123--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/automationMessages.tsx@@ -0,0 +1,178 @@+import { Trans } from 'react-i18next';++import { useFormat } from '#hooks/useFormat';+import { useLocale } from '#hooks/useLocale';++import { formatMonthLabel } from './formatMonthLabel';+import type {+ AutomationErrorKind,+ GlobalConflictKind,+} from './validateAutomation';++export function AutomationErrorTitle({+ error,+}: {+ error: AutomationErrorKind;+}) {+ switch (error.kind) {+ case 'schedule-not-found':+ return <Trans>Schedule not found</Trans>;+ case 'refill-no-cap':+ return <Trans>Refill needs a balance cap</Trans>;+ case 'percentage-out-of-range':+ return <Trans>Percentage out of range</Trans>;+ case 'percentage-no-source':+ return <Trans>Source category missing</Trans>;+ case 'by-no-month':+ return <Trans>Target month missing</Trans>;+ case 'by-target-past':+ return <Trans>Target is in the past</Trans>;+ case 'percentage-source-not-found':+ return <Trans>Source category not recognised</Trans>;+ default:+ error satisfies never;+ return null;+ }+}++export function AutomationErrorShort({+ error,+}: {+ error: AutomationErrorKind;+}) {+ const locale = useLocale();+ switch (error.kind) {+ case 'schedule-not-found':+ return error.name ? (+ <Trans>No schedule named “{{ name: error.name }}”</Trans>+ ) : (+ <Trans>Pick a schedule</Trans>+ );+ case 'refill-no-cap':+ return <Trans>Add a balance cap above</Trans>;+ case 'percentage-out-of-range':+ return (+ <Trans>{{ percent: error.percent }}% must be between 0 and 100</Trans>+ );+ case 'percentage-no-source':+ return <Trans>Pick a source category</Trans>;+ case 'by-no-month':+ return <Trans>Pick a target month</Trans>;+ case 'by-target-past':+ return (+ <Trans>+ {{ month: formatMonthLabel(error.month, locale) }} has already passed+ </Trans>+ );+ case 'percentage-source-not-found':+ return <Trans>Pick a valid income category</Trans>;+ default:+ error satisfies never;+ return null;+ }+}++export function AutomationErrorDetail({+ error,+}: {+ error: AutomationErrorKind;+}) {+ switch (error.kind) {+ case 'schedule-not-found':+ return (+ <Trans>+ Pick an existing schedule, or create one in Schedules. This automation+ can’t run until it’s linked to a schedule.+ </Trans>+ );+ case 'refill-no-cap':+ return (+ <Trans>+ Refill automations must have a “Balance cap” automation+ added to use as the target.+ </Trans>+ );+ case 'percentage-out-of-range':+ return <Trans>Set a value greater than 0% and at most 100%.</Trans>;+ case 'percentage-no-source':+ return (+ <Trans>+ Percentage automations need a source category to calculate against.+ </Trans>+ );+ case 'by-no-month':+ return (+ <Trans>+ Goals by date need a target month. Pick when you want this fully+ funded.+ </Trans>+ );+ case 'by-target-past':+ return (+ <Trans>+ Pick a future month, or switch to a recurring annual goal to keep+ saving.+ </Trans>+ );+ case 'percentage-source-not-found':+ return (+ <Trans>+ The selected source “{{ source: error.source }}” is not a+ known income category.+ </Trans>+ );+ default:+ error satisfies never;+ return null;+ }+}++export function GlobalConflictTitle({+ conflict,+}: {+ conflict: GlobalConflictKind;+}) {+ switch (conflict.kind) {+ case 'over-income':+ return <Trans>Automations will demand more than income</Trans>;+ case 'percent-over-100':+ return (+ <Trans>+ Percent automations total {{ total: Math.round(conflict.total) }}% of+ income+ </Trans>+ );+ default:+ conflict satisfies never;+ return null;+ }+}++export function GlobalConflictDetail({+ conflict,+}: {+ conflict: GlobalConflictKind;+}) {+ const format = useFormat();+ switch (conflict.kind) {+ case 'over-income':+ return (+ <Trans>+ This month’s automations ask for around{' '}+ {{ total: format(conflict.total, 'financial') }} but only{' '}+ {{ income: format(conflict.income, 'financial') }} is available to+ budget. Lower amounts or switch one to “Whatever is left”.+ </Trans>+ );+ case 'percent-over-100':+ return (+ <Trans>+ Your percent automations add up to more than 100% and will be capped+ at 100%.+ </Trans>+ );+ default:+ conflict satisfies never;+ return null;+ }+}diff --git a/packages/desktop-client/src/components/budget/goals/constants.ts b/packages/desktop-client/src/components/budget/goals/constants.tsindex f6c310bede..2f11a7c4f1 100644--- a/packages/desktop-client/src/components/budget/goals/constants.ts+++ b/packages/desktop-client/src/components/budget/goals/constants.ts@@ -1,23 +1,27 @@import type {AverageTemplate,+ ByTemplate,CopyTemplate,LimitTemplate,PercentageTemplate,PeriodicTemplate,RefillTemplate,+ RemainderTemplate,ScheduleTemplate,} from '@actual-app/core/types/models/templates';export const displayTemplateTypes = [- ['limit', 'Balance limit'] as const,- ['refill', 'Refill'] as const,- ['week', 'Fixed (weekly)'] as const,- ['schedule', 'Existing schedule'] as const,- ['percentage', 'Percent of category'] as const,- ['historical', 'Copy past budgets'] as const,-];+ 'fixed',+ 'schedule',+ 'by',+ 'percentage',+ 'historical',+ 'limit',+ 'refill',+ 'remainder',+] as const;-export type DisplayTemplateType = (typeof displayTemplateTypes)[number][0];+export type DisplayTemplateType = (typeof displayTemplateTypes)[number];export type ReducerState =| {@@ -30,7 +34,7 @@ export type ReducerState =}| {template: PeriodicTemplate;- displayType: 'week';+ displayType: 'fixed';}| {template: ScheduleTemplate;@@ -43,4 +47,12 @@ export type ReducerState =| {template: CopyTemplate | AverageTemplate;displayType: 'historical';+ }+ | {+ template: ByTemplate;+ displayType: 'by';+ }+ | {+ template: RemainderTemplate;+ displayType: 'remainder';};diff --git a/packages/desktop-client/src/components/budget/goals/displayTemplateMeta.ts b/packages/desktop-client/src/components/budget/goals/displayTemplateMeta.tsnew file mode 100644index 0000000000..016652a4e8--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/displayTemplateMeta.ts@@ -0,0 +1,91 @@+import type { ComponentType, SVGProps } from 'react';++import {+ SvgChartPie,+ SvgEquals,+ SvgMoneyBag,+ SvgPiggyBank,+ SvgShare,+ SvgTime,+} from '@actual-app/components/icons/v1';+import {+ SvgArrowsSynchronize,+ SvgCalendar3,+} from '@actual-app/components/icons/v2';+import { t } from 'i18next';++import type { DisplayTemplateType } from './constants';++type IconComponent = ComponentType<SVGProps<SVGSVGElement>>;++export type DisplayTemplateMeta = {+ label: string;+ description: string;+ icon: IconComponent;+};++export function getDisplayTemplateMeta(+ displayType: DisplayTemplateType,+): DisplayTemplateMeta {+ switch (displayType) {+ case 'fixed':+ return {+ label: t('Fixed amount'),+ description: t('Add a set amount every month, week, day, or year.'),+ icon: SvgPiggyBank,+ };+ case 'schedule':+ return {+ label: t('Cover schedule'),+ description: t('Save up for a recurring scheduled transaction.'),+ icon: SvgCalendar3,+ };+ case 'by':+ return {+ label: t('Save by date'),+ description: t(+ 'Spread a target amount across the months until a deadline.',+ ),+ icon: SvgMoneyBag,+ };+ case 'percentage':+ return {+ label: t('% of income'),+ description: t("A share of this month's or last month's income."),+ icon: SvgChartPie,+ };+ case 'historical':+ return {+ label: t('From history'),+ description: t(+ 'Use past months: average, a specific month, or a copy.',+ ),+ icon: SvgTime,+ };+ case 'limit':+ return {+ label: t('Balance cap'),+ description: t('Never let the category balance exceed a cap.'),+ icon: SvgEquals,+ };+ case 'refill':+ return {+ label: t('Refill to cap'),+ description: t(+ 'Top the category back up to the balance cap each month.',+ ),+ icon: SvgArrowsSynchronize,+ };+ case 'remainder':+ return {+ label: t('Whatever is left'),+ description: t(+ 'Split any remaining To Budget across these categories.',+ ),+ icon: SvgShare,+ };+ default:+ displayType satisfies never;+ throw new Error(`Unknown display type: ${String(displayType)}`);+ }+}diff --git a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsxnew file mode 100644index 0000000000..f5f013bfd1--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx@@ -0,0 +1,116 @@+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { Input } from '@actual-app/components/input';+import { Select } from '@actual-app/components/select';+import { SpaceBetween } from '@actual-app/components/space-between';+import { amountToInteger, integerToAmount } from '@actual-app/core/shared/util';+import type { ByTemplate } from '@actual-app/core/types/models/templates';++import { updateTemplate } from '#components/budget/goals/actions';+import type { Action } from '#components/budget/goals/actions';+import { FormField, FormLabel } from '#components/forms';+import { AmountInput } from '#components/util/AmountInput';+import { GenericInput } from '#components/util/GenericInput';+import { useFormat } from '#hooks/useFormat';++type BySaveAutomationProps = {+ template: ByTemplate;+ dispatch: (action: Action) => void;+};++export const BySaveAutomation = ({+ template,+ dispatch,+}: BySaveAutomationProps) => {+ const { t } = useTranslation();+ const format = useFormat();++ const amount = amountToInteger(+ template.amount,+ format.currency.decimalPlaces,+ );++ const committedRepeat = template.repeat ?? 1;+ const [rawRepeat, setRawRepeat] = useState(String(committedRepeat));+ useEffect(() => {+ setRawRepeat(String(committedRepeat));+ }, [committedRepeat]);+ const commitRepeat = () => {+ const parsed = Math.max(1, Math.trunc(Number(rawRepeat)) || 1);+ setRawRepeat(String(parsed));+ if (parsed !== committedRepeat) {+ dispatch(updateTemplate({ type: 'by', repeat: parsed }));+ }+ };++ return (+ <>+ <SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Total amount')} htmlFor="by-amount-field" />+ <AmountInput+ id="by-amount-field"+ value={amount}+ zeroSign="+"+ onUpdate={(value: number) =>+ dispatch(+ updateTemplate({+ type: 'by',+ amount: integerToAmount(value, format.currency.decimalPlaces),+ }),+ )+ }+ />+ </FormField>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Target date')} htmlFor="by-month-field" />+ <GenericInput+ type="date"+ field="date"+ value={template.month ? `${template.month}-01` : ''}+ onChange={(value: string) =>+ dispatch(+ updateTemplate({+ type: 'by',+ month: value ? value.slice(0, 7) : '',+ }),+ )+ }+ />+ </FormField>+ </SpaceBetween>+ <SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>+ <FormField style={{ flex: 1 }}>+ <FormLabel+ title={t('Repeat every')}+ htmlFor="by-repeat-amount-field"+ />+ <Input+ id="by-repeat-amount-field"+ type="number"+ min={1}+ step={1}+ value={rawRepeat}+ onChangeValue={setRawRepeat}+ onBlur={commitRepeat}+ />+ </FormField>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Period')} htmlFor="by-period-field" />+ <Select+ id="by-period-field"+ value={template.annual ? 'year' : 'month'}+ onChange={value =>+ dispatch(updateTemplate({ type: 'by', annual: value === 'year' }))+ }+ options={[+ ['month', t('Months')],+ ['year', t('Years')],+ ]}+ />+ </FormField>+ </SpaceBetween>+ </>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomationReadOnly.tsxnew file mode 100644index 0000000000..73260b42ef--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomationReadOnly.tsx@@ -0,0 +1,52 @@+import { Trans } from 'react-i18next';++import { amountToInteger } from '@actual-app/core/shared/util';+import type { ByTemplate } from '@actual-app/core/types/models/templates';+import type { TransObjectLiteral } from '@actual-app/core/types/util';++import { formatMonthLabel } from '#components/budget/goals/formatMonthLabel';+import { FinancialText } from '#components/FinancialText';+import { useFormat } from '#hooks/useFormat';+import { useLocale } from '#hooks/useLocale';++type BySaveAutomationReadOnlyProps = {+ template: ByTemplate;+};++export const BySaveAutomationReadOnly = ({+ template,+}: BySaveAutomationReadOnlyProps) => {+ const format = useFormat();+ const locale = useLocale();+ const amount = format(+ amountToInteger(template.amount, format.currency.decimalPlaces),+ 'financial',+ );+ const month = formatMonthLabel(template.month, locale);+ const repeat = template.repeat ?? 1;++ if (template.annual) {+ return (+ <Trans count={repeat}>+ Save <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}+ by {{ month }}, repeating every {{ count: repeat }} years+ </Trans>+ );+ }++ if (template.repeat && template.repeat > 0) {+ return (+ <Trans count={repeat}>+ Save <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}+ by {{ month }}, repeating every {{ count: repeat }} months+ </Trans>+ );+ }++ return (+ <Trans>+ Save <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText> by{' '}+ {{ month }}+ </Trans>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsxnew file mode 100644index 0000000000..db0d90f41a--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx@@ -0,0 +1,124 @@+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { Input } from '@actual-app/components/input';+import { Select } from '@actual-app/components/select';+import { SpaceBetween } from '@actual-app/components/space-between';+import { amountToInteger, integerToAmount } from '@actual-app/core/shared/util';+import type { PeriodicTemplate } from '@actual-app/core/types/models/templates';++import { updateTemplate } from '#components/budget/goals/actions';+import type { Action } from '#components/budget/goals/actions';+import { FormField, FormLabel } from '#components/forms';+import { AmountInput } from '#components/util/AmountInput';+import { GenericInput } from '#components/util/GenericInput';+import { useFormat } from '#hooks/useFormat';++type FixedAutomationProps = {+ template: PeriodicTemplate;+ dispatch: (action: Action) => void;+};++type PeriodUnit = 'day' | 'week' | 'month' | 'year';++export const FixedAutomation = ({+ template,+ dispatch,+}: FixedAutomationProps) => {+ const { t } = useTranslation();+ const periodUnitOptions: Array<[PeriodUnit, string]> = [+ ['day', t('days')],+ ['week', t('weeks')],+ ['month', t('months')],+ ['year', t('years')],+ ];+ const format = useFormat();++ const amount = amountToInteger(+ template.amount,+ format.currency.decimalPlaces,+ );+ const periodUnit = template.period?.period ?? 'month';+ const periodAmount = template.period?.amount ?? 1;+ const [rawPeriodAmount, setRawPeriodAmount] = useState(String(periodAmount));+ // Resync when a different automation row is selected (the component+ // instance is reused across rows).+ useEffect(() => {+ setRawPeriodAmount(String(periodAmount));+ }, [periodAmount]);+ const commitPeriodAmount = () => {+ const parsed = Math.max(1, Math.trunc(Number(rawPeriodAmount)) || 1);+ setRawPeriodAmount(String(parsed));+ if (parsed !== periodAmount) {+ dispatch(+ updateTemplate({+ type: 'periodic',+ period: { period: periodUnit, amount: parsed },+ }),+ );+ }+ };++ return (+ <SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Amount')} htmlFor="amount-field" />+ <AmountInput+ id="amount-field"+ value={amount}+ zeroSign="+"+ onUpdate={(value: number) =>+ dispatch(+ updateTemplate({+ type: 'periodic',+ amount: integerToAmount(value, format.currency.decimalPlaces),+ }),+ )+ }+ />+ </FormField>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Every')} htmlFor="period-amount-field" />+ <Input+ id="period-amount-field"+ type="number"+ min={1}+ step={1}+ value={rawPeriodAmount}+ onChangeValue={setRawPeriodAmount}+ onBlur={commitPeriodAmount}+ />+ </FormField>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Period')} htmlFor="period-unit-field" />+ <Select+ id="period-unit-field"+ value={periodUnit}+ onChange={value =>+ dispatch(+ updateTemplate({+ type: 'periodic',+ period: {+ period: value,+ amount: periodAmount,+ },+ }),+ )+ }+ options={periodUnitOptions}+ />+ </FormField>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Starting')} htmlFor="starting-field" />+ <GenericInput+ type="date"+ field="date"+ value={template.starting ?? ''}+ onChange={(value: string) =>+ dispatch(updateTemplate({ type: 'periodic', starting: value }))+ }+ />+ </FormField>+ </SpaceBetween>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/FixedAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomationReadOnly.tsxnew file mode 100644index 0000000000..770f34cf1b--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomationReadOnly.tsx@@ -0,0 +1,61 @@+import { Trans } from 'react-i18next';++import { amountToInteger } from '@actual-app/core/shared/util';+import type { PeriodicTemplate } from '@actual-app/core/types/models/templates';+import type { TransObjectLiteral } from '@actual-app/core/types/util';++import { FinancialText } from '#components/FinancialText';+import { useFormat } from '#hooks/useFormat';++type FixedAutomationReadOnlyProps = {+ template: PeriodicTemplate;+};++export function FixedAutomationReadOnly({+ template,+}: FixedAutomationReadOnlyProps) {+ const format = useFormat();+ const amount = format(+ amountToInteger(template.amount, format.currency.decimalPlaces),+ 'financial',+ );+ const periodAmount = template.period?.amount ?? 1;+ const periodUnit = template.period?.period ?? 'month';++ switch (periodUnit) {+ case 'day':+ return (+ <Trans count={periodAmount}>+ Budget{' '}+ <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}+ every {{ count: periodAmount }} days+ </Trans>+ );+ case 'week':+ return (+ <Trans count={periodAmount}>+ Budget{' '}+ <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}+ every {{ count: periodAmount }} weeks+ </Trans>+ );+ case 'month':+ return (+ <Trans count={periodAmount}>+ Budget{' '}+ <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}+ every {{ count: periodAmount }} months+ </Trans>+ );+ case 'year':+ return (+ <Trans count={periodAmount}>+ Budget{' '}+ <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}+ every {{ count: periodAmount }} years+ </Trans>+ );+ default:+ return null;+ }+}diff --git a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsxindex 39c6a10157..c330fcf854 100644--- a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx@@ -13,12 +13,12 @@ export const HistoricalAutomationReadOnly = ({template,}: HistoricalAutomationReadOnlyProps) => {return template.type === 'copy' ? (- <Trans>- Budget the same amount as {{ amount: template.lookBack }} months ago+ <Trans count={template.lookBack}>+ Budget the same amount as {{ count: template.lookBack }} months ago</Trans>) : (- <Trans>- Budget the average of the last {{ amount: template.numMonths }} months+ <Trans count={template.numMonths}>+ Budget the average of the last {{ count: template.numMonths }} months</Trans>);};diff --git a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsxindex cf7ea24d5d..e23c5663ea 100644--- a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx@@ -1,9 +1,8 @@-import { useTranslation } from 'react-i18next';+import { Trans, useTranslation } from 'react-i18next';import { Select } from '@actual-app/components/select';import { SpaceBetween } from '@actual-app/components/space-between';import { theme } from '@actual-app/components/theme';-import { View } from '@actual-app/components/view';import {currentDate,dayFromDate,@@ -18,6 +17,7 @@ import { setDay } from 'date-fns/setDay';import { updateTemplate } from '#components/budget/goals/actions';import type { Action } from '#components/budget/goals/actions';import { FormField, FormLabel } from '#components/forms';+import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';import { AmountInput } from '#components/util/AmountInput';import { useDaysOfWeek } from '#hooks/useDaysOfWeek';import { useFormat } from '#hooks/useFormat';@@ -115,26 +115,21 @@ export const LimitAutomation = ({<SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>{period === 'weekly' && amountField}- <FormField key="excess-funds-field" style={{ flex: 1 }}>- <FormLabel- title={t('Excess funds mode')}- htmlFor="excess-funds-field"- />-- <Select- id="excess-funds-field"- value={hold}- onChange={value =>- dispatch(updateTemplate({ type: 'limit', hold: value }))+ <FormField key="hold-overflow-field" style={{ flex: 1 }}>+ <LabeledCheckbox+ id="hold-overflow-field"+ checked={!!hold}+ onChange={e =>+ dispatch(+ updateTemplate({ type: 'limit', hold: e.target.checked }),+ )}- options={[- [false, t('Remove all funds over the limit')],- [true, t('Retain any funds over the limit')],- ]}- className={selectButtonClassName}- />+ >+ <span style={{ marginLeft: 6, fontSize: 12, whiteSpace: 'nowrap' }}>+ <Trans>Retain existing funds over the cap</Trans>+ </span>+ </LabeledCheckbox></FormField>- {period !== 'weekly' && <View style={{ flex: 1 }} />}</SpaceBetween></>);diff --git a/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsxindex bafc9c33df..51efda0db2 100644--- a/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsx@@ -44,7 +44,7 @@ export const PercentageAutomation = ({? categories.map(group => ({...group,categories: group.categories?.filter(- category => category.id !== 'to-budget',+ category => category.id !== 'available funds',),})): categories@@ -87,7 +87,7 @@ export const PercentageAutomation = ({updateTemplate({type: 'percentage',previous,- ...(previous && template.category === 'to-budget'+ ...(previous && template.category === 'available funds'? { category: '' }: {}),}),diff --git a/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomationReadOnly.tsxindex 2cb3f2c9b6..236f8d6dfe 100644--- a/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomationReadOnly.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomationReadOnly.tsx@@ -13,7 +13,7 @@ export const PercentageAutomationReadOnly = ({}: PercentageAutomationReadOnlyProps) => {const { t } = useTranslation();- if (template.category === 'total') {+ if (template.category === 'all income') {return template.previous ? (<Trans>Budget {{ percent: template.percent }}% of total income last month@@ -25,7 +25,7 @@ export const PercentageAutomationReadOnly = ({);}- if (template.category === 'to-budget') {+ if (template.category === 'available funds') {return template.previous ? (<Trans>Budget {{ percent: template.percent }}% of available funds to budgetdiff --git a/packages/desktop-client/src/components/budget/goals/editor/RemainderAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/RemainderAutomation.tsxnew file mode 100644index 0000000000..5aaf666502--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/RemainderAutomation.tsx@@ -0,0 +1,62 @@+import { useEffect, useState } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { Input } from '@actual-app/components/input';+import { SpaceBetween } from '@actual-app/components/space-between';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import type { RemainderTemplate } from '@actual-app/core/types/models/templates';++import { updateTemplate } from '#components/budget/goals/actions';+import type { Action } from '#components/budget/goals/actions';+import { FormField, FormLabel } from '#components/forms';++type RemainderAutomationProps = {+ template: RemainderTemplate;+ dispatch: (action: Action) => void;+};++export const RemainderAutomation = ({+ template,+ dispatch,+}: RemainderAutomationProps) => {+ const { t } = useTranslation();+ const committedWeight = template.weight ?? 1;+ // Track the raw input so the user can clear and retype without the field+ // snapping back. Commit (and clamp) on blur.+ const [rawWeight, setRawWeight] = useState(String(committedWeight));+ useEffect(() => {+ setRawWeight(String(committedWeight));+ }, [committedWeight]);++ const commitWeight = () => {+ const parsed = Math.max(1, Math.trunc(Number(rawWeight)) || 1);+ setRawWeight(String(parsed));+ if (parsed !== committedWeight) {+ dispatch(updateTemplate({ type: 'remainder', weight: parsed }));+ }+ };++ return (+ <SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Weight')} htmlFor="remainder-weight-field" />+ <Input+ id="remainder-weight-field"+ type="number"+ min={1}+ step={1}+ value={rawWeight}+ onChangeValue={setRawWeight}+ onBlur={commitWeight}+ />+ </FormField>+ <Text style={{ flex: 2, color: theme.pageTextSubdued, fontSize: 12 }}>+ <Trans>+ Categories with higher weights get a bigger share of the leftover To+ Budget.+ </Trans>+ </Text>+ </SpaceBetween>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/RemainderAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/RemainderAutomationReadOnly.tsxnew file mode 100644index 0000000000..7b36a78085--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/RemainderAutomationReadOnly.tsx@@ -0,0 +1,18 @@+import { Trans } from 'react-i18next';++import type { RemainderTemplate } from '@actual-app/core/types/models/templates';++type RemainderAutomationReadOnlyProps = {+ template: RemainderTemplate;+};++export const RemainderAutomationReadOnly = ({+ template,+}: RemainderAutomationReadOnlyProps) => {+ return (+ <Trans>+ Share remaining funds to budget (weight {{ weight: template.weight ?? 1 }}+ )+ </Trans>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsxindex 5c5ffde86e..ea78a3df9a 100644--- a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx@@ -23,8 +23,16 @@ export const ScheduleAutomation = ({dispatch,}: ScheduleAutomationProps) => {const { t } = useTranslation();+ // Match the filter applied to the Select options below — completed and+ // tombstoned schedules aren't selectable, so a category whose only+ // schedules are completed should fall through to the "no schedules" state+ // instead of showing an empty picker.+ const selectableSchedules = schedules.filter(+ (s): s is typeof s & { name: string } =>+ !!s.name && !s.completed && !s.tombstone,+ );- return schedules.length ? (+ return selectableSchedules.length ? (<SpaceBetween gap={50} style={{ marginTop: 10 }}><FormField style={{ flex: 1 }}><FormLabel title={t('Schedule')} htmlFor="schedule-field" />@@ -41,9 +49,7 @@ export const ScheduleAutomation = ({}),)}- options={schedules.flatMap(schedule =>- schedule.name ? [[schedule.name, schedule.name]] : [],- )}+ options={selectableSchedules.map(s => [s.name, s.name] as const)}/></FormField><FormField style={{ flex: 1 }}>diff --git a/packages/desktop-client/src/components/budget/goals/editor/WeekAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/WeekAutomation.tsxdeleted file mode 100644index 5951ef55bc..0000000000--- a/packages/desktop-client/src/components/budget/goals/editor/WeekAutomation.tsx+++ /dev/null@@ -1,37 +0,0 @@-import { useTranslation } from 'react-i18next';--import type { PeriodicTemplate } from '@actual-app/core/types/models/templates';--import { updateTemplate } from '#components/budget/goals/actions';-import type { Action } from '#components/budget/goals/actions';-import { FormField, FormLabel } from '#components/forms';-import { AmountInput } from '#components/util/AmountInput';--type WeekAutomationProps = {- template: PeriodicTemplate;- dispatch: (action: Action) => void;-};--export const WeekAutomation = ({ template, dispatch }: WeekAutomationProps) => {- const { t } = useTranslation();-- return (- <FormField style={{ flex: 1 }}>- <FormLabel title={t('Amount')} htmlFor="amount-field" />- <AmountInput- id="amount-field"- key="amount-input"- value={template.amount ?? 0}- zeroSign="+"- onUpdate={(value: number) =>- dispatch(- updateTemplate({- type: 'periodic',- amount: value,- }),- )- }- />- </FormField>- );-};diff --git a/packages/desktop-client/src/components/budget/goals/editor/WeekAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/WeekAutomationReadOnly.tsxdeleted file mode 100644index c7646b7fc5..0000000000--- a/packages/desktop-client/src/components/budget/goals/editor/WeekAutomationReadOnly.tsx+++ /dev/null@@ -1,31 +0,0 @@-import { Trans } from 'react-i18next';--import type { PeriodicTemplate } from '@actual-app/core/types/models/templates';-import type { TransObjectLiteral } from '@actual-app/core/types/util';--import { FinancialText } from '#components/FinancialText';-import { useFormat } from '#hooks/useFormat';--type WeekAutomationReadOnlyProps = {- template: PeriodicTemplate;-};--export const WeekAutomationReadOnly = ({- template,-}: WeekAutomationReadOnlyProps) => {- const format = useFormat();-- return (- <Trans>- Budget{' '}- <FinancialText>- {- {- amount: format(template.amount, 'financial'),- } as TransObjectLiteral- }- </FinancialText>{' '}- each week- </Trans>- );-};diff --git a/packages/desktop-client/src/components/budget/goals/formatMonthLabel.ts b/packages/desktop-client/src/components/budget/goals/formatMonthLabel.tsnew file mode 100644index 0000000000..204247d105--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/formatMonthLabel.ts@@ -0,0 +1,14 @@+import * as monthUtils from '@actual-app/core/shared/months';++// Format a YYYY-MM string as "MMM yyyy" using the active locale (matching+// the convention used elsewhere in the codebase via monthUtils.format).+// Falls back to the raw input if it doesn't look like YYYY-MM, and to "—"+// for empty/missing values so callers don't need their own guards.+export function formatMonthLabel(+ month: string | undefined | null,+ locale?: Parameters<typeof monthUtils.format>[2],+): string {+ if (!month) return '—';+ if (!monthUtils.isValidYearMonth(month)) return month;+ return monthUtils.format(`${month}-01`, 'MMM yyyy', locale);+}diff --git a/packages/desktop-client/src/components/budget/goals/reducer.ts b/packages/desktop-client/src/components/budget/goals/reducer.tsindex 986ceba6af..c6c161b50a 100644--- a/packages/desktop-client/src/components/budget/goals/reducer.ts+++ b/packages/desktop-client/src/components/budget/goals/reducer.ts@@ -1,4 +1,9 @@-import { firstDayOfMonth } from '@actual-app/core/shared/months';+import {+ addMonths,+ dayFromDate,+ firstDayOfMonth,+ monthFromDate,+} from '@actual-app/core/shared/months';import type { Template } from '@actual-app/core/types/models/templates';import type { Action } from './actions';@@ -25,7 +30,7 @@ export const getInitialState = (template: Template | null): ReducerState => {priority: template.priority,directive: template.directive,},- displayType: 'week',+ displayType: 'fixed',};case 'percentage':return {@@ -40,13 +45,20 @@ export const getInitialState = (template: Template | null): ReducerState => {case 'periodic':return {template,- displayType: 'week',+ displayType: 'fixed',};case 'spend':- case 'by':throw new Error('Goal is not yet supported');+ case 'by':+ return {+ template,+ displayType: 'by',+ };case 'remainder':- throw new Error('Remainder is not yet supported');+ return {+ template,+ displayType: 'remainder',+ };case 'limit':return {template,@@ -117,7 +129,7 @@ const changeType = (type: 'percentage',percent: 15,previous: false,- category: 'total',+ category: 'all income',priority: DEFAULT_PRIORITY,},};@@ -134,7 +146,7 @@ const changeType = (priority: DEFAULT_PRIORITY,},};- case 'week':+ case 'fixed':if (prevState.template.type === 'periodic') {return prevState;}@@ -143,12 +155,12 @@ const changeType = (template: {directive: 'template',type: 'periodic',- amount: 5,+ amount: 100,period: {- period: 'week',+ period: 'month',amount: 1,},- starting: '',+ starting: dayFromDate(firstDayOfMonth(new Date())),priority: DEFAULT_PRIORITY,},};@@ -168,6 +180,35 @@ const changeType = (priority: DEFAULT_PRIORITY,},};+ case 'by':+ if (prevState.template.type === 'by') {+ return prevState;+ }+ return {+ displayType: visualType,+ template: {+ directive: 'template',+ type: 'by',+ amount: 1200,+ month: addMonths(monthFromDate(new Date()), 12),+ annual: true,+ repeat: 1,+ priority: DEFAULT_PRIORITY,+ },+ };+ case 'remainder':+ if (prevState.template.type === 'remainder') {+ return prevState;+ }+ return {+ displayType: visualType,+ template: {+ directive: 'template',+ type: 'remainder',+ weight: 1,+ priority: null,+ },+ };default:// Make sure we're not missing any casesthrow new Error(diff --git a/packages/desktop-client/src/components/budget/goals/useBudgetAutomationCategories.ts b/packages/desktop-client/src/components/budget/goals/useBudgetAutomationCategories.tsindex f72e6cde26..3fb6074420 100644--- a/packages/desktop-client/src/components/budget/goals/useBudgetAutomationCategories.ts+++ b/packages/desktop-client/src/components/budget/goals/useBudgetAutomationCategories.ts@@ -13,9 +13,9 @@ export function useBudgetAutomationCategories() {id: '',name: t('Special categories'),categories: [- { id: 'total', group: '', name: t('Total of all income') },+ { id: 'all income', group: '', name: t('Total of all income') },{- id: 'to-budget',+ id: 'available funds',group: '',name: t('Available funds to budget'),},diff --git a/packages/desktop-client/src/components/budget/goals/validateAutomation.ts b/packages/desktop-client/src/components/budget/goals/validateAutomation.tsnew file mode 100644index 0000000000..781d46bf69--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/validateAutomation.ts@@ -0,0 +1,95 @@+import * as monthUtils from '@actual-app/core/shared/months';+import type { ScheduleEntity } from '@actual-app/core/types/models';+import type { Template } from '@actual-app/core/types/models/templates';++import type { DisplayTemplateType } from './constants';++export type AutomationErrorKind =+ | { kind: 'schedule-not-found'; name: string }+ | { kind: 'refill-no-cap' }+ | { kind: 'percentage-out-of-range'; percent: number }+ | { kind: 'percentage-no-source' }+ | { kind: 'percentage-source-not-found'; source: string }+ | { kind: 'by-no-month' }+ | { kind: 'by-target-past'; month: string };++export type GlobalConflictKind =+ | { kind: 'over-income'; total: number; income: number }+ | { kind: 'percent-over-100'; total: number };++export function validateAutomation(+ template: Template,+ displayType: DisplayTemplateType,+ allTemplates: readonly Template[],+ schedules: readonly ScheduleEntity[],+ today: Date,+ // Set of recognised percentage sources (income category ids, lower-cased+ // category names, and special source aliases like 'all income'). When+ // omitted the source-not-found check is skipped (the engine still validates+ // server-side at apply time).+ validPercentageSources?: ReadonlySet<string>,+): AutomationErrorKind | null {+ switch (displayType) {+ case 'schedule':+ if (template.type !== 'schedule') return null;+ if (!template.name) return { kind: 'schedule-not-found', name: '' };+ if (+ !schedules.some(+ s => s.name === template.name && !s.completed && !s.tombstone,+ )+ ) {+ return { kind: 'schedule-not-found', name: template.name };+ }+ return null;+ case 'refill':+ if (!allTemplates.some(t => t.type === 'limit')) {+ return { kind: 'refill-no-cap' };+ }+ return null;+ case 'percentage':+ if (template.type !== 'percentage') return null;+ if (!template.category) return { kind: 'percentage-no-source' };+ if (template.percent <= 0 || template.percent > 100) {+ return {+ kind: 'percentage-out-of-range',+ percent: template.percent,+ };+ }+ if (+ validPercentageSources &&+ !validPercentageSources.has(template.category) &&+ !validPercentageSources.has(template.category.toLowerCase())+ ) {+ return {+ kind: 'percentage-source-not-found',+ source: template.category,+ };+ }+ return null;+ case 'by': {+ if (template.type !== 'by') return null;+ if (!template.month || !monthUtils.isValidYearMonth(template.month)) {+ return { kind: 'by-no-month' };+ }+ const targetMonth = template.month;+ const startOfTodayMonth = monthUtils.monthFromDate(today);+ // Pass bare YYYY-MM strings, matching the server-side check in+ // CategoryTemplateContext.checkByAndScheduleAndSpend and avoiding the+ // local-vs-UTC parsing footgun called out in shared/months.ts:_parse.+ const monthsRemaining = monthUtils.differenceInCalendarMonths(+ targetMonth,+ startOfTodayMonth,+ );+ // Recurring goals (annual/repeat) anchored on a past month are+ // legitimate — the engine rolls them forward by the period. Only flag+ // the past-target case for one-shot goals. Mirrors the server check in+ // CategoryTemplateContext.checkByAndScheduleAndSpend.+ if (monthsRemaining < 0 && !template.annual && !template.repeat) {+ return { kind: 'by-target-past', month: targetMonth };+ }+ return null;+ }+ default:+ return null;+ }+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal.tsxdeleted file mode 100644index 3b5dac2ed3..0000000000--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal.tsx+++ /dev/null@@ -1,465 +0,0 @@-import { useCallback, useMemo, useState } from 'react';-import type { CSSProperties } from 'react';-import { Trans, useTranslation } from 'react-i18next';--import { Button } from '@actual-app/components/button';-import { AnimatedLoading } from '@actual-app/components/icons/AnimatedLoading';-import { SpaceBetween } from '@actual-app/components/space-between';-import { theme } from '@actual-app/components/theme';-import { View } from '@actual-app/components/view';-import { send } from '@actual-app/core/platform/client/connection';-import { dayFromDate, firstDayOfMonth } from '@actual-app/core/shared/months';-import { q } from '@actual-app/core/shared/query';-import type {- CategoryGroupEntity,- ScheduleEntity,-} from '@actual-app/core/types/models';-import type { Template } from '@actual-app/core/types/models/templates';-import uniqueId from 'lodash/uniqueId';--import { Warning } from '#components/alerts';-import { BudgetAutomation } from '#components/budget/goals/BudgetAutomation';-import type { DisplayTemplateType } from '#components/budget/goals/constants';-import { DEFAULT_PRIORITY } from '#components/budget/goals/reducer';-import { useBudgetAutomationCategories } from '#components/budget/goals/useBudgetAutomationCategories';-import { Link } from '#components/common/Link';-import { Modal, ModalCloseButton, ModalHeader } from '#components/common/Modal';-import { useBudgetAutomations } from '#hooks/useBudgetAutomations';-import { useCategory } from '#hooks/useCategory';-import { useNotes } from '#hooks/useNotes';-import { useSchedules } from '#hooks/useSchedules';-import { pushModal } from '#modals/modalsSlice';-import { useDispatch } from '#redux';--type AutomationEntry = {- id: string;- template: Template;- displayType: DisplayTemplateType;-};--function getDisplayTypeFromTemplate(template: Template): DisplayTemplateType {- switch (template.type) {- case 'percentage':- return 'percentage';- case 'schedule':- return 'schedule';- case 'periodic':- case 'simple':- return 'week';- case 'limit':- return 'limit';- case 'refill':- return 'refill';- case 'average':- case 'copy':- return 'historical';- default:- return 'week';- }-}--function createAutomationEntry(- template: Template,- displayType: DisplayTemplateType,-): AutomationEntry {- return {- id: uniqueId('automation-'),- template,- displayType,- };-}--export function migrateTemplatesToAutomations(- templates: Template[],-): AutomationEntry[] {- const entries: AutomationEntry[] = [];-- templates.forEach(template => {- // Expand simple templates into limit, refill, and/or periodic templates- if (template.type === 'simple') {- let hasExpandedTemplate = false;-- if (template.limit) {- hasExpandedTemplate = true;- entries.push(- createAutomationEntry(- {- type: 'limit',- amount: template.limit.amount,- hold: template.limit.hold,- period: template.limit.period,- start: template.limit.start,- directive: 'template',- priority: null,- },- 'limit',- ),- );- entries.push(- createAutomationEntry(- {- type: 'refill',- directive: 'template',- priority: template.priority,- },- 'refill',- ),- );- }- // If it has a monthly amount, create a periodic template- if (template.monthly != null && template.monthly !== 0) {- hasExpandedTemplate = true;- entries.push(- createAutomationEntry(- {- type: 'periodic',- amount: template.monthly,- period: {- period: 'month',- amount: 1,- },- starting: dayFromDate(firstDayOfMonth(new Date())),- directive: 'template',- priority: template.priority,- },- 'week',- ),- );- }-- if (!hasExpandedTemplate) {- entries.push(- createAutomationEntry(template, getDisplayTypeFromTemplate(template)),- );- }-- return;- }-- // For all other template types, create a single entry- entries.push(- createAutomationEntry(template, getDisplayTypeFromTemplate(template)),- );- });-- return entries;-}--function BudgetAutomationList({- automations,- setAutomations,- schedules,- categories,- style,-}: {- automations: AutomationEntry[];- setAutomations: (fn: (prev: AutomationEntry[]) => AutomationEntry[]) => void;- schedules: readonly ScheduleEntity[];- categories: CategoryGroupEntity[];- style?: CSSProperties;-}) {- const onAdd = () => {- setAutomations(prev => [- ...prev,- createAutomationEntry(- {- type: 'periodic',- amount: 500,- period: {- period: 'month',- amount: 1,- },- starting: dayFromDate(firstDayOfMonth(new Date())),- directive: 'template',- priority: DEFAULT_PRIORITY,- },- 'week',- ),- ]);- };- const onAddLimit = () => {- setAutomations(prev => [- ...prev,- createAutomationEntry(- {- directive: 'template',- type: 'limit',- amount: 500,- period: 'monthly',- hold: false,- priority: null,- },- 'limit',- ),- ]);- };- const onDelete = (index: number) => () => {- setAutomations(prev => [...prev.slice(0, index), ...prev.slice(index + 1)]);- };-- const onSave = useCallback(- (index: number) =>- (template: Template, displayType: DisplayTemplateType) => {- setAutomations(prev =>- prev.map((oldAutomation, mapIndex) =>- mapIndex === index- ? { ...oldAutomation, template, displayType }- : oldAutomation,- ),- );- },- [setAutomations],- );-- const hasLimitAutomation = automations.some(- automation => automation.displayType === 'limit',- );-- return (- <SpaceBetween- direction="vertical"- gap={20}- align="stretch"- wrap={false}- style={{- overflowY: 'scroll',- ...style,- }}- >- {automations.map((automation, index) => (- <BudgetAutomation- key={automation.id}- onSave={onSave(index)}- onDelete={onDelete(index)}- template={automation.template}- categories={categories}- schedules={schedules}- hasLimitAutomation={hasLimitAutomation}- onAddLimitAutomation={- automation.displayType === 'refill' ? onAddLimit : undefined- }- readOnlyStyle={{- color: theme.pillText,- backgroundColor: theme.pillBackground,- borderRadius: 4,- padding: 16,- paddingLeft: 30,- paddingRight: 16,- }}- />- ))}- <Button onPress={onAdd}>- <Trans>Add new automation</Trans>- </Button>- </SpaceBetween>- );-}--function BudgetAutomationMigrationWarning({- categoryId,- style,-}: {- categoryId: string;- style?: CSSProperties;-}) {- const notes = useNotes(categoryId);-- const templates = useMemo(() => {- if (!notes) return null;- const lines = notes.split('\n');- return lines- .flatMap(line => {- if (line.trim().startsWith('#template')) return line;- if (line.trim().startsWith('#goal')) return line;- if (line.trim().startsWith('#cleanup')) return line;- return [];- })- .join('\n');- }, [notes]);-- if (!templates) return null;-- return (- <Warning style={style}>- <SpaceBetween direction="vertical" style={{ minHeight: 'unset' }}>- <View>- <Trans>- This category uses notes-based automations (formerly "budget- templates"). We have automatically imported your existing- automations below. Please review them for accuracy and hit save to- complete the migration.- </Trans>- </View>- <View>- <Trans>- Original templates:- <View- style={{- whiteSpace: 'pre-wrap',- fontFamily: 'monospace',- marginTop: 4,- padding: 12,- borderRadius: 4,- backgroundColor: 'rgba(255, 255, 255, 0.1)',- }}- >- {templates}- </View>- </Trans>- </View>- </SpaceBetween>- </Warning>- );-}--export function BudgetAutomationsModal({ categoryId }: { categoryId: string }) {- const { t } = useTranslation();- const dispatch = useDispatch();-- const [automations, setAutomations] = useState<- Record<string, AutomationEntry[]>- >({});- const onLoaded = useCallback((result: Record<string, Template[]>) => {- const next: Record<string, AutomationEntry[]> = {};- for (const [id, templates] of Object.entries(result)) {- next[id] = migrateTemplatesToAutomations(templates);- }- setAutomations(next);- }, []);-- const { loading } = useBudgetAutomations({- categoryId,- onLoaded,- });-- const schedulesQuery = useMemo(() => q('schedules').select('*'), []);- const { schedules } = useSchedules({- query: schedulesQuery,- });-- const categories = useBudgetAutomationCategories();- const { data: currentCategory } = useCategory(categoryId);-- const needsMigration = currentCategory?.template_settings?.source !== 'ui';-- const onSave = async (close: () => void) => {- if (!automations[categoryId]) {- close();- return;- }-- const templates = automations[categoryId].map(({ template }) => template);- await send('budget/set-category-automations', {- categoriesWithTemplates: [- {- id: categoryId,- templates,- },- ],- source: 'ui',- });- close();- };-- return (- <Modal- name="category-automations-edit"- containerProps={{- style: { width: 850, height: 650, paddingBottom: 20 },- }}- >- {({ state }) => (- <SpaceBetween- direction="vertical"- wrap={false}- align="stretch"- style={{ height: '100%' }}- >- <ModalHeader- title={t('Budget automations: {{category}}', {- category: currentCategory?.name,- })}- rightContent={<ModalCloseButton onPress={() => state.close()} />}- />- {loading ? (- <View- style={{- position: 'absolute',- top: 0,- left: 0,- right: 0,- bottom: 0,- alignItems: 'center',- justifyContent: 'center',- }}- >- <AnimatedLoading style={{ width: 20, height: 20 }} />- </View>- ) : (- <SpaceBetween align="stretch" direction="vertical" wrap={false}>- {needsMigration && (- <BudgetAutomationMigrationWarning- categoryId={categoryId}- style={{ flexShrink: 0 }}- />- )}- <BudgetAutomationList- automations={automations[categoryId] || []}- setAutomations={(- cb: (prev: AutomationEntry[]) => AutomationEntry[],- ) => {- setAutomations(prev => ({- ...prev,- [categoryId]: cb(prev[categoryId] || []),- }));- }}- schedules={schedules}- categories={categories}- />- </SpaceBetween>- )}- <View style={{ flexGrow: 1 }} />- <SpaceBetween- style={{- marginTop: 20,- justifyContent: 'flex-end',- flexShrink: 0,- }}- >- {!needsMigration && (- <Link- variant="text"- onClick={() => {- const templates = automations[categoryId] || [];- dispatch(- pushModal({- modal: {- name: 'category-automations-unmigrate',- options: {- categoryId,- templates: templates.map(({ template }) => template),- },- },- }),- );- }}- >- <Trans>Un-migrate</Trans>- </Link>- )}- {/* <View style={{ flex: 1 }} /> */}- <Button onPress={() => state.close()}>- <Trans>Cancel</Trans>- </Button>- <Button- variant="primary"- onPress={() => onSave(() => state.close())}- >- <Trans>Save</Trans>- </Button>- </SpaceBetween>- </SpaceBetween>- )}- </Modal>- );-}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsxnew file mode 100644index 0000000000..9bf2e43d00--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsx@@ -0,0 +1,294 @@+import { Trans } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgDelete } from '@actual-app/components/icons/v0';+import { SvgAlertTriangle } from '@actual-app/components/icons/v2';+import { Input } from '@actual-app/components/input';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import type {+ CategoryGroupEntity,+ ScheduleEntity,+} from '@actual-app/core/types/models';+import { css } from '@emotion/css';++import { ActiveEditor } from '#components/budget/goals/ActiveEditor';+import type { AutomationEntry } from '#components/budget/goals/automationExamples';+import {+ AutomationErrorDetail,+ AutomationErrorTitle,+} from '#components/budget/goals/automationMessages';+import type { DisplayTemplateType } from '#components/budget/goals/constants';+import {+ getInitialState,+ templateReducer,+} from '#components/budget/goals/reducer';+import type { AutomationErrorKind } from '#components/budget/goals/validateAutomation';++import { TypePicker } from './TypePicker';++const CONFIG_PANEL_CLASS = css({+ '& > *:first-child': {+ marginTop: 0,+ },+ '& span > label': {+ fontSize: 11,+ fontWeight: 600,+ color: theme.pageTextSubdued,+ letterSpacing: '0.04em',+ textTransform: 'uppercase',+ },+ // Match Select borders to text inputs (Button uses buttonNormalBorder which+ // is brighter than formInputBorder in dark/midnight themes).+ '& button[type="button"]:not([aria-pressed])': {+ borderColor: theme.formInputBorder,+ },+});++const SINGLETON_TYPES: ReadonlySet<DisplayTemplateType> = new Set([+ 'limit',+ 'refill',+ 'remainder',+]);++type AutomationEditorPaneProps = {+ entries: AutomationEntry[];+ activeIdx: number;+ automationErrors: (AutomationErrorKind | null)[];+ schedules: readonly ScheduleEntity[];+ categories: CategoryGroupEntity[];+ hasLimitAutomation: boolean;+ onAddLimitAutomation: () => void;+ setEntries: (fn: (prev: AutomationEntry[]) => AutomationEntry[]) => void;+ onDelete: (index: number) => void;+};++export function AutomationEditorPane({+ entries,+ activeIdx,+ automationErrors,+ schedules,+ categories,+ hasLimitAutomation,+ onAddLimitAutomation,+ setEntries,+ onDelete,+}: AutomationEditorPaneProps) {+ const active = entries[activeIdx];+ const activeError = automationErrors[activeIdx];++ const state = active ? getInitialState(active.template) : null;++ const dispatch = (action: Parameters<typeof templateReducer>[1]) => {+ setEntries(prev =>+ prev.map((entry, i) => {+ if (i !== activeIdx) return entry;+ const current = getInitialState(entry.template);+ const next = templateReducer(current, action);+ return {+ id: entry.id,+ template: next.template,+ displayType: next.displayType,+ };+ }),+ );+ };++ const setPriority = (priority: number) => {+ setEntries(prev =>+ prev.map((entry, i) => {+ if (i !== activeIdx) return entry;+ const t = entry.template;+ switch (t.type) {+ case 'percentage':+ case 'periodic':+ case 'by':+ case 'spend':+ case 'simple':+ case 'schedule':+ case 'average':+ case 'copy':+ case 'refill':+ return { ...entry, template: { ...t, priority } };+ default:+ return entry;+ }+ }),+ );+ };++ const disabledTypes = new Set<DisplayTemplateType>();+ entries.forEach((entry, i) => {+ if (i !== activeIdx && SINGLETON_TYPES.has(entry.displayType)) {+ disabledTypes.add(entry.displayType);+ }+ });++ if (!active || !state) {+ return (+ <View style={{ padding: 20, color: theme.pageTextSubdued }}>+ <Trans>Select an automation on the left.</Trans>+ </View>+ );+ }++ return (+ <View+ style={{+ flex: 1,+ padding: 20,+ overflowY: 'auto',+ gap: 14,+ }}+ >+ {activeError && (+ <View+ style={{+ padding: '10px 12px',+ borderRadius: 6,+ backgroundColor: theme.errorBackground,+ border: `1px solid ${theme.errorBorder}`,+ color: theme.errorText,+ fontSize: 13,+ flexDirection: 'row',+ gap: 10,+ alignItems: 'flex-start',+ }}+ >+ <SvgAlertTriangle+ width={14}+ height={14}+ style={{ marginTop: 2, color: 'inherit', flexShrink: 0 }}+ />+ <View style={{ minWidth: 0 }}>+ <Text style={{ fontWeight: 600, color: 'inherit' }}>+ <AutomationErrorTitle error={activeError} />+ </Text>+ <Text+ style={{+ fontSize: 12,+ marginTop: 2,+ color: 'inherit',+ display: 'block',+ }}+ >+ <AutomationErrorDetail error={activeError} />+ </Text>+ </View>+ </View>+ )}++ <Text+ style={{+ fontSize: 11,+ textTransform: 'uppercase',+ color: theme.pageTextSubdued,+ fontWeight: 600,+ letterSpacing: '0.05em',+ }}+ >+ <Trans>Automation type</Trans>+ </Text>+ <TypePicker+ active={state.displayType}+ disabledTypes={disabledTypes}+ onPick={type => dispatch({ type: 'set-type', payload: type })}+ />++ {state.displayType !== 'refill' && (+ <>+ <Text+ style={{+ fontSize: 11,+ textTransform: 'uppercase',+ color: theme.pageTextSubdued,+ fontWeight: 600,+ letterSpacing: '0.05em',+ }}+ >+ <Trans>Configuration</Trans>+ </Text>+ <View+ className={CONFIG_PANEL_CLASS}+ style={{+ padding: 16,+ backgroundColor: theme.tableBackground,+ borderRadius: 6,+ border: `1px solid ${theme.tableBorder}`,+ }}+ >+ <ActiveEditor+ state={state}+ dispatch={dispatch}+ schedules={schedules}+ categories={categories}+ hasLimitAutomation={hasLimitAutomation}+ onAddLimitAutomation={onAddLimitAutomation}+ />+ </View>+ </>+ )}++ {state.displayType === 'refill' && (+ <ActiveEditor+ state={state}+ dispatch={dispatch}+ schedules={schedules}+ categories={categories}+ hasLimitAutomation={hasLimitAutomation}+ onAddLimitAutomation={onAddLimitAutomation}+ />+ )}++ <View style={{ flexDirection: 'row', gap: 12, alignItems: 'center' }}>+ {'priority' in state.template &&+ typeof state.template.priority === 'number' && (+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ gap: 8,+ }}+ >+ <Text+ style={{+ fontSize: 11,+ fontWeight: 600,+ color: theme.pageTextSubdued,+ letterSpacing: '0.04em',+ textTransform: 'uppercase',+ }}+ >+ <Trans>Priority</Trans>+ </Text>+ <Input+ type="number"+ style={{ width: 64 }}+ value={String(state.template.priority)}+ onChangeValue={value => {+ if (value === '') return;+ const parsed = Math.round(Number(value));+ if (Number.isNaN(parsed)) return;+ setPriority(Math.max(0, parsed));+ }}+ />+ </View>+ )}+ <View style={{ flex: 1 }} />+ <Button+ variant="bare"+ onPress={() => onDelete(activeIdx)}+ style={{ color: theme.errorText }}+ >+ <span+ style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}+ >+ <SvgDelete width={10} height={10} style={{ color: 'inherit' }} />+ <Trans>Delete automation</Trans>+ </span>+ </Button>+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationListRow.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationListRow.tsxnew file mode 100644index 0000000000..5a7732dddf--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationListRow.tsx@@ -0,0 +1,179 @@+import { useTranslation } from 'react-i18next';++import { SvgAlertTriangle } from '@actual-app/components/icons/v2';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import type { AutomationEntry } from '#components/budget/goals/automationExamples';+import { AutomationErrorShort } from '#components/budget/goals/automationMessages';+import { getDisplayTemplateMeta } from '#components/budget/goals/displayTemplateMeta';+import { TemplateSentence } from '#components/budget/goals/TemplateSentence';+import type { AutomationErrorKind } from '#components/budget/goals/validateAutomation';+import { useFormat } from '#hooks/useFormat';++type AutomationListRowProps = {+ index: number;+ entry: AutomationEntry;+ isActive: boolean;+ error: AutomationErrorKind | null;+ contribution: number | null;+ categoryNameMap: Record<string, string>;+ onSelect: (index: number) => void;+};++export function AutomationListRow({+ index,+ entry,+ isActive,+ error,+ contribution,+ categoryNameMap,+ onSelect,+}: AutomationListRowProps) {+ const { t } = useTranslation();+ const format = useFormat();+ const meta = getDisplayTemplateMeta(entry.displayType);+ const Icon = meta.icon;++ const subtitle = error ? (+ <AutomationErrorShort error={error} />+ ) : (+ <TemplateSentence+ template={entry.template}+ categoryNameMap={categoryNameMap}+ />+ );++ const borderColor = isActive+ ? theme.tableBorderSelected+ : error+ ? theme.errorBorder+ : 'transparent';+ const backgroundColor = isActive+ ? theme.upcomingBackground+ : error+ ? theme.errorBackground+ : 'transparent';+ const titleColor = error ? theme.errorText : theme.pageText;+ const subtitleColor = error ? theme.errorText : theme.pageTextSubdued;+ const priority =+ 'priority' in entry.template && typeof entry.template.priority === 'number'+ ? entry.template.priority+ : null;++ return (+ <View+ onClick={() => onSelect(index)}+ aria-label={t('Select automation')}+ style={{+ flexShrink: 0,+ flexDirection: 'row',+ alignItems: 'center',+ gap: 10,+ padding: 10,+ marginBottom: 4,+ borderRadius: 6,+ border: `1px solid ${borderColor}`,+ backgroundColor,+ cursor: 'pointer',+ position: 'relative',+ }}+ >+ <View+ style={{+ width: 28,+ height: 28,+ borderRadius: 6,+ backgroundColor: error+ ? theme.errorBackground+ : isActive+ ? theme.upcomingBackground+ : theme.pillBackground,+ color: error+ ? theme.errorText+ : isActive+ ? theme.pageTextPositive+ : theme.pageTextSubdued,+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ }}+ >+ <Icon width={14} height={14} style={{ color: 'inherit' }} />+ </View>+ <View style={{ minWidth: 0, flex: 1 }}>+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ gap: 4,+ fontSize: 12,+ fontWeight: 600,+ color: titleColor,+ }}+ >+ <Text>{meta.label}</Text>+ {error && (+ <SvgAlertTriangle+ width={11}+ height={11}+ style={{ color: 'inherit' }}+ />+ )}+ </View>+ <Text+ style={{+ fontSize: 11,+ color: subtitleColor,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ display: 'block',+ }}+ >+ {subtitle}+ </Text>+ </View>+ <View+ style={{+ flexShrink: 0,+ alignItems: 'flex-end',+ gap: 2,+ }}+ >+ <Text+ style={{+ fontSize: 12,+ fontWeight: 600,+ fontVariantNumeric: 'tabular-nums',+ color:+ contribution == null ||+ Number.isNaN(contribution) ||+ contribution === 0+ ? theme.pageTextSubdued+ : theme.pageText,+ }}+ >+ {contribution == null || Number.isNaN(contribution)+ ? '—'+ : contribution > 0+ ? '+' + format(contribution, 'financial')+ : format(contribution, 'financial')}+ </Text>+ {priority != null && (+ <Text+ style={{+ fontSize: 10,+ color: theme.pageTextSubdued,+ fontVariantNumeric: 'tabular-nums',+ letterSpacing: '0.04em',+ }}+ >+ {t('Priority: {{priority}}', { priority })}+ </Text>+ )}+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationMigrationWarning.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationMigrationWarning.tsxnew file mode 100644index 0000000000..b8d7539a8d--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationMigrationWarning.tsx@@ -0,0 +1,68 @@+import type { CSSProperties } from 'react';+import { Trans } from 'react-i18next';++import { Text } from '@actual-app/components/text';+import { View } from '@actual-app/components/view';++import { Warning } from '#components/alerts';+import { useNotes } from '#hooks/useNotes';++export function BudgetAutomationMigrationWarning({+ categoryId,+ style,+}: {+ categoryId: string;+ style?: CSSProperties;+}) {+ const notes = useNotes(categoryId);++ if (!notes) return null;+ const templates = notes+ .split('\n')+ .filter(line => /^\s*#(template|goal|cleanup)\b/.test(line))+ .join('\n');++ if (!templates) return null;++ return (+ <Warning+ style={{+ padding: '8px 12px',+ fontSize: 12,+ ...style,+ }}+ >+ <View style={{ gap: 4 }}>+ <Text>+ <Trans>+ Imported from notes-based templates. Review and Save to complete the+ migration.+ </Trans>+ </Text>+ <details>+ <summary style={{ cursor: 'pointer', fontSize: 11, opacity: 0.85 }}>+ <Trans>Show original templates</Trans>+ </summary>+ <View+ style={{+ whiteSpace: 'pre-wrap',+ fontFamily: 'monospace',+ fontSize: 11,+ marginTop: 6,+ padding: 8,+ borderRadius: 4,+ // Translucent overlay rather than a theme token so the inset+ // effect works regardless of the surrounding Warning colour+ // (which differs between light/dark/midnight themes).+ backgroundColor: 'rgba(0, 0, 0, 0.15)',+ maxHeight: 120,+ overflowY: 'auto',+ }}+ >+ {templates}+ </View>+ </details>+ </View>+ </Warning>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsxnew file mode 100644index 0000000000..fa6116377e--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsx@@ -0,0 +1,411 @@+import { useEffect, useState } from 'react';+import { Trans } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import { send } from '@actual-app/core/platform/client/connection';+import type {+ CategoryGroupEntity,+ ScheduleEntity,+} from '@actual-app/core/types/models';+import { css } from '@emotion/css';+import debounce from 'lodash/debounce';++import {+ createAutomationEntry,+ getAutomationExamples,+} from '#components/budget/goals/automationExamples';+import type { AutomationEntry } from '#components/budget/goals/automationExamples';+import { formatMonthLabel } from '#components/budget/goals/formatMonthLabel';+import { validateAutomation } from '#components/budget/goals/validateAutomation';+import type { GlobalConflictKind } from '#components/budget/goals/validateAutomation';+import { Link } from '#components/common/Link';+import { useFormat } from '#hooks/useFormat';+import { useLocale } from '#hooks/useLocale';+import { pushModal } from '#modals/modalsSlice';+import { useDispatch } from '#redux';++import { AutomationEditorPane } from './AutomationEditorPane';+import { AutomationListRow } from './AutomationListRow';+import { BudgetAutomationMigrationWarning } from './BudgetAutomationMigrationWarning';+import { ConflictBanner } from './ConflictBanner';+import { EmptyState } from './EmptyState';++const RULE_LIST_WIDTH = 310;++const ALWAYS_SCROLL_CLASS = css({+ scrollbarGutter: 'stable',+ '&::-webkit-scrollbar': {+ width: 11,+ backgroundColor: 'transparent',+ },+ '&::-webkit-scrollbar-thumb': {+ width: 7,+ minHeight: 24,+ borderRadius: 30,+ backgroundClip: 'padding-box',+ border: '2px solid rgba(0, 0, 0, 0)',+ backgroundColor: theme.tableBorder,+ },+});++type BudgetAutomationsBodyProps = {+ categoryId: string;+ categoryName: string;+ needsMigration: boolean;+ initialEntries: AutomationEntry[];+ schedules: readonly ScheduleEntity[];+ categories: CategoryGroupEntity[];+ month: string;+ onClose: () => void;+};++export function BudgetAutomationsBody({+ categoryId,+ categoryName,+ needsMigration,+ initialEntries,+ schedules,+ categories,+ month,+ onClose,+}: BudgetAutomationsBodyProps) {+ const dispatch = useDispatch();+ const format = useFormat();+ const locale = useLocale();++ const [entries, setEntries] = useState<AutomationEntry[]>(initialEntries);+ const [activeIdx, setActiveIdx] = useState(0);+ const [saving, setSaving] = useState(false);+ const [dryRun, setDryRun] = useState<{+ budgeted: number;+ perTemplate: number[];+ } | null>(null);++ const onAddAutomation = (create?: () => AutomationEntry) => {+ const fallback = getAutomationExamples().find(+ e => e.displayType === 'fixed',+ );+ const entry = (create ?? fallback?.create)?.();+ if (!entry) return;+ setEntries(prev => {+ const next = [...prev, entry];+ setActiveIdx(next.length - 1);+ return next;+ });+ };++ const onAddLimitAutomation = () => {+ const entry = createAutomationEntry(+ {+ directive: 'template',+ type: 'limit',+ amount: 500,+ period: 'monthly',+ hold: false,+ priority: null,+ },+ 'limit',+ );+ setEntries(prev => [entry, ...prev]);+ setActiveIdx(0);+ };++ const onDelete = (index: number) => {+ setEntries(prev => {+ const next = prev.filter((_, i) => i !== index);+ setActiveIdx(currentActive => {+ if (next.length === 0) return 0;+ if (currentActive >= next.length) return next.length - 1;+ if (currentActive > index) return currentActive - 1;+ return currentActive;+ });+ return next;+ });+ };++ const onSave = async () => {+ if (saving) return;+ setSaving(true);+ try {+ const templatesToSave = entries.map(({ template }) => template);+ await send('budget/set-category-automations', {+ categoriesWithTemplates: [+ { id: categoryId, templates: templatesToSave },+ ],+ source: 'ui',+ });+ onClose();+ } finally {+ setSaving(false);+ }+ };++ const onUnmigrate = () => {+ dispatch(+ pushModal({+ modal: {+ name: 'category-automations-unmigrate',+ options: {+ categoryId,+ templates: entries.map(({ template }) => template),+ },+ },+ }),+ );+ };++ const templates = entries.map(e => e.template);++ const validPercentageSources = new Set<string>([+ 'all income',+ 'available funds',+ ]);+ for (const group of categories) {+ for (const cat of group.categories ?? []) {+ if (!cat.is_income) continue;+ validPercentageSources.add(cat.id);+ if (cat.name) validPercentageSources.add(cat.name.toLowerCase());+ }+ }++ const automationErrors = entries.map(entry =>+ validateAutomation(+ entry.template,+ entry.displayType,+ templates,+ schedules,+ new Date(),+ validPercentageSources,+ ),+ );++ useEffect(() => {+ if (templates.length === 0) {+ setDryRun({ budgeted: 0, perTemplate: [] });+ return;+ }+ let cancelled = false;+ const run = debounce(async () => {+ try {+ const result = await send('budget/dry-run-category-template', {+ month,+ categoryId,+ templates,+ });+ if (!cancelled) setDryRun(result);+ } catch {+ if (!cancelled) setDryRun(null);+ }+ }, 200);+ void run();+ return () => {+ cancelled = true;+ run.cancel();+ };+ }, [templates, month, categoryId]);++ const totalMonthly = dryRun?.budgeted ?? 0;+ const contributions: (number | null)[] = entries.map((_, i) =>+ dryRun?.perTemplate?.[i] != null ? dryRun.perTemplate[i] : null,+ );+ const hasErrors = automationErrors.some(error => error !== null);+ const percentSum = templates.reduce<number>((sum, t) => {+ if (t.type === 'percentage') return sum + t.percent;+ return sum;+ }, 0);+ const conflict: GlobalConflictKind | null =+ percentSum > 100 ? { kind: 'percent-over-100', total: percentSum } : null;++ const categoryNameMap: Record<string, string> = {};+ for (const group of categories) {+ for (const cat of group.categories ?? []) {+ categoryNameMap[cat.id] = cat.name;+ }+ }++ const hasLimitAutomation = entries.some(e => e.displayType === 'limit');++ const safeActiveIdx = Math.min(activeIdx, Math.max(0, entries.length - 1));++ return (+ <View style={{ flex: 1, flexDirection: 'column', minHeight: 0 }}>+ <View+ style={{+ padding: '20px 24px 16px',+ borderBottom: `1px solid ${theme.tableBorder}`,+ flexDirection: 'row',+ alignItems: 'flex-start',+ justifyContent: 'space-between',+ gap: 16,+ }}+ >+ <View style={{ minWidth: 0 }}>+ <Text style={{ fontSize: 12, color: theme.pageTextSubdued }}>+ <Trans>Budget automation</Trans>+ </Text>+ <Text+ style={{+ fontSize: 20,+ fontWeight: 600,+ color: theme.pageText,+ marginTop: 2,+ }}+ >+ {categoryName}+ </Text>+ </View>+ <View style={{ textAlign: 'right', flexShrink: 0, minWidth: 220 }}>+ <Text+ style={{+ fontSize: 11,+ textTransform: 'uppercase',+ color: theme.pageTextSubdued,+ letterSpacing: '0.04em',+ }}+ >+ <Trans>+ Projected for {{ month: formatMonthLabel(month, locale) }}+ </Trans>+ </Text>+ <Text+ style={{+ fontSize: 22,+ fontWeight: 600,+ color: theme.pageTextPositive,+ fontVariantNumeric: 'tabular-nums',+ lineHeight: 1.2,+ display: 'block',+ }}+ >+ {format(totalMonthly, 'financial')}+ </Text>+ </View>+ </View>++ {needsMigration && (+ <BudgetAutomationMigrationWarning+ categoryId={categoryId}+ style={{ flexShrink: 0, margin: '12px 24px 0' }}+ />+ )}++ {conflict && <ConflictBanner conflict={conflict} />}++ <View+ style={{+ flex: 1,+ flexDirection: 'row',+ minHeight: 0,+ }}+ >+ <View+ className={ALWAYS_SCROLL_CLASS}+ style={{+ width: RULE_LIST_WIDTH,+ borderRight: `1px solid ${theme.tableBorder}`,+ padding: 10,+ overflowY: 'scroll',+ }}+ >+ <View+ style={{+ flexShrink: 0,+ flexDirection: 'row',+ justifyContent: 'space-between',+ alignItems: 'center',+ padding: '6px 8px',+ fontSize: 11,+ textTransform: 'uppercase',+ color: theme.pageTextSubdued,+ fontWeight: 600,+ letterSpacing: '0.05em',+ }}+ >+ <Text>+ <Trans>Automations</Trans>+ </Text>+ </View>+ {entries.map((entry, i) => (+ <AutomationListRow+ key={entry.id}+ index={i}+ entry={entry}+ isActive={i === safeActiveIdx}+ error={automationErrors[i]}+ contribution={contributions[i]}+ categoryNameMap={categoryNameMap}+ onSelect={setActiveIdx}+ />+ ))}+ <Button+ variant="bare"+ onPress={() => onAddAutomation()}+ style={{+ width: '100%',+ marginTop: 8,+ padding: 10,+ border: `1px dashed ${theme.tableBorder}`,+ borderRadius: 6,+ color: theme.pageTextPositive,+ fontWeight: 600,+ fontSize: 12,+ justifyContent: 'center',+ }}+ >+ + <Trans>Add an automation</Trans>+ </Button>+ </View>++ <View style={{ flex: 1, minWidth: 0 }}>+ {entries.length === 0 ? (+ <EmptyState onAdd={onAddAutomation} />+ ) : (+ <AutomationEditorPane+ entries={entries}+ activeIdx={safeActiveIdx}+ automationErrors={automationErrors}+ schedules={schedules}+ categories={categories}+ hasLimitAutomation={hasLimitAutomation}+ onAddLimitAutomation={onAddLimitAutomation}+ setEntries={setEntries}+ onDelete={onDelete}+ />+ )}+ </View>+ </View>++ <View+ style={{+ padding: '12px 20px',+ borderTop: `1px solid ${theme.tableBorder}`,+ flexDirection: 'row',+ gap: 8,+ alignItems: 'center',+ backgroundColor: theme.tableBackground,+ flexShrink: 0,+ }}+ >+ {!needsMigration && (+ <Link variant="text" onClick={onUnmigrate}>+ <Trans>Un-migrate to text notes</Trans>+ </Link>+ )}+ <View style={{ flex: 1 }} />+ <Button onPress={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ <Button+ variant="primary"+ onPress={onSave}+ isDisabled={hasErrors || conflict !== null || saving}+ >+ <Trans>Save</Trans>+ </Button>+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal.test.ts b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.test.tssimilarity index 64%rename from packages/desktop-client/src/components/modals/BudgetAutomationsModal.test.tsrename to packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.test.tsindex 2252c39325..13710acaf9 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal.test.ts+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.test.ts@@ -1,21 +1,41 @@import type { Template } from '@actual-app/core/types/models/templates';-import { migrateTemplatesToAutomations } from './BudgetAutomationsModal';+import { migrateTemplatesToAutomations } from './migrateTemplatesToAutomations';describe('migrateTemplatesToAutomations', () => {- it('preserves simple templates that have no limit and no monthly amount', () => {+ it('drops simple templates that have no limit and no monthly amount', () => {+ // these would otherwise be pushed as a phantom 'fixed' entry that+ // crashes FixedAutomationReadOnly (no .amount, no .period)const simpleTemplate = {type: 'simple',directive: 'template',priority: 5,} satisfies Template;- const result = migrateTemplatesToAutomations([simpleTemplate]);+ expect(migrateTemplatesToAutomations([simpleTemplate])).toEqual([]);+ });- expect(result).toHaveLength(1);- expect(result[0].displayType).toBe('week');- expect(result[0].template).toEqual(simpleTemplate);- expect(result[0].id).toMatch(/^automation-/);+ it('drops simple templates whose monthly amount is zero with no limit', () => {+ const simpleTemplate = {+ type: 'simple',+ directive: 'template',+ priority: 5,+ monthly: 0,+ } satisfies Template;++ expect(migrateTemplatesToAutomations([simpleTemplate])).toEqual([]);+ });++ it('throws when a goal directive reaches migration', () => {+ const goalTemplate = {+ type: 'goal',+ amount: 1000,+ directive: 'goal',+ } satisfies Template;++ expect(() => migrateTemplatesToAutomations([goalTemplate])).toThrow(+ /Unsupported template type/,+ );});it('expands a simple template with limit into limit and refill entries', () => {@@ -63,7 +83,7 @@ describe('migrateTemplatesToAutomations', () => {const result = migrateTemplatesToAutomations([simpleTemplate]);expect(result).toHaveLength(1);- expect(result[0].displayType).toBe('week');+ expect(result[0].displayType).toBe('fixed');expect(result[0].template).toMatchObject({type: 'periodic',amount: 45,@@ -79,7 +99,10 @@ describe('migrateTemplatesToAutomations', () => {});});- it('expands a simple template with both limit and monthly into three entries in order', () => {+ it('expands a simple template with both limit and monthly into limit + periodic (no implicit refill)', () => {+ // `#template 20 up to 200 per week` budgets 20/month and caps at the+ // limit — the engine's runSimple returns just the monthly value, so+ // there is no implicit refill-to-cap behaviour to migrate.const simpleTemplate = {type: 'simple',directive: 'template',@@ -94,13 +117,9 @@ describe('migrateTemplatesToAutomations', () => {const result = migrateTemplatesToAutomations([simpleTemplate]);- expect(result).toHaveLength(3);- expect(result.map(entry => entry.displayType)).toEqual([- 'limit',- 'refill',- 'week',- ]);- expect(result[2].template).toMatchObject({+ expect(result).toHaveLength(2);+ expect(result.map(entry => entry.displayType)).toEqual(['limit', 'fixed']);+ expect(result[1].template).toMatchObject({type: 'periodic',amount: 20,directive: 'template',diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsxnew file mode 100644index 0000000000..22cd3d5163--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx@@ -0,0 +1,125 @@+import { useState } from 'react';++import { AnimatedLoading } from '@actual-app/components/icons/AnimatedLoading';+import { View } from '@actual-app/components/view';+import { currentMonth } from '@actual-app/core/shared/months';+import { q } from '@actual-app/core/shared/query';+import type { Template } from '@actual-app/core/types/models/templates';++import { useBudgetAutomationCategories } from '#components/budget/goals/useBudgetAutomationCategories';+import { Modal } from '#components/common/Modal';+import { useBudgetAutomations } from '#hooks/useBudgetAutomations';+import { useCategory } from '#hooks/useCategory';+import { useNotes } from '#hooks/useNotes';+import { useSchedules } from '#hooks/useSchedules';++import { BudgetAutomationsBody } from './BudgetAutomationsBody';+import { migrateTemplatesToAutomations } from './migrateTemplatesToAutomations';+import {+ hasCleanupLine,+ UnsupportedDirectivesNotice,+} from './UnsupportedDirectivesNotice';++const MODAL_WIDTH = 960;+const MODAL_HEIGHT = 760;++export function BudgetAutomationsModal({+ categoryId,+ month,+}: {+ categoryId: string;+ month?: string;+}) {+ const [parsedTemplates, setParsedTemplates] = useState<Template[] | null>(+ null,+ );+ const effectiveMonth = month ?? currentMonth();++ const onLoaded = (result: Record<string, Template[]>) => {+ setParsedTemplates(result[categoryId] ?? []);+ };++ const { loading } = useBudgetAutomations({ categoryId, onLoaded });++ const { schedules } = useSchedules({ query: q('schedules').select('*') });++ const categories = useBudgetAutomationCategories();+ const { data: currentCategory } = useCategory(categoryId);+ const notes = useNotes(categoryId);++ const needsMigration = currentCategory?.template_settings?.source !== 'ui';++ const hasGoalTemplate =+ parsedTemplates?.some(t => t.type === 'goal') ?? false;+ const hasErrorTemplate =+ parsedTemplates?.some(t => t.type === 'error') ?? false;+ const hasSpendTemplate =+ parsedTemplates?.some(t => t.type === 'spend') ?? false;+ // Only surface stale `#cleanup` lines for categories that haven't been+ // migrated to UI-managed automations; once `source === 'ui'`, the notes+ // are no longer the source of truth.+ const hasCleanupDirective = needsMigration && hasCleanupLine(notes);+ const hasUnsupportedDirective =+ hasGoalTemplate ||+ hasErrorTemplate ||+ hasSpendTemplate ||+ hasCleanupDirective;++ const initialEntries =+ parsedTemplates && !hasUnsupportedDirective+ ? migrateTemplatesToAutomations(parsedTemplates)+ : null;++ return (+ <Modal+ name="category-automations-edit"+ containerProps={{+ style: {+ width: MODAL_WIDTH,+ maxWidth: '95vw',+ height: MODAL_HEIGHT,+ maxHeight: '90vh',+ padding: 0,+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column',+ },+ }}+ >+ {({ state }) => (+ <View style={{ flex: 1, minHeight: 0 }}>+ {loading || parsedTemplates === null ? (+ <View+ style={{+ flex: 1,+ alignItems: 'center',+ justifyContent: 'center',+ }}+ >+ <AnimatedLoading style={{ width: 20, height: 20 }} />+ </View>+ ) : hasUnsupportedDirective ? (+ <UnsupportedDirectivesNotice+ hasGoalTemplate={hasGoalTemplate}+ hasErrorTemplate={hasErrorTemplate}+ hasSpendTemplate={hasSpendTemplate}+ hasCleanupDirective={hasCleanupDirective}+ onClose={() => state.close()}+ />+ ) : (+ <BudgetAutomationsBody+ categoryId={categoryId}+ categoryName={currentCategory?.name ?? ''}+ needsMigration={needsMigration}+ initialEntries={initialEntries ?? []}+ schedules={schedules}+ categories={categories}+ month={effectiveMonth}+ onClose={() => state.close()}+ />+ )}+ </View>+ )}+ </Modal>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/ConflictBanner.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/ConflictBanner.tsxnew file mode 100644index 0000000000..4fb4e2f868--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/ConflictBanner.tsx@@ -0,0 +1,39 @@+import { SvgAlertTriangle } from '@actual-app/components/icons/v2';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import {+ GlobalConflictDetail,+ GlobalConflictTitle,+} from '#components/budget/goals/automationMessages';+import type { GlobalConflictKind } from '#components/budget/goals/validateAutomation';++type ConflictBannerProps = {+ conflict: GlobalConflictKind;+};++export function ConflictBanner({ conflict }: ConflictBannerProps) {+ return (+ <View+ style={{+ padding: '8px 22px',+ backgroundColor: theme.errorBackground,+ borderBottom: `1px solid ${theme.errorBorder}`,+ color: theme.errorText,+ fontSize: 12,+ flexDirection: 'row',+ gap: 8,+ alignItems: 'center',+ }}+ >+ <SvgAlertTriangle width={14} height={14} style={{ color: 'inherit' }} />+ <Text style={{ color: 'inherit' }}>+ <strong>+ <GlobalConflictTitle conflict={conflict} />.+ </strong>{' '}+ <GlobalConflictDetail conflict={conflict} />+ </Text>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/EmptyState.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/EmptyState.tsxnew file mode 100644index 0000000000..fd22e24075--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/EmptyState.tsx@@ -0,0 +1,138 @@+import { Trans } from 'react-i18next';++import { SvgAlertTriangle } from '@actual-app/components/icons/v2';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import { getAutomationExamples } from '#components/budget/goals/automationExamples';+import type { AutomationEntry } from '#components/budget/goals/automationExamples';+import { getDisplayTemplateMeta } from '#components/budget/goals/displayTemplateMeta';++type EmptyStateProps = {+ onAdd: (create: () => AutomationEntry) => void;+};++export function EmptyState({ onAdd }: EmptyStateProps) {+ const examples = getAutomationExamples();++ return (+ <View+ style={{+ padding: '40px 20px',+ textAlign: 'center',+ maxWidth: 540,+ margin: '0 auto',+ }}+ >+ <View+ style={{+ width: 56,+ height: 56,+ borderRadius: 12,+ margin: '0 auto 14px',+ backgroundColor: theme.upcomingBackground,+ color: theme.pageTextPositive,+ alignItems: 'center',+ justifyContent: 'center',+ }}+ >+ <SvgAlertTriangle width={20} height={20} style={{ color: 'inherit' }} />+ </View>+ <Text+ style={{+ fontSize: 18,+ fontWeight: 600,+ color: theme.pageText,+ letterSpacing: '-0.01em',+ }}+ >+ <Trans>No automations yet</Trans>+ </Text>+ <Text+ style={{+ fontSize: 13,+ color: theme.pageTextSubdued,+ marginTop: 4,+ marginBottom: 22,+ display: 'block',+ }}+ >+ <Trans>+ Budget automations keep this category funded with one click each+ month. Start with one of these.+ </Trans>+ </Text>+ <View+ style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr 1fr',+ gap: 10,+ textAlign: 'center',+ }}+ >+ {examples.map(example => {+ const meta = getDisplayTemplateMeta(example.displayType);+ const Icon = meta.icon;+ return (+ <View+ key={example.displayType}+ role="button"+ tabIndex={0}+ aria-label={meta.label}+ onClick={() => onAdd(example.create)}+ onKeyDown={e => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onAdd(example.create);+ }+ }}+ style={{+ padding: 14,+ borderRadius: 8,+ backgroundColor: theme.cardBackground,+ border: `1px solid ${theme.tableBorder}`,+ gap: 6,+ cursor: 'pointer',+ }}+ >+ <View+ style={{+ width: 30,+ height: 30,+ borderRadius: 6,+ backgroundColor: theme.upcomingBackground,+ color: theme.pageTextPositive,+ alignItems: 'center',+ justifyContent: 'center',+ alignSelf: 'center',+ marginBottom: 6,+ }}+ >+ <Icon width={16} height={16} />+ </View>+ <Text+ style={{+ fontSize: 13,+ fontWeight: 600,+ color: theme.pageText,+ }}+ >+ {meta.label}+ </Text>+ <Text+ style={{+ fontSize: 11,+ color: theme.pageTextSubdued,+ lineHeight: 1.4,+ }}+ >+ {meta.description}+ </Text>+ </View>+ );+ })}+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/TypePicker.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/TypePicker.tsxnew file mode 100644index 0000000000..fc710a0c5b--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/TypePicker.tsx@@ -0,0 +1,109 @@+import { useTranslation } from 'react-i18next';++import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import { displayTemplateTypes } from '#components/budget/goals/constants';+import type { DisplayTemplateType } from '#components/budget/goals/constants';+import { getDisplayTemplateMeta } from '#components/budget/goals/displayTemplateMeta';++type TypePickerProps = {+ active: DisplayTemplateType;+ disabledTypes: ReadonlySet<DisplayTemplateType>;+ onPick: (type: DisplayTemplateType) => void;+};++export function TypePicker({ active, disabledTypes, onPick }: TypePickerProps) {+ const { t } = useTranslation();+ const entries = displayTemplateTypes.map(+ id => [id, getDisplayTemplateMeta(id)] as const,+ );+ const disabledHint = t('Only one of this type allowed per category');++ return (+ <View+ style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(4, 1fr)',+ gap: 8,+ }}+ >+ {entries.map(([id, meta]) => {+ const Icon = meta.icon;+ const isActive = id === active;+ const isDisabled = !isActive && disabledTypes.has(id);+ return (+ <View+ key={id}+ role="button"+ tabIndex={isDisabled ? -1 : 0}+ aria-pressed={isActive}+ aria-disabled={isDisabled}+ title={isDisabled ? disabledHint : undefined}+ onClick={() => {+ if (!isDisabled) onPick(id);+ }}+ onKeyDown={e => {+ if (isDisabled) return;+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onPick(id);+ }+ }}+ style={{+ padding: '10px 10px 8px',+ borderRadius: 6,+ backgroundColor: isActive+ ? theme.upcomingBackground+ : theme.cardBackground,+ border: `1px solid ${isActive ? theme.pageTextPositive : theme.tableBorder}`,+ gap: 6,+ cursor: isDisabled ? 'not-allowed' : 'pointer',+ opacity: isDisabled ? 0.45 : 1,+ minWidth: 0,+ }}+ >+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ gap: 8,+ }}+ >+ <Icon+ width={16}+ height={16}+ style={{+ flexShrink: 0,+ color: isActive ? theme.pageTextPositive : theme.pageText,+ }}+ />+ <Text+ style={{+ display: 'block',+ fontSize: 12,+ fontWeight: 600,+ color: isActive ? theme.pageTextPositive : theme.pageText,+ lineHeight: 1.25,+ }}+ >+ {meta.label}+ </Text>+ </View>+ <Text+ style={{+ display: 'block',+ fontSize: 11,+ color: theme.pageTextSubdued,+ lineHeight: 1.35,+ }}+ >+ {meta.description}+ </Text>+ </View>+ );+ })}+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsxnew file mode 100644index 0000000000..8b4301a8a5--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsx@@ -0,0 +1,100 @@+import { Trans } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgAlertTriangle } from '@actual-app/components/icons/v2';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++export function UnsupportedDirectivesNotice({+ hasGoalTemplate,+ hasErrorTemplate,+ hasSpendTemplate,+ hasCleanupDirective,+ onClose,+}: {+ hasGoalTemplate: boolean;+ hasErrorTemplate: boolean;+ hasSpendTemplate: boolean;+ hasCleanupDirective: boolean;+ onClose: () => void;+}) {+ return (+ <View+ style={{+ flex: 1,+ padding: 32,+ gap: 16,+ alignItems: 'center',+ justifyContent: 'center',+ textAlign: 'center',+ }}+ >+ <SvgAlertTriangle+ width={32}+ height={32}+ style={{ color: theme.errorText }}+ />+ <Text+ style={{+ fontSize: 18,+ fontWeight: 600,+ color: theme.pageText,+ }}+ >+ <Trans>This category isn’t supported in the UI yet</Trans>+ </Text>+ <Text+ style={{+ fontSize: 13,+ color: theme.pageTextSubdued,+ maxWidth: 480,+ lineHeight: 1.5,+ }}+ >+ {hasErrorTemplate ? (+ <Trans>+ One or more <code>#template</code> lines in this category’s+ notes couldn’t be parsed. Fix them as text first, then re-open+ this modal to migrate.+ </Trans>+ ) : hasSpendTemplate ? (+ <Trans>+ This category uses a <code>spend from</code> template, which the+ budget automations UI doesn’t handle yet. Keep editing it as+ text in the category’s notes.+ </Trans>+ ) : hasGoalTemplate && hasCleanupDirective ? (+ <Trans>+ This category’s notes use <code>#goal</code> and{' '}+ <code>#cleanup</code> directives, neither of which the budget+ automations UI handles yet. Keep editing them as text in the+ category’s notes.+ </Trans>+ ) : hasGoalTemplate ? (+ <Trans>+ This category uses a <code>#goal</code> directive, which the budget+ automations UI doesn’t handle yet. Keep editing it as text in+ the category’s notes.+ </Trans>+ ) : (+ <Trans>+ This category uses a <code>#cleanup</code> directive, which the+ budget automations UI doesn’t handle yet. Keep editing it as+ text in the category’s notes.+ </Trans>+ )}+ </Text>+ <Button onPress={onClose}>+ <Trans>Close</Trans>+ </Button>+ </View>+ );+}++const CLEANUP_DIRECTIVE = /^\s*#cleanup\b/;++export function hasCleanupLine(notes: string | null | undefined): boolean {+ if (!notes) return false;+ return notes.split('\n').some(line => CLEANUP_DIRECTIVE.test(line));+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/index.ts b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/index.tsnew file mode 100644index 0000000000..a5170735be--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/index.ts@@ -0,0 +1,2 @@+export { BudgetAutomationsModal } from './BudgetAutomationsModal';+export { migrateTemplatesToAutomations } from './migrateTemplatesToAutomations';diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.tsnew file mode 100644index 0000000000..bf7174ab25--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts@@ -0,0 +1,111 @@+import { dayFromDate, firstDayOfMonth } from '@actual-app/core/shared/months';+import type { Template } from '@actual-app/core/types/models/templates';++import { createAutomationEntry } from '#components/budget/goals/automationExamples';+import type { AutomationEntry } from '#components/budget/goals/automationExamples';+import type { DisplayTemplateType } from '#components/budget/goals/constants';++function getDisplayTypeFromTemplate(template: Template): DisplayTemplateType {+ switch (template.type) {+ case 'percentage':+ return 'percentage';+ case 'schedule':+ return 'schedule';+ case 'periodic':+ case 'simple':+ return 'fixed';+ case 'limit':+ return 'limit';+ case 'refill':+ return 'refill';+ case 'average':+ case 'copy':+ return 'historical';+ case 'by':+ return 'by';+ case 'remainder':+ return 'remainder';+ case 'goal':+ case 'error':+ case 'spend':+ // filtered upstream by hasUnsupportedDirective; surface if it ever isn't+ throw new Error(`Unsupported template type reached migration`);+ default: {+ const _exhaustive: never = template;+ void _exhaustive;+ throw new Error(`Unhandled template type`);+ }+ }+}++export function migrateTemplatesToAutomations(+ templates: Template[],+): AutomationEntry[] {+ const entries: AutomationEntry[] = [];++ templates.forEach(template => {+ if (template.type === 'simple') {+ const monthly = template.monthly;+ const hasMonthly = monthly != null && monthly !== 0;++ if (template.limit) {+ entries.push(+ createAutomationEntry(+ {+ type: 'limit',+ amount: template.limit.amount,+ hold: template.limit.hold,+ period: template.limit.period,+ start: template.limit.start,+ directive: 'template',+ priority: null,+ },+ 'limit',+ ),+ );+ // The implicit refill only applies to a limit-only simple template+ // (e.g. `#template up to 200`). When a monthly amount is also set+ // (`#template 50 up to 200`), the engine just budgets the monthly+ // amount and clamps to the cap — no top-up to the limit.+ if (!hasMonthly) {+ entries.push(+ createAutomationEntry(+ {+ type: 'refill',+ directive: 'template',+ priority: template.priority,+ },+ 'refill',+ ),+ );+ }+ }+ if (hasMonthly) {+ entries.push(+ createAutomationEntry(+ {+ type: 'periodic',+ amount: monthly,+ period: { period: 'month', amount: 1 },+ starting: dayFromDate(firstDayOfMonth(new Date())),+ directive: 'template',+ priority: template.priority,+ },+ 'fixed',+ ),+ );+ }++ // a simple template with neither monthly nor limit is a no-op; drop it+ // rather than passing through as a phantom 'fixed' entry that would+ // crash FixedAutomationReadOnly (no .amount, no .period)+ return;+ }++ entries.push(+ createAutomationEntry(template, getDisplayTypeFromTemplate(template)),+ );+ });++ return entries;+}diff --git a/packages/desktop-client/src/components/modals/UnmigrateBudgetAutomationsModal.tsx b/packages/desktop-client/src/components/modals/UnmigrateBudgetAutomationsModal.tsxindex dae373e8c2..20b6cc18d2 100644--- a/packages/desktop-client/src/components/modals/UnmigrateBudgetAutomationsModal.tsx+++ b/packages/desktop-client/src/components/modals/UnmigrateBudgetAutomationsModal.tsx@@ -11,9 +11,26 @@ import type { Template } from '@actual-app/core/types/models/templates';import { Link } from '#components/common/Link';import { Modal, ModalCloseButton, ModalHeader } from '#components/common/Modal';import { Notes } from '#components/Notes';+import { useCategories } from '#hooks/useCategories';import { useCategory } from '#hooks/useCategory';import { useNotes } from '#hooks/useNotes';+// The UI's CategoryAutocomplete stores the income category id on a+// percentage template, but text-template grammar addresses categories by+// name. Rewrite percentage templates so the un-migrated notes are readable+// (and don't drift if the category is later renamed).+function sanitizePercentageCategoriesForNotes(+ templates: Template[],+ idToName: Map<string, string>,+): Template[] {+ return templates.map(template => {+ if (template.type !== 'percentage') return template;+ const name = idToName.get(template.category);+ if (name) return { ...template, category: name };+ return template;+ });+}+export function UnmigrateBudgetAutomationsModal({categoryId,templates,@@ -23,6 +40,7 @@ export function UnmigrateBudgetAutomationsModal({}) {const { t } = useTranslation();const { data: category } = useCategory(categoryId);+ const { data: categoryData } = useCategories();const existingNotes = useNotes(categoryId) || '';const [editedNotes, setEditedNotes] = useState<string>('');@@ -30,12 +48,18 @@ export function UnmigrateBudgetAutomationsModal({const [saving, setSaving] = useState(false);useEffect(() => {+ if (!categoryData?.list) return;+ const idToName = new Map<string, string>();+ for (const cat of categoryData.list) {+ idToName.set(cat.id, cat.name);+ }+ const sanitized = sanitizePercentageCategoriesForNotes(templates, idToName);let mounted = true;void (async () => {try {const text: string = await send('budget/render-note-templates',- templates,+ sanitized,);if (mounted) setRendered(text);} catch {@@ -45,7 +69,7 @@ export function UnmigrateBudgetAutomationsModal({return () => {mounted = false;};- }, [templates]);+ }, [templates, categoryData]);// Seed editable notes once templates rendereduseEffect(() => {@@ -87,13 +111,21 @@ export function UnmigrateBudgetAutomationsModal({async function onSave(close: () => void) {setSaving(true);- await send('notes-save-undoable', { id: categoryId, note: editedNotes });- await send('budget/set-category-automations', {- categoriesWithTemplates: [{ id: categoryId, templates }],- source: 'notes',- });- setSaving(false);- close();+ try {+ await send('notes-save-undoable', { id: categoryId, note: editedNotes });+ // Hand control back to the notes parser: clear the UI-managed goal_def+ // and mark notes as the source of truth. `storeNoteTemplates` will+ // re-derive goal_def from the notes the next time it runs (e.g. on+ // modal open or when applying templates).+ await send('budget/set-category-automations', {+ categoriesWithTemplates: [{ id: categoryId, templates: [] }],+ source: 'notes',+ });+ await send('budget/store-note-templates');+ close();+ } finally {+ setSaving(false);+ }}return (diff --git a/packages/desktop-client/src/components/settings/Experimental.tsx b/packages/desktop-client/src/components/settings/Experimental.tsxindex 3de21078f6..cd6bdf27fc 100644--- a/packages/desktop-client/src/components/settings/Experimental.tsx+++ b/packages/desktop-client/src/components/settings/Experimental.tsx@@ -151,10 +151,7 @@ export function ExperimentalFeatures() {const goalTemplatesEnabled = useFeatureFlag('goalTemplatesEnabled');const goalTemplatesUIEnabled = useFeatureFlag('goalTemplatesUIEnabled');- const showGoalTemplatesUI =- goalTemplatesUIEnabled ||- (goalTemplatesEnabled &&- localStorage.getItem('devEnableGoalTemplatesUI') === 'true');+ const showGoalTemplatesUI = goalTemplatesEnabled || goalTemplatesUIEnabled;const showServerPrefs =localStorage.getItem('devEnableServerPrefs') === 'true';diff --git a/packages/desktop-client/src/modals/modalsSlice.ts b/packages/desktop-client/src/modals/modalsSlice.tsindex dac79c63c3..284e09a324 100644--- a/packages/desktop-client/src/modals/modalsSlice.ts+++ b/packages/desktop-client/src/modals/modalsSlice.ts@@ -610,6 +610,7 @@ export type Modal =name: 'category-automations-edit';options: {categoryId: CategoryEntity['id'];+ month?: string;};}| {diff --git a/packages/loot-core/src/server/budget/app.ts b/packages/loot-core/src/server/budget/app.tsindex a0b1776bf3..bc85490929 100644--- a/packages/loot-core/src/server/budget/app.ts+++ b/packages/loot-core/src/server/budget/app.ts@@ -57,6 +57,7 @@ export type BudgetHandlers = {'must-category-transfer': typeof isCategoryTransferRequired;'budget/get-category-automations': typeof goalActions.getTemplatesForCategory;'budget/set-category-automations': typeof goalActions.storeTemplates;+ 'budget/dry-run-category-template': typeof goalActions.dryRunCategoryTemplate;'budget/store-note-templates': typeof goalNoteActions.storeNoteTemplates;'budget/render-note-templates': typeof goalNoteActions.unparse;};@@ -153,6 +154,10 @@ app.method('budget/set-category-automations',mutator(undoable(goalActions.storeTemplates)),);+app.method(+ 'budget/dry-run-category-template',+ goalActions.dryRunCategoryTemplate,+);app.method('budget/store-note-templates',mutator(goalNoteActions.storeNoteTemplates),diff --git a/packages/loot-core/src/server/budget/category-template-context.test.ts b/packages/loot-core/src/server/budget/category-template-context.test.tsindex a10625a83a..54897042df 100644--- a/packages/loot-core/src/server/budget/category-template-context.test.ts+++ b/packages/loot-core/src/server/budget/category-template-context.test.ts@@ -5,7 +5,7 @@ import * as db from '#server/db';import type { DbCategory } from '#server/db';import { amountToInteger } from '#shared/util';import type { CategoryEntity } from '#types/models';-import type { Template } from '#types/models/templates';+import type { ByTemplate, Template } from '#types/models/templates';import * as actions from './actions';import { CategoryTemplateContext } from './category-template-context';@@ -876,7 +876,7 @@ describe('CategoryTemplateContext', () => {it('should calculate monthly amount needed for multiple targets', () => {const result = CategoryTemplateContext.runBy(instance);- expect(result).toBe(66667);+ expect(result.toBudget).toBe(66667);});it('should handle repeating targets', () => {@@ -906,7 +906,7 @@ describe('CategoryTemplateContext', () => {);const result = CategoryTemplateContext.runBy(instance);- expect(result).toBe(83333);+ expect(result.toBudget).toBe(83333);});it('should handle existing balance', () => {@@ -934,7 +934,7 @@ describe('CategoryTemplateContext', () => {);const result = CategoryTemplateContext.runBy(instance);- expect(result).toBe(66500); // (1000 + 2000 - 5) / 3+ expect(result.toBudget).toBe(66500); // (1000 + 2000 - 5) / 3});});@@ -1707,6 +1707,201 @@ describe('CategoryTemplateContext', () => {});});+ describe('per-template attribution', () => {+ const category: CategoryEntity = {+ id: 'attribution-cat',+ name: 'Attribution Category',+ group: 'g',+ is_income: false,+ };++ it('sums per-template contributions to the engine total for sibling periodic templates', async () => {+ const templates: Template[] = [+ {+ type: 'periodic',+ amount: 100,+ period: { period: 'month', amount: 1 },+ starting: '2024-01-01',+ directive: 'template',+ priority: 1,+ },+ {+ type: 'periodic',+ amount: 50,+ period: { period: 'month', amount: 1 },+ starting: '2024-01-01',+ directive: 'template',+ priority: 1,+ },+ ];+ const instance = new TestCategoryTemplateContext(+ templates,+ category,+ '2024-01',+ 0,+ 0,+ );+ await instance.runTemplatesForPriority(1, 1_000_000, 1_000_000);+ const values = instance.getValues();+ const contributions = templates.map(+ t => values.perTemplateContribution.get(t) ?? 0,+ );+ expect(contributions).toEqual([10000, 5000]);+ expect(contributions.reduce((a, b) => a + b, 0)).toBe(values.budgeted);+ });++ it('weights `by` siblings by their effective per-month need from runBy, not raw target', async () => {+ // The redistribute weight uses runBy's effective per-template need+ // (back-interpolated over the shortest sibling window) rather than+ // raw target amounts.+ const templates: Template[] = [+ {+ type: 'by',+ amount: 1200,+ month: '2025-01',+ annual: false,+ directive: 'template',+ priority: 1,+ },+ {+ type: 'by',+ amount: 100,+ month: '2024-02',+ annual: false,+ directive: 'template',+ priority: 1,+ },+ ];+ const instance = new TestCategoryTemplateContext(+ templates,+ category,+ '2024-01',+ 0,+ 0,+ );+ await instance.runTemplatesForPriority(1, 1_000_000, 1_000_000);+ const values = instance.getValues();+ const longHorizon = values.perTemplateContribution.get(templates[0]) ?? 0;+ const urgent = values.perTemplateContribution.get(templates[1]) ?? 0;+ expect(longHorizon + urgent).toBe(values.budgeted);++ // Raw-amount weighting would give the urgent $100 template only a+ // 100/1300 share. Need-based weighting gives it much more.+ const rawShareUrgent = Math.round((values.budgeted * 100) / (100 + 1200));+ expect(urgent).toBeGreaterThan(rawShareUrgent * 4);+ });++ it('scales per-template contributions when a balance cap clamps the total', async () => {+ const templates: Template[] = [+ {+ type: 'periodic',+ amount: 100,+ period: { period: 'month', amount: 1 },+ starting: '2024-01-01',+ directive: 'template',+ priority: 1,+ },+ {+ type: 'periodic',+ amount: 50,+ period: { period: 'month', amount: 1 },+ starting: '2024-01-01',+ directive: 'template',+ priority: 1,+ },+ {+ type: 'limit',+ amount: 120,+ hold: false,+ period: 'monthly',+ directive: 'template',+ priority: null,+ },+ ];+ const instance = new TestCategoryTemplateContext(+ templates,+ category,+ '2024-01',+ 0,+ 0,+ );+ await instance.runTemplatesForPriority(1, 1_000_000, 1_000_000);+ const values = instance.getValues();+ // $150 demanded, cap $120; per-row contributions sum to the clamp.+ const sum = templates.reduce(+ (acc, t) => acc + (values.perTemplateContribution.get(t) ?? 0),+ 0,+ );+ expect(sum).toBe(values.budgeted);+ expect(values.budgeted).toBe(12000);+ for (const t of templates) {+ expect(+ values.perTemplateContribution.get(t) ?? 0,+ ).toBeGreaterThanOrEqual(0);+ }+ });++ it('attributes remainder rules per template by weight', async () => {+ const templates: Template[] = [+ {+ type: 'remainder',+ weight: 3,+ directive: 'template',+ priority: null,+ },+ {+ type: 'remainder',+ weight: 1,+ directive: 'template',+ priority: null,+ },+ ];+ const instance = new TestCategoryTemplateContext(+ templates,+ category,+ '2024-01',+ 0,+ 0,+ );+ instance.runRemainder(100, 25);+ const values = instance.getValues();+ expect(values.perTemplateContribution.get(templates[0])).toBe(75);+ expect(values.perTemplateContribution.get(templates[1])).toBe(25);+ });++ it('runBy returns a per-template need map keyed by template reference', () => {+ const templates: ByTemplate[] = [+ {+ type: 'by',+ amount: 1200,+ month: '2024-12',+ annual: false,+ directive: 'template',+ priority: 1,+ },+ {+ type: 'by',+ amount: 600,+ month: '2024-12',+ annual: false,+ directive: 'template',+ priority: 1,+ },+ ];+ const instance = new TestCategoryTemplateContext(+ templates,+ category,+ '2024-01',+ 0,+ 0,+ );+ const result = CategoryTemplateContext.runBy(instance);+ // Same horizon for both, so per-template need == target amount.+ expect(result.perTemplateNeed.get(templates[0])).toBe(120000);+ expect(result.perTemplateNeed.get(templates[1])).toBe(60000);+ });+ });+describe('validation (init checks)', () => {const category: CategoryEntity = {id: 'val-cat',@@ -1866,6 +2061,38 @@ describe('CategoryTemplateContext', () => {expect(budgeted).toBeGreaterThan(0);});+ it('accepts a percentage template that uses an income category id', async () => {+ // CategoryAutocomplete stores the id; the case-folded name is also+ // accepted for text-template compatibility.+ vi.mocked(statements.getActiveSchedules).mockResolvedValue(+ [] as Awaited<ReturnType<typeof statements.getActiveSchedules>>,+ );+ vi.mocked(db.getCategories).mockResolvedValue([+ {+ id: 'inc-1',+ name: 'Salary',+ is_income: 1,+ cat_group: 'g-income',+ sort_order: 0,+ hidden: 0,+ tombstone: 0,+ } satisfies DbCategory,+ ]);+ const templates: Template[] = [+ {+ type: 'percentage',+ percent: 10,+ previous: false,+ category: 'inc-1',+ directive: 'template',+ priority: 1,+ },+ ];+ await expect(+ CategoryTemplateContext.init(templates, category, '2024-01', 0),+ ).resolves.toBeDefined();+ });+it('accepts the special `all income` and `available funds` source aliases', async () => {vi.mocked(statements.getActiveSchedules).mockResolvedValue([] as Awaited<ReturnType<typeof statements.getActiveSchedules>>,diff --git a/packages/loot-core/src/server/budget/category-template-context.ts b/packages/loot-core/src/server/budget/category-template-context.tsindex ed09080cf2..27ba413250 100644--- a/packages/loot-core/src/server/budget/category-template-context.ts+++ b/packages/loot-core/src/server/budget/category-template-context.ts@@ -148,9 +148,12 @@ export class CategoryTemplateContext {);let available = budgetAvail || 0;let toBudget = 0;+ const perTemplateLocal = new Map<Template, number>();let byFlag = false;let remainder = 0;let scheduleFlag = false;+ let schedulePerTemplate: Map<string, number> | null = null;+ let byPerTemplate: Map<ByTemplate, number> | null = null;// switch on template type and calculate the amount for the linefor (const template of t) {let newBudget = 0;@@ -186,7 +189,9 @@ export class CategoryTemplateContext {case 'by': {// all by's get run at onceif (!byFlag) {- newBudget = CategoryTemplateContext.runBy(this);+ const ret = CategoryTemplateContext.runBy(this);+ newBudget = ret.toBudget;+ byPerTemplate = ret.perTemplateNeed;} else {newBudget = 0;}@@ -211,6 +216,7 @@ export class CategoryTemplateContext {// needs to remove the previous funds so they aren't double countednewBudget = ret.to_budget - toBudget;remainder = ret.remainder;+ schedulePerTemplate = ret.perScheduleMonthly;scheduleFlag = true;}break;@@ -226,8 +232,35 @@ export class CategoryTemplateContext {available = available - newBudget;toBudget += newBudget;+ perTemplateLocal.set(+ template,+ (perTemplateLocal.get(template) ?? 0) + newBudget,+ );}+ // `runBy` and `runSchedule` produce a single batch total per priority bucket+ // and the loop above credits it to whichever sibling template ran first. For+ // per-template UI projections we want to split that batch across all the+ // sibling templates. The breakdown is approximate (equal split for schedule,+ // weighted by goal amount for by); the actual budgeted total is unaffected.+ // Weight by each `by` template's effective per-month need (as computed+ // inside runBy) rather than its raw target amount, so per-row UI+ // projections reflect templates with shorter deadlines or different+ // repeat windows correctly.+ redistributeBatch(perTemplateLocal, t, 'by', template => {+ if (template.type !== 'by') return 0;+ return Math.max(0, byPerTemplate?.get(template) ?? 0);+ });+ // Schedules: weight by each schedule's actual monthly contribution as+ // computed by runSchedule, so the per-row UI projection reflects the+ // schedule's real cost rather than an equal split.+ redistributeBatch(perTemplateLocal, t, 'schedule', template => {+ if (template.type !== 'schedule') return 0;+ const monthly = schedulePerTemplate?.get(template.name.trim()) ?? 0;+ return Math.max(0, monthly);+ });++ let scale = 1;//check limitif (this.limitCheck) {if (@@ -238,21 +271,51 @@ export class CategoryTemplateContext {toBudget = this.limitAmount - this.toBudgetAmount - this.fromLastMonth;this.limitMet = true;available = available + orig - toBudget;+ if (orig > 0) scale *= toBudget / orig;}}//round all budget values if needed- if (this.hideDecimal) toBudget = this.removeFraction(toBudget);+ if (this.hideDecimal) {+ // Capture the pre-round value so per-row contributions track the same+ // rounding delta as toBudget; otherwise perTemplateContribution would+ // sum to slightly more/less than the engine's actual budgeted amount.+ const preRound = toBudget;+ toBudget = this.removeFraction(toBudget);+ if (preRound !== 0) scale *= toBudget / preRound;+ }// don't overbudget when using a priority unless income categoryif (priority > 0 && available < 0 && !this.category.is_income) {this.fullAmount = (this.fullAmount || 0) + toBudget;- toBudget = Math.max(0, toBudget + available);+ const adjusted = Math.max(0, toBudget + available);+ if (toBudget > 0) scale *= adjusted / toBudget;+ toBudget = adjusted;this.toBudgetAmount += toBudget;} else {this.fullAmount = (this.fullAmount || 0) + toBudget;this.toBudgetAmount += toBudget;}++ // Distribute the priority's final budget across its templates so per-row+ // projections reflect any clamping that occurred above. The limit branch+ // can produce a negative scale when the carried-over balance already+ // exceeds the cap; floor at 0 here so per-row UI projections never go+ // negative (engine totals are unaffected). Give the last entry the+ // residual so the per-row sum equals toBudget exactly even when scale+ // produces fractional cents.+ const perRowScale = Math.max(0, scale);+ const items = Array.from(perTemplateLocal);+ let remaining = Math.max(0, toBudget);+ items.forEach(([template, value], i) => {+ const isLast = i === items.length - 1;+ const share = isLast+ ? remaining+ : Math.max(0, Math.min(remaining, Math.round(value * perRowScale)));+ const existing = this.perTemplateContribution.get(template) ?? 0;+ this.perTemplateContribution.set(template, existing + share);+ remaining -= share;+ });return this.category.is_income ? -toBudget : toBudget;}@@ -282,6 +345,21 @@ export class CategoryTemplateContext {}}+ if (toBudget > 0 && this.remainderWeight > 0) {+ let remaining = toBudget;+ for (let i = 0; i < this.remainder.length; i++) {+ const template = this.remainder[i];+ const isLast = i === this.remainder.length - 1;+ const share = isLast+ ? remaining+ : Math.round(toBudget * (template.weight / this.remainderWeight));+ const allocated = Math.max(0, Math.min(share, remaining));+ const existing = this.perTemplateContribution.get(template) ?? 0;+ this.perTemplateContribution.set(template, existing + allocated);+ remaining -= allocated;+ }+ }+this.toBudgetAmount += toBudget;return toBudget;}@@ -292,6 +370,7 @@ export class CategoryTemplateContext {budgeted: this.toBudgetAmount,goal: this.goalAmount,longGoal: this.isLongGoal,+ perTemplateContribution: this.perTemplateContribution,};}@@ -306,6 +385,7 @@ export class CategoryTemplateContext {readonly hideDecimal: boolean = false;private remainderWeight: number = 0;private toBudgetAmount: number = 0; // amount that will be budgeted by the templates+ private perTemplateContribution = new Map<Template, number>();private fullAmount: number | null = null; // the full requested amount, start null for remainder only catsprivate isLongGoal: boolean | null = null; //defaulting the goals to null so templates can be unsetprivate goalAmount: number | null = null;@@ -429,21 +509,31 @@ export class CategoryTemplateContext {static async checkPercentage(templates: Template[]) {const pt = templates.filter(t => t.type === 'percentage');if (pt.length === 0) return;- const reqCategories = pt.map(t => t.category.toLowerCase());const availCategories = await db.getCategories();- const availNames = availCategories- .filter(c => c.is_income)- .map(c => c.name.toLocaleLowerCase());-- reqCategories.forEach(n => {- if (n === 'available funds' || n === 'all income') {- //skip the name check since these are special- } else if (!availNames.includes(n)) {- throw new Error(- `Category \x22${n}\x22 is not found in available income categories`,- );+ const incomeCategories = availCategories.filter(c => c.is_income);+ const availNames = new Set(+ incomeCategories.map(c => c.name.toLocaleLowerCase()),+ );+ const availIds = new Set(incomeCategories.map(c => c.id));++ const specialSources = new Set(['all income', 'available funds']);++ pt.forEach(t => {+ const raw = t.category;+ const lowered = raw.toLocaleLowerCase();+ // Accept either an income category name (text templates) or an income+ // category id (UI-managed templates from CategoryAutocomplete).+ if (+ specialSources.has(lowered) ||+ availNames.has(lowered) ||+ availIds.has(raw)+ ) {+ return;}+ throw new Error(+ `Category \x22${raw}\x22 is not found in available income categories`,+ );});}@@ -591,7 +681,9 @@ export class CategoryTemplateContext {const period = template.period.period;const numPeriods = template.period.amount;let date =- template.starting ?? monthUtils.firstDayOfMonth(templateContext.month);+ template.starting && template.starting.length > 0+ ? template.starting+ : monthUtils.firstDayOfMonth(templateContext.month);let dateShiftFunction;switch (period) {@@ -708,7 +800,7 @@ export class CategoryTemplateContext {templateContext: CategoryTemplateContext,): Promise<number> {const percent = template.percent;- const cat = template.category.toLowerCase();+ const cat = template.category.toLocaleLowerCase();const prev = template.previous;let sheetName;let monthlyIncome;@@ -726,8 +818,13 @@ export class CategoryTemplateContext {} else if (cat === 'available funds') {monthlyIncome = availableFunds;} else {+ // Text templates address income categories by name (e.g. `#template+ // 10% of Salary`); the UI's CategoryAutocomplete stores the category+ // id. Accept either form.const incomeCat = (await db.getCategories()).find(- c => c.is_income && c.name.toLowerCase() === cat,+ c =>+ c.is_income &&+ (c.id === template.category || c.name.toLocaleLowerCase() === cat),);if (!incomeCat) {throw new Error(@@ -784,7 +881,10 @@ export class CategoryTemplateContext {return Math.round(average);}- static runBy(templateContext: CategoryTemplateContext): number {+ static runBy(templateContext: CategoryTemplateContext): {+ toBudget: number;+ perTemplateNeed: Map<ByTemplate, number>;+ } {const byTemplates: ByTemplate[] = templateContext.templates.filter(t => t.type === 'by',);@@ -822,6 +922,7 @@ export class CategoryTemplateContext {// calculate needed funds per templateconst shortNumMonths = workingShortNumMonths || 0;+ const perTemplateNeed = new Map<ByTemplate, number>();for (let i = 0; i < byTemplates.length; i++) {const template = byTemplates[i];const numMonths = savedInfo[i].numMonths;@@ -853,10 +954,68 @@ export class CategoryTemplateContext {templateContext.currency.decimalPlaces,);}+ perTemplateNeed.set(template, amount);totalNeeded += amount;}- return Math.round(+ const toBudget = Math.round((totalNeeded - templateContext.fromLastMonth) / (shortNumMonths + 1),);+ return { toBudget, perTemplateNeed };+ }+}++// `runBy` and `runSchedule` are batched: they compute a single budget number+// for all sibling templates of the same type at a given priority, and the+// caller loop credits that total to whichever template was iterated first.+// Split the batch total across all siblings using `weightOf` so the+// per-template projection map reflects each template's share. The total+// allocated is preserved (last sibling absorbs any rounding remainder).+function redistributeBatch<T extends Template>(+ perTemplateLocal: Map<Template, number>,+ templates: Template[],+ type: T['type'],+ weightOf: (template: T) => number,+) {+ const siblings = templates.filter(+ (template): template is T => template.type === type,+ );+ if (siblings.length < 2) return;++ let total = 0;+ for (const sibling of siblings) {+ total += perTemplateLocal.get(sibling) ?? 0;+ perTemplateLocal.set(sibling, 0);}+ if (total === 0) return;++ const totalWeight = siblings.reduce((sum, s) => sum + weightOf(s), 0);+ if (totalWeight <= 0) {+ // Fall back to an equal split if no weights are usable.+ let remaining = total;+ siblings.forEach((sibling, i) => {+ const isLast = i === siblings.length - 1;+ const share = isLast ? remaining : Math.round(total / siblings.length);+ const allocated = Math.max(0, Math.min(share, remaining));+ perTemplateLocal.set(+ sibling,+ (perTemplateLocal.get(sibling) ?? 0) + allocated,+ );+ remaining -= allocated;+ });+ return;+ }++ let remaining = total;+ siblings.forEach((sibling, i) => {+ const isLast = i === siblings.length - 1;+ const share = isLast+ ? remaining+ : Math.round((total * weightOf(sibling)) / totalWeight);+ const allocated = Math.max(0, Math.min(share, remaining));+ perTemplateLocal.set(+ sibling,+ (perTemplateLocal.get(sibling) ?? 0) + allocated,+ );+ remaining -= allocated;+ });}diff --git a/packages/loot-core/src/server/budget/goal-template.test.ts b/packages/loot-core/src/server/budget/goal-template.test.tsindex ebbae38665..49cb5281d1 100644--- a/packages/loot-core/src/server/budget/goal-template.test.ts+++ b/packages/loot-core/src/server/budget/goal-template.test.ts@@ -7,7 +7,11 @@ import type { CategoryEntity } from '#types/models';import type { Template } from '#types/models/templates';import * as actions from './actions';-import { applyMultipleCategoryTemplates, applyTemplate } from './goal-template';+import {+ applyMultipleCategoryTemplates,+ applyTemplate,+ dryRunCategoryTemplate,+} from './goal-template';import * as statements from './statements';vi.mock('./actions', () => ({@@ -40,6 +44,13 @@ vi.mock('./template-notes', () => ({storeNoteTemplates: vi.fn(),}));+const category: CategoryEntity = {+ id: 'cat-1',+ name: 'Groceries',+ group: 'g1',+ is_income: false,+};+function setupSheetMock(values: Record<string, number>) {vi.mocked(actions.getSheetValue).mockImplementation(async (_sheet: string, key: string) => values[key] ?? 0,@@ -47,6 +58,26 @@ function setupSheetMock(values: Record<string, number>) {vi.mocked(actions.getSheetBoolean).mockResolvedValue(false);vi.mocked(actions.isTrackingBudget).mockReturnValue(false);}++function setupAqlForCategoryLookup(cat: CategoryEntity) {+ vi.mocked(aql.aqlQuery).mockImplementation(async (query: unknown) => {+ const queryStr = JSON.stringify(query);+ if (queryStr.includes('hideFraction')) {+ return { data: [{ value: 'false' }], dependencies: [] };+ }+ if (queryStr.includes('defaultCurrencyCode')) {+ return { data: [{ value: 'USD' }], dependencies: [] };+ }+ if (queryStr.includes('category_groups')) {+ return {+ data: [{ id: cat.group, hidden: false, categories: [cat] }],+ dependencies: [],+ };+ }+ return { data: [], dependencies: [] };+ });+}+function setupAqlForWideScope(savedTemplatesByCategory: Array<{category: CategoryEntity;@@ -80,6 +111,206 @@ function setupAqlForWideScope(return { data: [], dependencies: [] };});}++describe('dryRunCategoryTemplate', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(statements.getActiveSchedules).mockResolvedValue(+ [] as Awaited<ReturnType<typeof statements.getActiveSchedules>>,+ );+ vi.mocked(db.getCategories).mockResolvedValue([]);+ });++ it('budgets a single periodic template through the engine end-to-end', async () => {+ setupSheetMock({ 'to-budget': 100000 });+ setupAqlForCategoryLookup(category);++ const templates: Template[] = [+ {+ type: 'periodic',+ amount: 100,+ period: { period: 'month', amount: 1 },+ starting: '2024-01-01',+ directive: 'template',+ priority: 1,+ },+ ];+ const result = await dryRunCategoryTemplate({+ month: '2024-01',+ categoryId: category.id,+ templates,+ });+ expect(result.budgeted).toBe(10000);+ expect(result.perTemplate).toEqual([10000]);+ });++ it('clamps a periodic + percentage stack at the balance cap', async () => {+ setupSheetMock({ 'to-budget': 1_000_000, 'total-income': 100000 });+ setupAqlForCategoryLookup(category);++ const templates: Template[] = [+ {+ type: 'periodic',+ amount: 100,+ period: { period: 'month', amount: 1 },+ starting: '2024-01-01',+ directive: 'template',+ priority: 1,+ },+ {+ type: 'percentage',+ percent: 50,+ previous: false,+ category: 'all income',+ directive: 'template',+ priority: 1,+ },+ {+ type: 'limit',+ amount: 200,+ hold: false,+ period: 'monthly',+ directive: 'template',+ priority: null,+ },+ ];+ const result = await dryRunCategoryTemplate({+ month: '2024-01',+ categoryId: category.id,+ templates,+ });+ // $100 + 50% of $1000 = $600 demanded, capped at $200.+ expect(result.budgeted).toBe(20000);+ expect(result.perTemplate.reduce((a, b) => a + b, 0)).toBe(20000);+ expect(result.perTemplate[2]).toBe(0); // cap row contributes nothing+ });++ it('returns zeros when the category lookup yields nothing', async () => {+ setupSheetMock({});+ vi.mocked(aql.aqlQuery).mockImplementation(async (query: unknown) => {+ const queryStr = JSON.stringify(query);+ if (queryStr.includes('hideFraction')) {+ return { data: [{ value: 'false' }], dependencies: [] };+ }+ if (queryStr.includes('defaultCurrencyCode')) {+ return { data: [{ value: 'USD' }], dependencies: [] };+ }+ return { data: [], dependencies: [] };+ });++ const templates: Template[] = [+ {+ type: 'periodic',+ amount: 100,+ period: { period: 'month', amount: 1 },+ starting: '2024-01-01',+ directive: 'template',+ priority: 1,+ },+ ];+ const result = await dryRunCategoryTemplate({+ month: '2024-01',+ categoryId: 'missing',+ templates,+ });+ expect(result).toEqual({ budgeted: 0, perTemplate: [0] });+ });++ it('competes with sibling remainder templates under wide scope', async () => {+ // Remainder triggers wide scope: the engine must see the sibling so+ // weights divide the leftover proportionally instead of giving it all+ // to the target.+ const sibling: CategoryEntity = {+ id: 'cat-sibling',+ name: 'Other',+ group: 'g1',+ is_income: false,+ };+ setupSheetMock({ 'to-budget': 20000 });+ setupAqlForWideScope(+ [+ {+ category: sibling,+ templates: [+ {+ type: 'remainder',+ weight: 1,+ directive: 'template',+ priority: null,+ },+ ],+ },+ ],+ [category, sibling],+ );++ const templates: Template[] = [+ {+ type: 'remainder',+ weight: 3,+ directive: 'template',+ priority: null,+ },+ ];+ const result = await dryRunCategoryTemplate({+ month: '2024-01',+ categoryId: category.id,+ templates,+ });+ expect(result.budgeted).toBe(15000);+ expect(result.perTemplate).toEqual([15000]);+ });++ it('reads availBudget consumed by siblings for percentage of available funds', async () => {+ // Sibling at priority 1 spends $50 of $200 first, leaving $150. The+ // target's 50%-of-available-funds at priority 2 should then resolve to+ // $75, not the $100 a narrow-scope run would produce.+ const sibling: CategoryEntity = {+ id: 'cat-sibling',+ name: 'Other',+ group: 'g1',+ is_income: false,+ };+ setupSheetMock({ 'to-budget': 20000 });+ setupAqlForWideScope(+ [+ {+ category: sibling,+ templates: [+ {+ type: 'periodic',+ amount: 50,+ period: { period: 'month', amount: 1 },+ starting: '2024-01-01',+ directive: 'template',+ priority: 1,+ },+ ],+ },+ ],+ [sibling, category],+ );++ const templates: Template[] = [+ {+ type: 'percentage',+ percent: 50,+ previous: false,+ category: 'available funds',+ directive: 'template',+ priority: 2,+ },+ ];+ const result = await dryRunCategoryTemplate({+ month: '2024-01',+ categoryId: category.id,+ templates,+ });+ expect(result.budgeted).toBe(7500);+ expect(result.perTemplate).toEqual([7500]);+ });+});+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 0321573d33..9839e4cacd 100644--- a/packages/loot-core/src/server/budget/goal-template.ts+++ b/packages/loot-core/src/server/budget/goal-template.ts@@ -52,7 +52,7 @@ export async function storeTemplates({}): Promise<void> {await batchMessages(async () => {for (const { id, templates } of categoriesWithTemplates) {- const goalDefs = JSON.stringify(templates);+ const goalDefs = templates.length > 0 ? JSON.stringify(templates) : null;await db.updateWithSchema('categories', {id,@@ -153,6 +153,7 @@ async function getTemplates(const categoryTemplates: Record<CategoryEntity['id'], Template[]> = {};for (const categoryWithGoalDef of categoriesWithGoalDef.filter(filter)) {+ if (!categoryWithGoalDef.goal_def) continue;categoryTemplates[categoryWithGoalDef.id] = JSON.parse(categoryWithGoalDef.goal_def,);@@ -202,12 +203,18 @@ async function setGoals(month: string, templateGoal: TemplateGoal[]) {});}-async function processTemplate(+type ComputedTemplates = {+ contexts: CategoryTemplateContext[];+ errors: string[];+ orphanGoals: TemplateGoal[];+};++async function computeTemplates(month: string,force: boolean,categoryTemplates: Record<CategoryEntity['id'], Template[]>,categories: CategoryEntity[] = [],-): Promise<Notification> {+): Promise<ComputedTemplates> {// setup categoriesconst isTracking = isTrackingBudget();if (!categories.length) {@@ -224,8 +231,7 @@ async function processTemplate();const prioritiesSet = new Set<number>();const errors: string[] = [];- const budgetList: TemplateBudget[] = [];- const goalList: TemplateGoal[] = [];+ const orphanGoals: TemplateGoal[] = [];for (const category of categories) {const { id } = category;const sheetName = monthUtils.sheetForMonth(month);@@ -255,7 +261,7 @@ async function processTemplate(// do a reset of the goals that are orphaned} else if (existingGoal !== null && !templates) {- goalList.push({+ orphanGoals.push({category: id,goal: null,longGoal: null,@@ -263,22 +269,8 @@ async function processTemplate(}}- //break early if nothing to do, or there are errors- if (templateContexts.length === 0 && errors.length === 0) {- if (goalList.length > 0) {- void setGoals(month, goalList);- }- return {- type: 'message',- message: 'Everything is up to date',- };- }if (errors.length > 0) {- return {- sticky: true,- message: 'There were errors interpreting some templates:',- pre: errors.join(`\n\n`),- };+ return { contexts: templateContexts, errors, orphanGoals };}const priorities = new Int32Array([...prioritiesSet]).sort((a, b) => a - b);@@ -295,11 +287,44 @@ async function processTemplate(}}- // run remainder- availBudget = distributeRemainder(templateContexts, availBudget);+ distributeRemainder(templateContexts, availBudget);++ return { contexts: templateContexts, errors, orphanGoals };+}++async function processTemplate(+ month: string,+ force: boolean,+ categoryTemplates: Record<CategoryEntity['id'], Template[]>,+ categories: CategoryEntity[] = [],+): Promise<Notification> {+ const { contexts, errors, orphanGoals } = await computeTemplates(+ month,+ force,+ categoryTemplates,+ categories,+ );++ if (contexts.length === 0 && errors.length === 0) {+ if (orphanGoals.length > 0) {+ await setGoals(month, orphanGoals);+ }+ return {+ type: 'message',+ message: 'Everything is up to date',+ };+ }+ if (errors.length > 0) {+ return {+ sticky: true,+ message: 'There were errors interpreting some templates:',+ pre: errors.join(`\n\n`),+ };+ }- // finish- templateContexts.forEach(context => {+ const budgetList: TemplateBudget[] = [];+ const goalList: TemplateGoal[] = [...orphanGoals];+ contexts.forEach(context => {const values = context.getValues();budgetList.push({category: context.category.id,@@ -316,6 +341,43 @@ async function processTemplate(return {type: 'message',- message: `Successfully applied templates to ${templateContexts.length} categories`,+ message: `Successfully applied templates to ${contexts.length} categories`,+ };+}++export type DryRunCategoryResult = {+ budgeted: number;+ perTemplate: number[];+};++export async function dryRunCategoryTemplate({+ month,+ categoryId,+ templates,+}: {+ month: string;+ categoryId: CategoryEntity['id'];+ templates: Template[];+}): Promise<DryRunCategoryResult> {+ // Always run the full set of saved category templates and override the+ // target's saved templates with the in-flight ones. Sibling categories+ // consume from To Budget at each priority; running them too keeps the+ // projection in sync with what an actual apply would produce — including+ // the constrained-budget case where prior categories at the same priority+ // exhaust the pool and clamp this category's amount.+ const allCategoryTemplates = await getTemplates();+ allCategoryTemplates[categoryId] = templates;+ const { contexts } = await computeTemplates(+ month,+ true,+ allCategoryTemplates,+ [],+ );+ const ctx = contexts.find(c => c.category.id === categoryId);+ if (!ctx) return { budgeted: 0, perTemplate: templates.map(() => 0) };+ const values = ctx.getValues();+ return {+ budgeted: values.budgeted,+ perTemplate: templates.map(t => values.perTemplateContribution.get(t) ?? 0),};}diff --git a/packages/loot-core/src/server/budget/schedule-template.test.ts b/packages/loot-core/src/server/budget/schedule-template.test.tsindex 19b830ef22..520b10d6ec 100644--- a/packages/loot-core/src/server/budget/schedule-template.test.ts+++ b/packages/loot-core/src/server/budget/schedule-template.test.ts@@ -169,6 +169,82 @@ describe('runSchedule', () => {expect(result.remainder).toBe(0);});+ it('returns a per-template monthly attribution map keyed by trimmed template name', async () => {+ const template_lines = [+ {+ type: 'schedule',+ name: ' Test Schedule ',+ directive: 'template',+ priority: 0,+ } as const,+ ];+ mockSingleSchedule({+ start: '2024-08-01',+ amount: -10000,+ frequency: 'monthly',+ });++ const result = await runSchedule(+ template_lines,+ '2024-08-01',+ 0,+ 0,+ 0,+ 0,+ [],+ defaultCategory,+ defaultCurrency,+ );++ expect(result.perScheduleMonthly.get('Test Schedule')).toBe(10000);+ expect(result.to_budget).toBe(10000);+ });++ it('handles a pay-month-of monthly schedule alongside a yearly sinking schedule', async () => {+ const template_lines = [+ {+ type: 'schedule',+ name: 'Internet',+ directive: 'template',+ priority: 0,+ } as const,+ {+ type: 'schedule',+ name: 'Insurance',+ directive: 'template',+ priority: 0,+ } as const,+ ];+ mockSchedulesByName({+ Internet: {+ spec: { start: '2024-01-15', amount: -10000, frequency: 'monthly' },+ },+ Insurance: {+ spec: { start: '2024-12-15', amount: -60000, frequency: 'yearly' },+ },+ });++ const result = await runSchedule(+ template_lines,+ '2024-01-01',+ 0,+ 0,+ 0,+ 0,+ [],+ defaultCategory,+ defaultCurrency,+ );++ expect(result.errors).toHaveLength(0);+ const internet = result.perScheduleMonthly.get('Internet') ?? 0;+ const insurance = result.perScheduleMonthly.get('Insurance') ?? 0;+ expect(internet).toBe(10000); // pay-month-of: full target+ expect(insurance).toBeGreaterThan(0);+ expect(insurance).toBeLessThan(internet);+ expect(internet + insurance).toBeCloseTo(result.to_budget, -1);+ });+it('budgets nothing in advance for a yearly schedule with `full: true`', async () => {const template_lines = [{diff --git a/packages/loot-core/src/server/budget/schedule-template.ts b/packages/loot-core/src/server/budget/schedule-template.tsindex c2d70dd0f3..c5a1501989 100644--- a/packages/loot-core/src/server/budget/schedule-template.ts+++ b/packages/loot-core/src/server/budget/schedule-template.ts@@ -218,13 +218,16 @@ function getPayMonthOfTotal(t: ScheduleTemplateTarget[]) {return total;}-async function getSinkingContributionTotal(+function getSinkingContributionBreakdown(t: ScheduleTemplateTarget[],remainder: number,last_month_balance: number,) {- //return the contribution amount if there is a balance carried in the category+ // Mirrors getSinkingContributionTotal but also records each schedule's+ // contribution so the caller can attribute the batch back to individual+ // templates. Total math is unchanged.let total = 0;+ const perSchedule = new Map<string, number>();for (const [index, schedule] of t.entries()) {remainder =index === 0@@ -238,58 +241,55 @@ async function getSinkingContributionTotal(tg = 0;remainder = Math.abs(remainder);}- total += tg / (schedule.num_months + 1);+ const contribution = tg / (schedule.num_months + 1);+ total += contribution;+ perSchedule.set(+ schedule.name.trim(),+ (perSchedule.get(schedule.name.trim()) ?? 0) + contribution,+ );+ }+ return { total, perSchedule };+}++function getMonthlyBaseContribution(schedule: ScheduleTemplateTarget) {+ let prevDate;+ let intervalMonths;+ switch (schedule.target_frequency) {+ case 'yearly':+ return schedule.target / schedule.target_interval / 12;+ case 'monthly':+ return schedule.target / schedule.target_interval;+ case 'weekly':+ prevDate = monthUtils.subWeeks(+ schedule.next_date_string,+ schedule.target_interval,+ );+ intervalMonths = monthUtils.differenceInCalendarMonths(+ schedule.next_date_string,+ prevDate,+ );+ if (intervalMonths === 0) intervalMonths = 1;+ return schedule.target / intervalMonths;+ case 'daily':+ prevDate = monthUtils.subDays(+ schedule.next_date_string,+ schedule.target_interval,+ );+ intervalMonths = monthUtils.differenceInCalendarMonths(+ schedule.next_date_string,+ prevDate,+ );+ if (intervalMonths === 0) intervalMonths = 1;+ return schedule.target / intervalMonths;+ default:+ // default to same math as monthly for now for non-reoccuring+ return schedule.target / schedule.target_interval;}- return total;}function getSinkingBaseContributionTotal(t: ScheduleTemplateTarget[]) {- //return only the base contribution of each schedulelet total = 0;- for (const schedule of t) {- let monthlyAmount = 0;- let prevDate;- let intervalMonths;- switch (schedule.target_frequency) {- case 'yearly':- monthlyAmount = schedule.target / schedule.target_interval / 12;- break;- case 'monthly':- monthlyAmount = schedule.target / schedule.target_interval;- break;- case 'weekly':- prevDate = monthUtils.subWeeks(- schedule.next_date_string,- schedule.target_interval,- );- intervalMonths = monthUtils.differenceInCalendarMonths(- schedule.next_date_string,- prevDate,- );- // shouldn't be possible, but better check- if (intervalMonths === 0) intervalMonths = 1;- monthlyAmount = schedule.target / intervalMonths;- break;- case 'daily':- prevDate = monthUtils.subDays(- schedule.next_date_string,- schedule.target_interval,- );- intervalMonths = monthUtils.differenceInCalendarMonths(- schedule.next_date_string,- prevDate,- );- // shouldn't be possible, but better check- if (intervalMonths === 0) intervalMonths = 1;- monthlyAmount = schedule.target / intervalMonths;- break;- default:- // default to same math as monthly for now for non-reoccuring- monthlyAmount = schedule.target / schedule.target_interval;- break;- }- total += monthlyAmount;- }+ for (const schedule of t) total += getMonthlyBaseContribution(schedule);return total;}@@ -353,6 +353,17 @@ export async function runSchedule(// haven't been paid yet, or if we can use the leftover balance for this month// First option: check if the previous month doesn't have its monthly schedules paid yet// Second option: check if the previous month needed less than this month and hasn't paid yet+ // Accumulate per-schedule contributions (keyed by trimmed template name) so+ // callers can attribute the batched to_budget back to individual schedule+ // templates for UI projections.+ const perScheduleMonthly = new Map<string, number>();+ const addContribution = (name: string, amount: number) => {+ perScheduleMonthly.set(+ name.trim(),+ (perScheduleMonthly.get(name.trim()) ?? 0) + amount,+ );+ };+if (balance >= totalSinking + totalPayMonthOf ||(lastMonthGoal < totalSinking + totalPayMonthOf &&@@ -361,12 +372,13 @@ export async function runSchedule(numSubMonthly > 0)) {to_budget += Math.round(totalPayMonthOf + totalSinkingBaseContribution);+ for (const c of t_payMonthOf) addContribution(c.name, c.target);+ for (const c of t_sinking) {+ addContribution(c.name, getMonthlyBaseContribution(c));+ }} else {- const totalSinkingContribution = await getSinkingContributionTotal(- t_sinking,- remainder,- last_month_balance,- );+ const { total: totalSinkingContribution, perSchedule: sinkingPerSchedule } =+ getSinkingContributionBreakdown(t_sinking, remainder, last_month_balance);if (t_sinking.length === 0) {to_budget +=Math.round(totalPayMonthOf + totalSinkingContribution) -@@ -374,6 +386,10 @@ export async function runSchedule(} else {to_budget += Math.round(totalPayMonthOf + totalSinkingContribution);}+ for (const c of t_payMonthOf) addContribution(c.name, c.target);+ for (const [name, amount] of sinkingPerSchedule) {+ addContribution(name, amount);+ }}- return { to_budget, errors, remainder };+ return { to_budget, errors, remainder, perScheduleMonthly };}diff --git a/packages/loot-core/src/server/budget/template-notes.test.ts b/packages/loot-core/src/server/budget/template-notes.test.tsindex 02841a08fd..4b66e4c1dc 100644--- a/packages/loot-core/src/server/budget/template-notes.test.ts+++ b/packages/loot-core/src/server/budget/template-notes.test.ts@@ -326,6 +326,7 @@ describe('unparse/parse round-trip', () => {'#template 200 repeat every 2 months starting 2025-06-01','#template 300 repeat every week starting 2025-01-07','#template 400 repeat every year starting 2025-01-01 up to 50',+ '#template 100 repeat every 1 months starting 2026-04-01',// by / spend'#template 500 by 2025-12','#template 600 by 2025-11 repeat every month',diff --git a/packages/loot-core/src/server/budget/template-notes.ts b/packages/loot-core/src/server/budget/template-notes.tsindex 216234d0af..65ddc0644d 100644--- a/packages/loot-core/src/server/budget/template-notes.ts+++ b/packages/loot-core/src/server/budget/template-notes.ts@@ -143,7 +143,10 @@ async function getCategoriesWithTemplates(): Promise<}function prefixFromPriority(priority: number | null): string {- return priority === null ? TEMPLATE_PREFIX : `${TEMPLATE_PREFIX}-${priority}`;+ // Priority 0 is the parser's "unset" default and serializes without a suffix.+ return priority === null || priority === 0+ ? TEMPLATE_PREFIX+ : `${TEMPLATE_PREFIX}-${priority}`;}export async function unparse(templates: Template[]): Promise<string> {@@ -297,12 +300,7 @@ function periodToString(p: {period: 'day' | 'week' | 'month' | 'year';amount: number;}): string {- const { period, amount } = p;- if (amount === 1) {- return period; // singular- }- // pluralize simple- return `${amount} ${period}s`;+ return `${p.amount} ${p.period}s`;}function repeatToString(annual?: boolean, repeat?: number): string | null {diff --git a/packages/loot-core/src/shared/months.ts b/packages/loot-core/src/shared/months.tsindex 71f781aa5e..c4eccfae30 100644--- a/packages/loot-core/src/shared/months.ts+++ b/packages/loot-core/src/shared/months.ts@@ -91,6 +91,13 @@ export function monthFromDate(date: DateLike): string {return d.format(_parse(date), 'yyyy-MM');}+export function isValidYearMonth(value: string): boolean {+ const match = /^(\d{4})-(\d{2})$/.exec(value);+ if (!match) return false;+ const month = Number(match[2]);+ return month >= 1 && month <= 12;+}+export function weekFromDate(date: DateLike,firstDayOfWeekIdx: SyncedPrefs['firstDayOfWeekIdx'],diff --git a/upcoming-release-notes/7597.md b/upcoming-release-notes/7597.mdnew file mode 100644index 0000000000..7159da6ffa--- /dev/null+++ b/upcoming-release-notes/7597.md@@ -0,0 +1,6 @@+---+category: Features+authors: [matt-fidd]+---++Visual overhaul of the experimental budget automation UI