A local-first personal finance app
automation UI: add increase/decrease functionality (#7881)
Matt Fiddamana587ed3ebc17
diff --git a/packages/desktop-client/src/components/budget/goals/automationMessages.tsx b/packages/desktop-client/src/components/budget/goals/automationMessages.tsxindex aac32eab0c..e450bc0295 100644--- a/packages/desktop-client/src/components/budget/goals/automationMessages.tsx+++ b/packages/desktop-client/src/components/budget/goals/automationMessages.tsx@@ -35,6 +35,8 @@ export function AutomationErrorTitle({return <Trans>Early spending starts after target</Trans>;case 'percentage-source-not-found':return <Trans>Source category not recognised</Trans>;+ case 'adjustment-out-of-range':+ return <Trans>Adjustment out of range</Trans>;default:error satisfies never;return null;@@ -78,6 +80,8 @@ export function AutomationErrorShort({return <Trans>Early spending must start before the target</Trans>;case 'percentage-source-not-found':return <Trans>Pick a valid income category</Trans>;+ case 'adjustment-out-of-range':+ return <Trans>Adjustment out of range</Trans>;default:error satisfies never;return null;@@ -155,6 +159,13 @@ export function AutomationErrorDetail({known income category.</Trans>);+ case 'adjustment-out-of-range':+ return (+ <Trans>+ A percentage decrease must be under 100% and an increase at most+ 1000%.+ </Trans>+ );default:error satisfies never;return null;diff --git a/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsx b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsxnew file mode 100644index 0000000000..9597f30950--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsx@@ -0,0 +1,160 @@+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 {+ AverageTemplate,+ ScheduleTemplate,+} 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 { useFormat } from '#hooks/useFormat';++type AdjustableTemplate = ScheduleTemplate | AverageTemplate;+type AdjustmentType = 'percent' | 'fixed';+type UnitOption = 'none' | AdjustmentType;+type Direction = 'increase' | 'decrease';++// Seeded when an adjustment is first switched on.+const DEFAULT_MAGNITUDE = 10;++type AmountAdjustmentProps = {+ template: AdjustableTemplate;+ dispatch: (action: Action) => void;+};++// Editor for the optional increase/decrease modifier on schedule and average+// templates. `adjustment` is stored as a single signed number. The unit+// dropdown turns the adjustment on and off and picks percentage vs fixed+// amount. A percentage uses an increase/decrease selector for the direction;+// a fixed amount uses AmountInput, whose own sign is the direction.+export const AmountAdjustment = ({+ template,+ dispatch,+}: AmountAdjustmentProps) => {+ const { t } = useTranslation();+ const format = useFormat();++ const enabled = template.adjustment !== undefined;+ const adjustmentType: AdjustmentType = template.adjustmentType ?? 'percent';+ const adjustment = template.adjustment ?? 0;+ const increasing = adjustment >= 0;+ const magnitude = Math.abs(adjustment);++ const [rawMagnitude, setRawMagnitude] = useState(String(magnitude));+ // Resync when a different automation row is selected (the component+ // instance is reused across rows).+ useEffect(() => {+ setRawMagnitude(String(magnitude));+ }, [magnitude]);++ const apply = (+ next: number | undefined,+ type: AdjustmentType | undefined,+ ) => {+ if (template.type === 'schedule') {+ dispatch(+ updateTemplate({+ type: 'schedule',+ adjustment: next,+ adjustmentType: type,+ }),+ );+ } else {+ dispatch(+ updateTemplate({+ type: 'average',+ adjustment: next,+ adjustmentType: type,+ }),+ );+ }+ };++ const changeUnit = (unit: UnitOption) => {+ if (unit === 'none') {+ apply(undefined, undefined);+ return;+ }+ // Keep the current size when switching units; seed an increase when+ // switching on from off.+ apply(template.adjustment ?? DEFAULT_MAGNITUDE, unit);+ };++ const changeDirection = (direction: Direction) => {+ apply(direction === 'decrease' ? -magnitude : magnitude, 'percent');+ };++ const commitMagnitude = () => {+ const parsed = Number(rawMagnitude);+ const size = Number.isFinite(parsed) ? Math.max(0, parsed) : 0;+ setRawMagnitude(String(size));+ apply(increasing ? size : -size, 'percent');+ };++ return (+ <SpaceBetween gap={50} style={{ marginTop: 10 }}>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Adjustment')} htmlFor="adjustment-unit-field" />+ <SpaceBetween align="center" gap={12}>+ <Select+ id="adjustment-unit-field"+ value={enabled ? adjustmentType : 'none'}+ onChange={changeUnit}+ options={[+ ['none', t('No adjustment')],+ ['fixed', t('Fixed amount')],+ ['percent', t('Percentage')],+ ]}+ style={{ width: 160 }}+ />+ {enabled &&+ (adjustmentType === 'fixed' ? (+ <AmountInput+ id="adjustment-amount-field"+ zeroSign="+"+ value={amountToInteger(+ adjustment,+ format.currency.decimalPlaces,+ )}+ onUpdate={next =>+ apply(+ integerToAmount(next, format.currency.decimalPlaces),+ 'fixed',+ )+ }+ style={{ flex: 'none', width: 140 }}+ />+ ) : (+ <>+ <Select+ id="adjustment-direction-field"+ value={increasing ? 'increase' : 'decrease'}+ onChange={changeDirection}+ options={[+ ['increase', t('Increase')],+ ['decrease', t('Decrease')],+ ]}+ style={{ width: 150 }}+ />+ <Input+ id="adjustment-amount-field"+ inputMode="decimal"+ style={{ width: 120 }}+ value={rawMagnitude}+ onChangeValue={setRawMagnitude}+ onBlur={commitMagnitude}+ />+ </>+ ))}+ </SpaceBetween>+ </FormField>+ </SpaceBetween>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsx b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsxnew file mode 100644index 0000000000..dcb94a41d7--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsx@@ -0,0 +1,46 @@+import { Trans } from 'react-i18next';++import { amountToInteger } from '@actual-app/core/shared/util';+import type {+ AverageTemplate,+ ScheduleTemplate,+} from '@actual-app/core/types/models/templates';++import { useFormat } from '#hooks/useFormat';++type AmountAdjustmentSummaryProps = {+ template: ScheduleTemplate | AverageTemplate;+};++// Trailing clause for a template's increase or decrease adjustment, e.g.+// "(increased by 10%)". Renders nothing when no adjustment is set.+export function AmountAdjustmentSummary({+ template,+}: AmountAdjustmentSummaryProps) {+ const format = useFormat();++ if (template.adjustment === undefined) {+ return null;+ }++ const increase = template.adjustment >= 0;+ const magnitude = Math.abs(template.adjustment);++ if (template.adjustmentType === 'fixed') {+ const amount = format(+ amountToInteger(magnitude, format.currency.decimalPlaces),+ 'financial',+ );+ return increase ? (+ <Trans>(increased by {{ amount }})</Trans>+ ) : (+ <Trans>(decreased by {{ amount }})</Trans>+ );+ }++ return increase ? (+ <Trans>(increased by {{ percent: magnitude }}%)</Trans>+ ) : (+ <Trans>(decreased by {{ percent: magnitude }}%)</Trans>+ );+}diff --git a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsxindex 8ac8f993d6..16be09b83e 100644--- a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx@@ -9,6 +9,7 @@ import type {import { updateTemplate } from '#components/budget/goals/actions';import type { Action } from '#components/budget/goals/actions';+import { AmountAdjustment } from '#components/budget/goals/editor/AmountAdjustment';import { FormField, FormLabel } from '#components/forms';import { GenericInput } from '#components/util/GenericInput';@@ -24,42 +25,49 @@ export const HistoricalAutomation = ({const { t } = useTranslation();return (- <SpaceBetween gap={50} style={{ marginTop: 10 }}>- <FormField style={{ flex: 1 }}>- <FormLabel title={t('Mode')} htmlFor="mode-field" />- <Select- id="mode-field"- key="mode-picker"- options={[- ['copy', t('Copy a previous month')],- ['average', t('Average of previous months')],- ]}- value={template.type}- onChange={type => dispatch(updateTemplate({ type }))}- />- </FormField>- <FormField style={{ flex: 1 }}>- <FormLabel- title={t('Number of months back')}- htmlFor="look-back-field"- />- <GenericInput- key="look-back-input"- type="number"- value={- template.type === 'average' ? template.numMonths : template.lookBack- }- onChange={value =>- dispatch(- updateTemplate(- template.type === 'average'- ? { type: 'average', numMonths: value }- : { type: 'copy', lookBack: value },- ),- )- }- />- </FormField>- </SpaceBetween>+ <>+ <SpaceBetween gap={50} style={{ marginTop: 10 }}>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Mode')} htmlFor="mode-field" />+ <Select+ id="mode-field"+ key="mode-picker"+ options={[+ ['copy', t('Copy a previous month')],+ ['average', t('Average of previous months')],+ ]}+ value={template.type}+ onChange={type => dispatch(updateTemplate({ type }))}+ />+ </FormField>+ <FormField style={{ flex: 1 }}>+ <FormLabel+ title={t('Number of months back')}+ htmlFor="look-back-field"+ />+ <GenericInput+ key="look-back-input"+ type="number"+ value={+ template.type === 'average'+ ? template.numMonths+ : template.lookBack+ }+ onChange={value =>+ dispatch(+ updateTemplate(+ template.type === 'average'+ ? { type: 'average', numMonths: value }+ : { type: 'copy', lookBack: value },+ ),+ )+ }+ />+ </FormField>+ </SpaceBetween>+ {template.type === 'average' && (+ <AmountAdjustment template={template} dispatch={dispatch} />+ )}+ </>);};diff --git a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsxindex c330fcf854..5ef4f3bfc9 100644--- a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx@@ -5,6 +5,8 @@ import type {CopyTemplate,} from '@actual-app/core/types/models/templates';+import { AmountAdjustmentSummary } from './AmountAdjustmentSummary';+type HistoricalAutomationReadOnlyProps = {template: CopyTemplate | AverageTemplate;};@@ -12,13 +14,27 @@ type HistoricalAutomationReadOnlyProps = {export const HistoricalAutomationReadOnly = ({template,}: HistoricalAutomationReadOnlyProps) => {- return template.type === 'copy' ? (- <Trans count={template.lookBack}>- Budget the same amount as {{ count: template.lookBack }} months ago- </Trans>- ) : (+ if (template.type === 'copy') {+ return (+ <Trans count={template.lookBack}>+ Budget the same amount as {{ count: template.lookBack }} months ago+ </Trans>+ );+ }++ const base = (<Trans count={template.numMonths}>Budget the average of the last {{ count: template.numMonths }} months</Trans>);++ if (template.adjustment === undefined) {+ return base;+ }++ return (+ <>+ {base} <AmountAdjustmentSummary template={template} />+ </>+ );};diff --git a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsxindex ea78a3df9a..6ce7e3964f 100644--- a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx@@ -8,6 +8,7 @@ import type { ScheduleTemplate } from '@actual-app/core/types/models/templates';import { updateTemplate } from '#components/budget/goals/actions';import type { Action } from '#components/budget/goals/actions';+import { AmountAdjustment } from '#components/budget/goals/editor/AmountAdjustment';import { Link } from '#components/common/Link';import { FormField, FormLabel } from '#components/forms';@@ -33,46 +34,49 @@ export const ScheduleAutomation = ({);return selectableSchedules.length ? (- <SpaceBetween gap={50} style={{ marginTop: 10 }}>- <FormField style={{ flex: 1 }}>- <FormLabel title={t('Schedule')} htmlFor="schedule-field" />- <Select- id="schedule-field"- key="schedule-picker"- defaultLabel={t('Select a schedule')}- value={template.name}- onChange={schedule =>- dispatch(- updateTemplate({- type: 'schedule',- name: schedule,- }),- )- }- options={selectableSchedules.map(s => [s.name, s.name] as const)}- />- </FormField>- <FormField style={{ flex: 1 }}>- <FormLabel title={t('Savings mode')} htmlFor="schedule-full-field" />- <Select- id="schedule-full-field"- key="schedule-full"- options={[- ['false', t('Save up for the next occurrence')],- ['true', t('Cover each occurrence when it occurs')],- ]}- value={String(!!template.full)}- onChange={full =>- dispatch(- updateTemplate({- type: 'schedule',- full: full === 'true',- }),- )- }- />- </FormField>- </SpaceBetween>+ <>+ <SpaceBetween gap={50} style={{ marginTop: 10 }}>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Schedule')} htmlFor="schedule-field" />+ <Select+ id="schedule-field"+ key="schedule-picker"+ defaultLabel={t('Select a schedule')}+ value={template.name}+ onChange={schedule =>+ dispatch(+ updateTemplate({+ type: 'schedule',+ name: schedule,+ }),+ )+ }+ options={selectableSchedules.map(s => [s.name, s.name] as const)}+ />+ </FormField>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Savings mode')} htmlFor="schedule-full-field" />+ <Select+ id="schedule-full-field"+ key="schedule-full"+ options={[+ ['false', t('Save up for the next occurrence')],+ ['true', t('Cover each occurrence when it occurs')],+ ]}+ value={String(!!template.full)}+ onChange={full =>+ dispatch(+ updateTemplate({+ type: 'schedule',+ full: full === 'true',+ }),+ )+ }+ />+ </FormField>+ </SpaceBetween>+ <AmountAdjustment template={template} dispatch={dispatch} />+ </>) : (<Text style={{ marginTop: 10 }}><Trans>diff --git a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomationReadOnly.tsxindex 1db91a36d2..397d01dd25 100644--- a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomationReadOnly.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomationReadOnly.tsx@@ -2,6 +2,8 @@ import { Trans } from 'react-i18next';import type { ScheduleTemplate } from '@actual-app/core/types/models/templates';+import { AmountAdjustmentSummary } from './AmountAdjustmentSummary';+type ScheduleAutomationReadOnlyProps = {template: ScheduleTemplate;};@@ -13,21 +15,27 @@ export const ScheduleAutomationReadOnly = ({return <Trans>Budget for a schedule</Trans>;}- if (template.full) {- return (- <Trans>- Cover the occurrences of the schedule ‘- {{ name: template.name }}- ’ this month- </Trans>- );- }-- return (+ const base = template.full ? (+ <Trans>+ Cover the occurrences of the schedule ‘+ {{ name: template.name }}+ ’ this month+ </Trans>+ ) : (<Trans>Save up for the schedule ‘{{ name: template.name }}’</Trans>);++ if (template.adjustment === undefined) {+ return base;+ }++ return (+ <>+ {base} <AmountAdjustmentSummary template={template} />+ </>+ );};diff --git a/packages/desktop-client/src/components/budget/goals/validateAutomation.test.ts b/packages/desktop-client/src/components/budget/goals/validateAutomation.test.tsindex f8569dd04e..1f4fc70575 100644--- a/packages/desktop-client/src/components/budget/goals/validateAutomation.test.ts+++ b/packages/desktop-client/src/components/budget/goals/validateAutomation.test.ts@@ -1,7 +1,11 @@+import type { ScheduleEntity } from '@actual-app/core/types/models';import type { Template } from '@actual-app/core/types/models/templates';import { describe, expect, it } from 'vitest';-import { validatePercentageAllocation } from './validateAutomation';+import {+ validateAutomation,+ validatePercentageAllocation,+} from './validateAutomation';function percent(category: string,@@ -67,3 +71,143 @@ describe('validatePercentageAllocation', () => {).toEqual({ kind: 'percent-over-100', total: 110 });});});++function averageTemplate(+ adjustment?: number,+ adjustmentType?: 'percent' | 'fixed',+): Template {+ return {+ type: 'average',+ numMonths: 3,+ directive: 'template',+ priority: 1,+ adjustment,+ adjustmentType,+ };+}++function scheduleTemplate(+ name: string,+ adjustment?: number,+ adjustmentType?: 'percent' | 'fixed',+): Template {+ return {+ type: 'schedule',+ name,+ directive: 'template',+ priority: 1,+ adjustment,+ adjustmentType,+ };+}++function schedule(name: string): ScheduleEntity {+ return {+ id: name,+ name,+ rule: 'rule-1',+ next_date: '2026-01-01',+ completed: false,+ posts_transaction: false,+ tombstone: false,+ _payee: 'payee-1',+ _account: 'account-1',+ _amount: 0,+ _amountOp: 'is',+ _date: '2026-01-01',+ _conditions: [],+ _actions: [],+ };+}++describe('validateAutomation adjustment range', () => {+ const today = new Date('2026-01-15');++ it('accepts an average with no adjustment', () => {+ expect(+ validateAutomation(averageTemplate(), 'historical', [], [], today),+ ).toBeNull();+ });++ it('accepts a percentage adjustment within range', () => {+ expect(+ validateAutomation(+ averageTemplate(10, 'percent'),+ 'historical',+ [],+ [],+ today,+ ),+ ).toBeNull();+ // 1000% increase is the inclusive upper bound+ expect(+ validateAutomation(+ averageTemplate(1000, 'percent'),+ 'historical',+ [],+ [],+ today,+ ),+ ).toBeNull();+ });++ it('flags a percentage increase above 1000%', () => {+ expect(+ validateAutomation(+ averageTemplate(1001, 'percent'),+ 'historical',+ [],+ [],+ today,+ ),+ ).toEqual({ kind: 'adjustment-out-of-range' });+ });++ it('flags a percentage decrease of 100% or more', () => {+ expect(+ validateAutomation(+ averageTemplate(-100, 'percent'),+ 'historical',+ [],+ [],+ today,+ ),+ ).toEqual({ kind: 'adjustment-out-of-range' });+ });++ it('does not range-check fixed adjustments', () => {+ expect(+ validateAutomation(+ averageTemplate(999999, 'fixed'),+ 'historical',+ [],+ [],+ today,+ ),+ ).toBeNull();+ });++ it('flags an out-of-range adjustment on a schedule template', () => {+ expect(+ validateAutomation(+ scheduleTemplate('Rent', 2000, 'percent'),+ 'schedule',+ [],+ [schedule('Rent')],+ today,+ ),+ ).toEqual({ kind: 'adjustment-out-of-range' });+ });++ it('reports a missing schedule before checking the adjustment', () => {+ expect(+ validateAutomation(+ scheduleTemplate('Rent', 2000, 'percent'),+ 'schedule',+ [],+ [],+ today,+ ),+ ).toEqual({ kind: 'schedule-not-found', name: 'Rent' });+ });+});diff --git a/packages/desktop-client/src/components/budget/goals/validateAutomation.ts b/packages/desktop-client/src/components/budget/goals/validateAutomation.tsindex 01005b39d5..3f9009b6b8 100644--- a/packages/desktop-client/src/components/budget/goals/validateAutomation.ts+++ b/packages/desktop-client/src/components/budget/goals/validateAutomation.ts@@ -14,7 +14,19 @@ export type AutomationErrorKind =| { kind: 'by-no-month' }| { kind: 'by-target-past'; month: string }| { kind: 'spend-no-from' }- | { kind: 'spend-from-after-target' };+ | { kind: 'spend-from-after-target' }+ | { kind: 'adjustment-out-of-range' };++function isAdjustmentOutOfRange(template: Template): boolean {+ if (+ (template.type === 'schedule' || template.type === 'average') &&+ template.adjustment !== undefined &&+ template.adjustmentType === 'percent'+ ) {+ return template.adjustment <= -100 || template.adjustment > 1000;+ }+ return false;+}export type GlobalConflictKind =| { kind: 'over-income'; total: number; income: number }@@ -43,6 +55,14 @@ export function validateAutomation() {return { kind: 'schedule-not-found', name: template.name };}+ if (isAdjustmentOutOfRange(template)) {+ return { kind: 'adjustment-out-of-range' };+ }+ return null;+ case 'historical':+ if (isAdjustmentOutOfRange(template)) {+ return { kind: 'adjustment-out-of-range' };+ }return null;case 'refill':if (!allTemplates.some(t => t.type === 'limit')) {diff --git a/upcoming-release-notes/7881.md b/upcoming-release-notes/7881.mdnew file mode 100644index 0000000000..a631b9f615--- /dev/null+++ b/upcoming-release-notes/7881.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [matt-fidd]+---++Automation UI: add ability to increase/decrease historical and schedule templates