Skip to content

A local-first personal finance app

automation UI: add spend from functionality (#7823)

Matt Fiddaman4b1b68a3531c
diff --git a/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsx b/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsx
index 2d95369d7a..9c2b7bc20f 100644
--- a/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsx
+++ b/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsx
@@ -42,13 +42,13 @@ export function TemplateSentence({
case 'copy':
return <HistoricalAutomationReadOnly template={template} />;
case 'by':
+ case 'spend':
return <BySaveAutomationReadOnly template={template} />;
case 'remainder':
return <RemainderAutomationReadOnly template={template} />;
case 'goal':
return <LongTermGoalAutomationReadOnly template={template} />;
case 'simple':
- case 'spend':
case 'error': {
const type = template.type;
return (
diff --git a/packages/desktop-client/src/components/budget/goals/automationMessages.tsx b/packages/desktop-client/src/components/budget/goals/automationMessages.tsx
index e784b19123..384e653ca8 100644
--- a/packages/desktop-client/src/components/budget/goals/automationMessages.tsx
+++ b/packages/desktop-client/src/components/budget/goals/automationMessages.tsx
@@ -27,6 +27,10 @@ export function AutomationErrorTitle({
return <Trans>Target month missing</Trans>;
case 'by-target-past':
return <Trans>Target is in the past</Trans>;
+ case 'spend-no-from':
+ return <Trans>Early-spending month missing</Trans>;
+ case 'spend-from-after-target':
+ return <Trans>Early spending starts after target</Trans>;
case 'percentage-source-not-found':
return <Trans>Source category not recognised</Trans>;
default:
@@ -64,6 +68,10 @@ export function AutomationErrorShort({
{{ month: formatMonthLabel(error.month, locale) }} has already passed
</Trans>
);
+ case 'spend-no-from':
+ return <Trans>Pick an early-spending start month</Trans>;
+ case 'spend-from-after-target':
+ return <Trans>Early spending must start before the target</Trans>;
case 'percentage-source-not-found':
return <Trans>Pick a valid income category</Trans>;
default:
@@ -114,6 +122,20 @@ export function AutomationErrorDetail({
saving.
</Trans>
);
+ case 'spend-no-from':
+ return (
+ <Trans>
+ Early-spending templates need a start month. Pick when you want
+ spending to begin.
+ </Trans>
+ );
+ case 'spend-from-after-target':
+ return (
+ <Trans>
+ The early-spending month must be the same as or earlier than the
+ target month, since it marks when spending begins.
+ </Trans>
+ );
case 'percentage-source-not-found':
return (
<Trans>
diff --git a/packages/desktop-client/src/components/budget/goals/constants.ts b/packages/desktop-client/src/components/budget/goals/constants.ts
index 1422b29e2e..39e7092c9a 100644
--- a/packages/desktop-client/src/components/budget/goals/constants.ts
+++ b/packages/desktop-client/src/components/budget/goals/constants.ts
@@ -9,6 +9,7 @@ import type {
RefillTemplate,
RemainderTemplate,
ScheduleTemplate,
+ SpendTemplate,
} from '@actual-app/core/types/models/templates';
export const displayTemplateTypes = [
@@ -51,7 +52,7 @@ export type ReducerState =
displayType: 'historical';
}
| {
- template: ByTemplate;
+ template: ByTemplate | SpendTemplate;
displayType: 'by';
}
| {
diff --git a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx
index c5dc025ab7..6c6fb0f205 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx
@@ -1,11 +1,18 @@
import { useEffect, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
+import { SvgInformationCircle } from '@actual-app/components/icons/v2';
import { Input } from '@actual-app/components/input';
import { Select } from '@actual-app/components/select';
import { SpaceBetween } from '@actual-app/components/space-between';
+import { theme } from '@actual-app/components/theme';
+import { Tooltip } from '@actual-app/components/tooltip';
+import { View } from '@actual-app/components/view';
import { amountToInteger, integerToAmount } from '@actual-app/core/shared/util';
-import type { ByTemplate } from '@actual-app/core/types/models/templates';
+import type {
+ ByTemplate,
+ SpendTemplate,
+} from '@actual-app/core/types/models/templates';
import { updateTemplate } from '#components/budget/goals/actions';
import type { Action } from '#components/budget/goals/actions';
@@ -16,7 +23,7 @@ import { GenericInput } from '#components/util/GenericInput';
import { useFormat } from '#hooks/useFormat';
type BySaveAutomationProps = {
- template: ByTemplate;
+ template: ByTemplate | SpendTemplate;
dispatch: (action: Action) => void;
};
@@ -41,11 +48,13 @@ export const BySaveAutomation = ({
const parsed = Math.max(1, Math.trunc(Number(rawRepeat)) || 1);
setRawRepeat(String(parsed));
if (parsed !== committedRepeat) {
- dispatch(updateTemplate({ type: 'by', repeat: parsed }));
+ dispatch(updateTemplate({ type: template.type, repeat: parsed }));
}
};
const repeats = !!template.repeat;
+ const spendDown = template.type === 'spend';
+ const fromMonth = template.type === 'spend' ? template.from : '';
return (
<>
@@ -59,7 +68,7 @@ export const BySaveAutomation = ({
onUpdate={(value: number) =>
dispatch(
updateTemplate({
- type: 'by',
+ type: template.type,
amount: integerToAmount(value, format.currency.decimalPlaces),
}),
)
@@ -67,15 +76,18 @@ export const BySaveAutomation = ({
/>
</FormField>
<FormField style={{ flex: 1 }}>
- <FormLabel title={t('Target date')} htmlFor="by-month-field" />
+ <FormLabel title={t('Target month')} htmlFor="by-month-field" />
<GenericInput
+ // remount when the stored month changes so the picker re-syncs
+ // to day 01 instead of lingering on whatever day the user picked
+ key={template.month}
type="date"
field="date"
value={template.month ? `${template.month}-01` : ''}
onChange={(value: string) =>
dispatch(
updateTemplate({
- type: 'by',
+ type: template.type,
month: value ? value.slice(0, 7) : '',
}),
)
@@ -93,11 +105,15 @@ export const BySaveAutomation = ({
updateTemplate(
e.target.checked
? {
- type: 'by',
+ type: template.type,
annual: false,
repeat: template.repeat ?? 1,
}
- : { type: 'by', annual: undefined, repeat: undefined },
+ : {
+ type: template.type,
+ annual: undefined,
+ repeat: undefined,
+ },
),
)
}
@@ -131,7 +147,10 @@ export const BySaveAutomation = ({
value={template.annual ? 'year' : 'month'}
onChange={value =>
dispatch(
- updateTemplate({ type: 'by', annual: value === 'year' }),
+ updateTemplate({
+ type: template.type,
+ annual: value === 'year',
+ }),
)
}
options={[
@@ -143,6 +162,95 @@ export const BySaveAutomation = ({
</>
)}
</SpaceBetween>
+ <SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>
+ <FormField style={{ flex: 1 }}>
+ <LabeledCheckbox
+ id="by-spend-down-field"
+ checked={spendDown}
+ onChange={e =>
+ dispatch(
+ updateTemplate(
+ e.target.checked
+ ? { type: 'spend', from: fromMonth || template.month }
+ : { type: 'by' },
+ ),
+ )
+ }
+ >
+ <span
+ style={{
+ marginLeft: 6,
+ fontSize: 12,
+ whiteSpace: 'nowrap',
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: 4,
+ }}
+ >
+ <Trans>Allow early spending</Trans>
+ {/* tooltip lives inside the checkbox label; stop the click
+ from also toggling the checkbox */}
+ <span
+ onClick={e => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onMouseDown={e => e.stopPropagation()}
+ style={{ display: 'inline-flex' }}
+ >
+ <Tooltip
+ content={
+ <View style={{ maxWidth: 280 }}>
+ <Trans>
+ Without this, spending before the target month leaves a
+ gap that the next month's contribution has to make up.
+ Turn this on to tell Actual spending is expected from a
+ chosen month onwards, so it doesn't budget more to
+ recover the shortfall.
+ </Trans>
+ <View style={{ marginTop: 6, fontStyle: 'italic' }}>
+ <Trans>
+ Example: budget for Christmas presents by December,
+ with shopping starting in March.
+ </Trans>
+ </View>
+ </View>
+ }
+ placement="top start"
+ >
+ <SvgInformationCircle
+ width={12}
+ height={12}
+ style={{ color: theme.pageTextLight, cursor: 'help' }}
+ />
+ </Tooltip>
+ </span>
+ </span>
+ </LabeledCheckbox>
+ </FormField>
+ {spendDown && (
+ <FormField style={{ flex: 1 }}>
+ <FormLabel
+ title={t('Start spending in')}
+ htmlFor="by-spend-from-field"
+ />
+ <GenericInput
+ key={fromMonth}
+ type="date"
+ field="date"
+ value={fromMonth ? `${fromMonth}-01` : ''}
+ onChange={(value: string) =>
+ dispatch(
+ updateTemplate({
+ type: 'spend',
+ from: value ? value.slice(0, 7) : '',
+ }),
+ )
+ }
+ />
+ </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.tsx
index 73260b42ef..fece0c2508 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomationReadOnly.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomationReadOnly.tsx
@@ -1,7 +1,10 @@
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 {
+ ByTemplate,
+ SpendTemplate,
+} from '@actual-app/core/types/models/templates';
import type { TransObjectLiteral } from '@actual-app/core/types/util';
import { formatMonthLabel } from '#components/budget/goals/formatMonthLabel';
@@ -10,7 +13,7 @@ import { useFormat } from '#hooks/useFormat';
import { useLocale } from '#hooks/useLocale';
type BySaveAutomationReadOnlyProps = {
- template: ByTemplate;
+ template: ByTemplate | SpendTemplate;
};
export const BySaveAutomationReadOnly = ({
@@ -24,8 +27,19 @@ export const BySaveAutomationReadOnly = ({
);
const month = formatMonthLabel(template.month, locale);
const repeat = template.repeat ?? 1;
+ const from =
+ template.type === 'spend' ? formatMonthLabel(template.from, locale) : null;
if (template.annual) {
+ if (from) {
+ return (
+ <Trans count={repeat}>
+ Save <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}
+ by {{ month }}, early spending from {{ from }}, repeating every{' '}
+ {{ count: repeat }} years
+ </Trans>
+ );
+ }
return (
<Trans count={repeat}>
Save <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}
@@ -35,6 +49,15 @@ export const BySaveAutomationReadOnly = ({
}
if (template.repeat && template.repeat > 0) {
+ if (from) {
+ return (
+ <Trans count={repeat}>
+ Save <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}
+ by {{ month }}, early spending from {{ from }}, repeating every{' '}
+ {{ count: repeat }} months
+ </Trans>
+ );
+ }
return (
<Trans count={repeat}>
Save <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}
@@ -43,6 +66,15 @@ export const BySaveAutomationReadOnly = ({
);
}
+ if (from) {
+ return (
+ <Trans>
+ Save <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText>{' '}
+ by {{ month }}, early spending from {{ from }}
+ </Trans>
+ );
+ }
+
return (
<Trans>
Save <FinancialText>{{ amount } as TransObjectLiteral}</FinancialText> by{' '}
diff --git a/packages/desktop-client/src/components/budget/goals/reducer.ts b/packages/desktop-client/src/components/budget/goals/reducer.ts
index b222cc6c5f..19700613b1 100644
--- a/packages/desktop-client/src/components/budget/goals/reducer.ts
+++ b/packages/desktop-client/src/components/budget/goals/reducer.ts
@@ -47,9 +47,8 @@ export const getInitialState = (template: Template | null): ReducerState => {
template,
displayType: 'fixed',
};
- case 'spend':
- throw new Error('Goal is not yet supported');
case 'by':
+ case 'spend':
return {
template:
template.annual !== undefined && template.repeat == null
@@ -187,7 +186,11 @@ const changeType = (
},
};
case 'by':
- if (prevState.template.type === 'by') {
+ // 'spend' shares displayType 'by'; preserve it instead of discarding
+ if (
+ prevState.template.type === 'by' ||
+ prevState.template.type === 'spend'
+ ) {
return prevState;
}
return {
@@ -276,6 +279,50 @@ function mapTemplateTypesForUpdate(
break;
}
break;
+ case 'by':
+ switch (template.type) {
+ case 'spend': {
+ // toggling spend-down on: carry the by template's fields into a
+ // spend template; default `from` to the target month if not given
+ const from =
+ 'from' in template && typeof template.from === 'string'
+ ? template.from
+ : state.template.month;
+ return {
+ ...state,
+ displayType: 'by',
+ template: {
+ ...state.template,
+ ...template,
+ type: 'spend',
+ from,
+ },
+ };
+ }
+ default:
+ break;
+ }
+ break;
+ case 'spend':
+ switch (template.type) {
+ case 'by': {
+ // toggling spend-down off: drop `from`, keep everything else
+ const { from: _from, ...rest } = state.template;
+ void _from;
+ return {
+ ...state,
+ displayType: 'by',
+ template: {
+ ...rest,
+ ...template,
+ type: 'by',
+ },
+ };
+ }
+ default:
+ break;
+ }
+ break;
default:
break;
}
diff --git a/packages/desktop-client/src/components/budget/goals/validateAutomation.ts b/packages/desktop-client/src/components/budget/goals/validateAutomation.ts
index 5d8239f8e0..842c2e3e19 100644
--- a/packages/desktop-client/src/components/budget/goals/validateAutomation.ts
+++ b/packages/desktop-client/src/components/budget/goals/validateAutomation.ts
@@ -11,7 +11,9 @@ export type AutomationErrorKind =
| { kind: 'percentage-no-source' }
| { kind: 'percentage-source-not-found'; source: string }
| { kind: 'by-no-month' }
- | { kind: 'by-target-past'; month: string };
+ | { kind: 'by-target-past'; month: string }
+ | { kind: 'spend-no-from' }
+ | { kind: 'spend-from-after-target' };
export type GlobalConflictKind =
| { kind: 'over-income'; total: number; income: number }
@@ -67,7 +69,7 @@ export function validateAutomation(
}
return null;
case 'by': {
- if (template.type !== 'by') return null;
+ if (template.type !== 'by' && template.type !== 'spend') return null;
if (!template.month || !monthUtils.isValidYearMonth(template.month)) {
return { kind: 'by-no-month' };
}
@@ -87,6 +89,16 @@ export function validateAutomation(
if (monthsRemaining < 0 && !template.annual && !template.repeat) {
return { kind: 'by-target-past', month: targetMonth };
}
+ if (template.type === 'spend') {
+ if (!template.from || !monthUtils.isValidYearMonth(template.from)) {
+ return { kind: 'spend-no-from' };
+ }
+ if (
+ monthUtils.differenceInCalendarMonths(targetMonth, template.from) < 0
+ ) {
+ return { kind: 'spend-from-after-target' };
+ }
+ }
return null;
}
default:
diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx
index c056c3b2f3..78815fadd3 100644
--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx
+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx
@@ -67,9 +67,7 @@ export function BudgetAutomationsModal({
const hasErrorTemplate =
parsedTemplates?.some(t => t.type === 'error') ?? false;
- const hasSpendTemplate =
- parsedTemplates?.some(t => t.type === 'spend') ?? false;
- const hasUnsupportedDirective = hasErrorTemplate || hasSpendTemplate;
+ const hasUnsupportedDirective = hasErrorTemplate;
const incomeNameToId = new Map<string, string>();
for (const group of categories) {
@@ -116,10 +114,7 @@ export function BudgetAutomationsModal({
<AnimatedLoading style={{ width: 20, height: 20 }} />
</View>
) : hasUnsupportedDirective ? (
- <UnsupportedDirectivesNotice
- hasErrorTemplate={hasErrorTemplate}
- onClose={() => state.close()}
- />
+ <UnsupportedDirectivesNotice onClose={() => state.close()} />
) : (
<BudgetAutomationsBody
categoryId={categoryId}
diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsx
index 7ffadcab8d..7508c62d8e 100644
--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsx
+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsx
@@ -7,10 +7,8 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
export function UnsupportedDirectivesNotice({
- hasErrorTemplate,
onClose,
}: {
- hasErrorTemplate: boolean;
onClose: () => void;
}) {
return (
@@ -46,19 +44,11 @@ export function UnsupportedDirectivesNotice({
lineHeight: 1.5,
}}
>
- {hasErrorTemplate ? (
- <Trans>
- One or more <code>#template</code> lines in this category&rsquo;s
- notes couldn&rsquo;t be parsed. Fix them as text first, then re-open
- this modal to migrate.
- </Trans>
- ) : (
- <Trans>
- This category uses a <code>spend from</code> template, which the
- budget automations UI doesn&rsquo;t handle yet. Keep editing it as
- text in the category&rsquo;s notes.
- </Trans>
- )}
+ <Trans>
+ One or more <code>#template</code> lines in this category&rsquo;s
+ notes couldn&rsquo;t be parsed. Fix them as text first, then re-open
+ this modal to migrate.
+ </Trans>
</Text>
<Button onPress={onClose}>
<Trans>Close</Trans>
diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts
index 36a97175e2..b14355ef27 100644
--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts
+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts
@@ -22,13 +22,13 @@ function getDisplayTypeFromTemplate(template: Template): DisplayTemplateType {
case 'copy':
return 'historical';
case 'by':
+ case 'spend':
return 'by';
case 'remainder':
return 'remainder';
case 'goal':
return 'goal';
case 'error':
- case 'spend':
// filtered upstream by hasUnsupportedDirective; surface if it ever isn't
throw new Error(`Unsupported template type reached migration`);
default: {
diff --git a/upcoming-release-notes/7823.md b/upcoming-release-notes/7823.md
new file mode 100644
index 0000000000..213a24a02b
--- /dev/null
+++ b/upcoming-release-notes/7823.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [matt-fidd]
+---
+
+Automation UI: add spend from functionality