A local-first personal finance app
Add basic modal for budget automations (#4810)
Julian Dominguez-Schatz8878f36eaf8c
diff --git a/packages/desktop-client/src/components/Modals.tsx b/packages/desktop-client/src/components/Modals.tsxindex 941743b718..240f63693a 100644--- a/packages/desktop-client/src/components/Modals.tsx+++ b/packages/desktop-client/src/components/Modals.tsx@@ -11,6 +11,7 @@ import { useDispatch } from '../redux';import { EditSyncAccount } from './banksync/EditSyncAccount';import { AccountAutocompleteModal } from './modals/AccountAutocompleteModal';import { AccountMenuModal } from './modals/AccountMenuModal';+import { BudgetAutomationsModal } from './modals/BudgetAutomationsModal';import { BudgetFileSelectionModal } from './modals/BudgetFileSelectionModal';import { BudgetPageMenuModal } from './modals/BudgetPageMenuModal';import { CategoryAutocompleteModal } from './modals/CategoryAutocompleteModal';@@ -100,6 +101,9 @@ export function Modals() {case 'goal-templates':return budgetId ? <GoalTemplateModal key={key} /> : null;+ case 'category-automations-edit':+ return budgetId ? <BudgetAutomationsModal key={name} /> : null;+case 'keyboard-shortcuts':// don't show the hotkey help modal when a budget is not openreturn budgetId ? <KeyboardShortcutModal key={key} /> : null;diff --git a/packages/desktop-client/src/components/budget/goals/BudgetAutomation.tsx b/packages/desktop-client/src/components/budget/goals/BudgetAutomation.tsxnew file mode 100644index 0000000000..41da07ef7c--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/BudgetAutomation.tsx@@ -0,0 +1,96 @@+import { useCallback, useMemo, useReducer, useState } from 'react';++import { Stack } from '@actual-app/components/stack';+import { type CSSProperties } from '@actual-app/components/styles';++import { type Template } from 'loot-core/server/budget/types/templates';+import {+ type CategoryGroupEntity,+ type ScheduleEntity,+} from 'loot-core/types/models';++import { type Action } from './actions';+import { BudgetAutomationEditor } from './BudgetAutomationEditor';+import { BudgetAutomationReadOnly } from './BudgetAutomationReadOnly';+import { getInitialState, templateReducer } from './reducer';++type BudgetAutomationProps = {+ categories: CategoryGroupEntity[];+ schedules: readonly ScheduleEntity[];+ template?: Template;+ onSave?: () => void;+ onDelete?: () => void;+ style?: CSSProperties;+ readOnlyStyle?: CSSProperties;+ inline?: boolean;+};++const DEFAULT_TEMPLATE: Template = {+ directive: '',+ type: 'simple',+ monthly: 0,+};++export const BudgetAutomation = ({+ onDelete,+ onSave,+ categories,+ schedules,+ readOnlyStyle,+ style,+ template,+ inline = false,+}: BudgetAutomationProps) => {+ const [isEditing, setIsEditing] = useState(false);++ const [state, originalDispatch] = useReducer(+ templateReducer,+ getInitialState(template ?? DEFAULT_TEMPLATE),+ );+ const dispatch = useCallback(+ (action: Action) => {+ originalDispatch(action);+ onSave?.();+ },+ [originalDispatch, onSave],+ );++ const categoryNameMap = useMemo(() => {+ return categories.reduce(+ (acc, group) => {+ for (const category of group.categories ?? []) {+ acc[category.id] = category.name;+ }+ return acc;+ },+ {} as Record<string, string>,+ );+ }, [categories]);++ return (+ <Stack+ direction="column"+ spacing={inline ? 0 : 1}+ style={{ ...style, minHeight: 'fit-content' }}+ >+ <BudgetAutomationReadOnly+ state={state}+ categoryNameMap={categoryNameMap}+ isEditing={isEditing}+ setIsEditing={setIsEditing}+ onDelete={onDelete}+ style={readOnlyStyle}+ inline={inline}+ />+ {isEditing && (+ <BudgetAutomationEditor+ inline={inline}+ state={state}+ dispatch={dispatch}+ schedules={schedules}+ categories={categories}+ />+ )}+ </Stack>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/BudgetAutomationEditor.tsx b/packages/desktop-client/src/components/budget/goals/BudgetAutomationEditor.tsxnew file mode 100644index 0000000000..e3e538e7cd--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/BudgetAutomationEditor.tsx@@ -0,0 +1,158 @@+import { useTranslation, Trans } from 'react-i18next';++import { InitialFocus } from '@actual-app/components/initial-focus';+import { Select } from '@actual-app/components/select';+import { Stack } from '@actual-app/components/stack';+import { styles } from '@actual-app/components/styles';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';++import type {+ CategoryGroupEntity,+ ScheduleEntity,+} from 'loot-core/types/models';++import { FormField, FormLabel } from '../../forms';++import { type Action, setType } from './actions';+import { displayTemplateTypes, type ReducerState } from './constants';+import { HistoricalAutomation } from './editor/HistoricalAutomation';+import { PercentageAutomation } from './editor/PercentageAutomation';+import { ScheduleAutomation } from './editor/ScheduleAutomation';+import { SimpleAutomation } from './editor/SimpleAutomation';+import { WeekAutomation } from './editor/WeekAutomation';++type BudgetAutomationEditorProps = {+ inline: boolean;+ state: ReducerState;+ dispatch: (action: Action) => void;+ schedules: readonly ScheduleEntity[];+ categories: CategoryGroupEntity[];+};++const displayTypeToDescription = {+ simple: <Trans>Add a fixed amount to this category each month.</Trans>,+ week: (+ <Trans>+ Add a fixed amount to this category for each week in the month. For+ example, $100 per week would be $400 per month in a 4-week month.+ </Trans>+ ),+ schedule: (+ <Trans>+ Add enough to this category to cover the selected schedule. If the+ schedule occurs multiple times in a month, an amount will be added for+ each occurrence. You can choose to save up for the next occurrence over+ time (e.g. save $100 each month for a $300 quarterly bill) or cover each+ occurrence when it occurs (e.g. only add the $300 when the bill is due).+ </Trans>+ ),+ percentage: (+ <Trans>+ Add a fixed percentage of your income to this category each month. You can+ choose to take the percentage from the current month or the previous+ month.+ </Trans>+ ),+ historical: (+ <Trans>+ Add an amount to this category each month based on the values from+ previous months. For example, you can copy the amount from a year ago to+ budget for an annual expense, or budget the average of the last 3 months+ to account for seasonal changes.+ </Trans>+ ),+};++export function BudgetAutomationEditor({+ inline,+ state,+ dispatch,+ schedules,+ categories,+}: BudgetAutomationEditorProps) {+ const { t } = useTranslation();++ let automationEditor;+ switch (state.displayType) {+ case 'simple':+ automationEditor = (+ <SimpleAutomation template={state.template} dispatch={dispatch} />+ );+ break;+ case 'week':+ automationEditor = (+ <WeekAutomation template={state.template} dispatch={dispatch} />+ );+ break;+ case 'schedule':+ automationEditor = (+ <ScheduleAutomation+ schedules={schedules}+ template={state.template}+ dispatch={dispatch}+ />+ );+ break;+ case 'percentage':+ automationEditor = (+ <PercentageAutomation+ dispatch={dispatch}+ template={state.template}+ categories={categories}+ />+ );+ break;+ case 'historical':+ automationEditor = (+ <HistoricalAutomation template={state.template} dispatch={dispatch} />+ );+ break;+ default:+ automationEditor = (+ <Text>+ <Trans>Unrecognized automation type.</Trans>+ </Text>+ );+ }++ return (+ <Stack+ direction="column"+ spacing={2}+ style={{+ flex: 1,+ ...styles.editorPill,+ backgroundColor: theme.pillBackgroundLight,+ ...(inline ? { borderRadius: 0 } : {}),+ padding: 30,+ minHeight: 'fit-content',+ }}+ >+ <Stack direction="row" align="flex-start" spacing={4}>+ <FormField style={{ flexShrink: 0 }}>+ <FormLabel title={t('Type')} htmlFor="type-field" />+ <InitialFocus>+ <Select+ id="type-field"+ options={displayTemplateTypes}+ defaultLabel="Select an option"+ value={state.displayType}+ onChange={type => type && dispatch(setType(type))}+ style={{ width: 172 }}+ />+ </InitialFocus>+ </FormField>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Description')} />+ <Text>+ {displayTypeToDescription[state.displayType] ?? (+ <Trans>No description available</Trans>+ )}+ </Text>+ </FormField>+ </Stack>+ {automationEditor}+ </Stack>+ );+}diff --git a/packages/desktop-client/src/components/budget/goals/BudgetAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/BudgetAutomationReadOnly.tsxnew file mode 100644index 0000000000..09056d83ee--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/BudgetAutomationReadOnly.tsx@@ -0,0 +1,119 @@+import { type Dispatch, type SetStateAction } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgDelete } from '@actual-app/components/icons/v0';+import {+ SvgCheveronDown,+ SvgCheveronUp,+} from '@actual-app/components/icons/v1';+import { Stack } from '@actual-app/components/stack';+import { type CSSProperties } from '@actual-app/components/styles';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import { type ReducerState } from './constants';+import { HistoricalAutomationReadOnly } from './editor/HistoricalAutomationReadOnly';+import { PercentageAutomationReadOnly } from './editor/PercentageAutomationReadOnly';+import { ScheduleAutomationReadOnly } from './editor/ScheduleAutomationReadOnly';+import { SimpleAutomationReadOnly } from './editor/SimpleAutomationReadOnly';+import { WeekAutomationReadOnly } from './editor/WeekAutomationReadOnly';++type BudgetAutomationReadOnlyProps = {+ state: ReducerState;+ categoryNameMap: Record<string, string>;+ isEditing: boolean;+ setIsEditing: Dispatch<SetStateAction<boolean>>;+ onDelete?: () => void;+ style?: CSSProperties;+ inline?: boolean;+};++export function BudgetAutomationReadOnly({+ state,+ categoryNameMap,+ isEditing,+ setIsEditing,+ onDelete,+ style,+ inline,+}: BudgetAutomationReadOnlyProps) {+ const { t } = useTranslation();++ let automationReadOnly;+ switch (state.displayType) {+ case 'simple':+ automationReadOnly = (+ <SimpleAutomationReadOnly template={state.template} />+ );+ break;+ case 'week':+ automationReadOnly = <WeekAutomationReadOnly template={state.template} />;+ break;+ case 'schedule':+ automationReadOnly = (+ <ScheduleAutomationReadOnly template={state.template} />+ );+ break;+ case 'percentage':+ automationReadOnly = (+ <PercentageAutomationReadOnly+ template={state.template}+ categoryNameMap={categoryNameMap}+ />+ );+ break;+ case 'historical':+ automationReadOnly = (+ <HistoricalAutomationReadOnly template={state.template} />+ );+ break;+ default:+ automationReadOnly = (+ <Text>+ <Trans>Unrecognized automation type.</Trans>+ </Text>+ );+ break;+ }++ return (+ <Stack direction="row" align="center" spacing={2} style={style}>+ {inline && (+ <View+ style={{+ borderLeft: `1px solid ${theme.tableBorder}`,+ height: 'calc(100% - 4px)',+ }}+ />+ )}+ <Text style={{ color: theme.tableText, fontSize: 13 }}>+ {automationReadOnly}+ </Text>+ <View style={{ flex: 1 }} />+ <Button+ variant="bare"+ onPress={() => setIsEditing(prev => !prev)}+ style={{ padding: 2 }}+ aria-label={t('Edit template')}+ >+ {isEditing ? (+ <SvgCheveronUp style={{ width: 16, height: 16, color: 'inherit' }} />+ ) : (+ <SvgCheveronDown+ style={{ width: 16, height: 16, color: 'inherit' }}+ />+ )}+ </Button>+ <Button+ variant="bare"+ onPress={onDelete}+ style={{ padding: 5 }}+ aria-label={t('Delete template')}+ >+ <SvgDelete style={{ width: 8, height: 8, color: 'inherit' }} />+ </Button>+ </Stack>+ );+}diff --git a/packages/desktop-client/src/components/budget/goals/actions.ts b/packages/desktop-client/src/components/budget/goals/actions.tsnew file mode 100644index 0000000000..5e9f7890c5--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/actions.ts@@ -0,0 +1,37 @@+import { type Template } from 'loot-core/server/budget/types/templates';++import { type DisplayTemplateType } from './constants';++type SET_TYPE = {+ type: 'set-type';+ payload: DisplayTemplateType;+};++type SET_TEMPLATE = {+ type: 'set-template';+ payload: Template;+};++type UPDATE_TEMPLATE = {+ type: 'update-template';+ payload: Partial<Template>;+};++export const setType = (type: DisplayTemplateType): SET_TYPE => ({+ type: 'set-type' as const,+ payload: type,+});++export const setTemplate = (template: Template): SET_TEMPLATE => ({+ type: 'set-template' as const,+ payload: template,+});++export const updateTemplate = (+ template: Partial<Template>,+): UPDATE_TEMPLATE => ({+ type: 'update-template' as const,+ payload: template,+});++export type Action = SET_TYPE | SET_TEMPLATE | UPDATE_TEMPLATE;diff --git a/packages/desktop-client/src/components/budget/goals/constants.ts b/packages/desktop-client/src/components/budget/goals/constants.tsnew file mode 100644index 0000000000..8497e2104c--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/constants.ts@@ -0,0 +1,40 @@+import {+ type AverageTemplate,+ type CopyTemplate,+ type PercentageTemplate,+ type ScheduleTemplate,+ type SimpleTemplate,+ type WeekTemplate,+} from 'loot-core/server/budget/types/templates';++export const displayTemplateTypes = [+ ['simple', 'Fixed (monthly)'] as const,+ ['week', 'Fixed (weekly)'] as const,+ ['schedule', 'Schedule'] as const,+ ['percentage', 'Percent of category'] as const,+ ['historical', 'Copy past budgets'] as const,+];++export type DisplayTemplateType = (typeof displayTemplateTypes)[number][0];++export type ReducerState =+ | {+ template: SimpleTemplate;+ displayType: 'simple';+ }+ | {+ template: WeekTemplate;+ displayType: 'week';+ }+ | {+ template: ScheduleTemplate;+ displayType: 'schedule';+ }+ | {+ template: PercentageTemplate;+ displayType: 'percentage';+ }+ | {+ template: CopyTemplate | AverageTemplate;+ displayType: 'historical';+ };diff --git a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsxnew file mode 100644index 0000000000..3682dedff5--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx@@ -0,0 +1,71 @@+import { useTranslation } from 'react-i18next';++import { Select } from '@actual-app/components/select';+import { Stack } from '@actual-app/components/stack';++import type {+ CopyTemplate,+ AverageTemplate,+} from 'loot-core/server/budget/types/templates';++import { FormField, FormLabel } from '../../../forms';+import { GenericInput } from '../../../util/GenericInput';+import { type Action, updateTemplate } from '../actions';++type HistoricalAutomationProps = {+ template: CopyTemplate | AverageTemplate;+ dispatch: (action: Action) => void;+};++export const HistoricalAutomation = ({+ template,+ dispatch,+}: HistoricalAutomationProps) => {+ const { t } = useTranslation();++ return (+ <Stack+ direction="row"+ align="center"+ spacing={10}+ 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"+ />+ {/* @ts-expect-error should be auto-patched once GenericInput is converted to TS */}+ <GenericInput+ key="look-back-input"+ type="number"+ value={+ template.type === 'average' ? template.numMonths : template.lookBack+ }+ onChange={(value: number) =>+ dispatch(+ updateTemplate(+ template.type === 'average'+ ? { numMonths: value }+ : { lookBack: value },+ ),+ )+ }+ />+ </FormField>+ </Stack>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsxnew file mode 100644index 0000000000..625bfbaecc--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx@@ -0,0 +1,24 @@+import { Trans } from 'react-i18next';++import type {+ CopyTemplate,+ AverageTemplate,+} from 'loot-core/server/budget/types/templates';++type HistoricalAutomationReadOnlyProps = {+ template: CopyTemplate | AverageTemplate;+};++export const HistoricalAutomationReadOnly = ({+ template,+}: HistoricalAutomationReadOnlyProps) => {+ return template.type === 'copy' ? (+ <Trans>+ Budget the same amount as {{ amount: template.lookBack }} months ago+ </Trans>+ ) : (+ <Trans>+ Budget the average of the last {{ amount: template.numMonths }} months+ </Trans>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsxnew file mode 100644index 0000000000..8df3023995--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsx@@ -0,0 +1,112 @@+import { useTranslation } from 'react-i18next';++import { Select } from '@actual-app/components/select';+import { Stack } from '@actual-app/components/stack';+import { View } from '@actual-app/components/view';++import type { PercentageTemplate } from 'loot-core/server/budget/types/templates';+import type {+ CategoryGroupEntity,+ CategoryEntity,+} from 'loot-core/types/models';++import { CategoryAutocomplete } from '../../../autocomplete/CategoryAutocomplete';+import { FormField, FormLabel } from '../../../forms';+import { PercentInput } from '../../../util/PercentInput';+import { type Action, updateTemplate } from '../actions';++type PercentageAutomationProps = {+ dispatch: (action: Action) => void;+ template: PercentageTemplate;+ categories: CategoryGroupEntity[];+};++export const PercentageAutomation = ({+ dispatch,+ template,+ categories,+}: PercentageAutomationProps) => {+ const { t } = useTranslation();++ return (+ <>+ <Stack+ direction="row"+ align="center"+ spacing={10}+ style={{ marginTop: 10 }}+ >+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Category')} htmlFor="category-field" />+ <CategoryAutocomplete+ inputProps={{ id: 'category-field' }}+ onSelect={(category: CategoryEntity['id']) =>+ dispatch(updateTemplate({ type: 'percentage', category }))+ }+ value={template.category}+ categoryGroups={+ template.previous+ ? categories.map(group => ({+ ...group,+ categories: group.categories?.filter(+ category => category.id !== 'to-budget',+ ),+ }))+ : categories+ }+ />+ </FormField>+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Percentage')} htmlFor="percent-field" />+ <PercentInput+ id="percent-field"+ key="percent-input"+ value={template.percent}+ onUpdatePercent={(percent: number) =>+ dispatch(+ updateTemplate({+ type: 'percentage',+ percent,+ }),+ )+ }+ />+ </FormField>+ </Stack>+ <Stack+ direction="row"+ align="center"+ spacing={10}+ style={{ marginTop: 10 }}+ >+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Percentage of')} htmlFor="previous-field" />+ <Select+ id="previous-field"+ key="previous-month"+ options={[+ [false, t('This month')],+ [true, t('Last month')],+ ]}+ value={template.previous}+ onChange={previous => {+ if (template.type !== 'percentage') {+ return;+ }+ return dispatch(+ updateTemplate({+ type: 'percentage',+ previous,+ ...(previous && template.category === 'to-budget'+ ? { category: '' }+ : {}),+ }),+ );+ }}+ />+ </FormField>+ <View style={{ flex: 1 }} />+ </Stack>+ </>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomationReadOnly.tsxnew file mode 100644index 0000000000..78964cb433--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomationReadOnly.tsx@@ -0,0 +1,60 @@+import { useTranslation, Trans } from 'react-i18next';++import type { PercentageTemplate } from 'loot-core/server/budget/types/templates';++type PercentageAutomationReadOnlyProps = {+ template: PercentageTemplate;+ categoryNameMap: Record<string, string>;+};++export const PercentageAutomationReadOnly = ({+ template,+ categoryNameMap,+}: PercentageAutomationReadOnlyProps) => {+ const { t } = useTranslation();++ if (template.category === 'total') {+ return template.previous ? (+ <Trans>+ Budget {{ percent: template.percent }}% of total income last month+ </Trans>+ ) : (+ <Trans>+ Budget {{ percent: template.percent }}% of total income this month+ </Trans>+ );+ }++ if (template.category === 'to-budget') {+ return template.previous ? (+ <Trans>+ Budget {{ percent: template.percent }}% of available funds to budget+ last month+ </Trans>+ ) : (+ <Trans>+ Budget {{ percent: template.percent }}% of available funds to budget+ this month+ </Trans>+ );+ }++ // Regular income categories+ return template.previous ? (+ <Trans>+ Budget {{ percent: template.percent }}% of ‘+ {{+ category: categoryNameMap[template.category] ?? t('Unknown category'),+ }}+ ’ last month+ </Trans>+ ) : (+ <Trans>+ Budget {{ percent: template.percent }}% of ‘+ {{+ category: categoryNameMap[template.category] ?? t('Unknown category'),+ }}+ ’ this month+ </Trans>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsxnew file mode 100644index 0000000000..97ef76dc7b--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx@@ -0,0 +1,86 @@+import { useTranslation, Trans } from 'react-i18next';++import { Select } from '@actual-app/components/select';+import { Stack } from '@actual-app/components/stack';+import { Text } from '@actual-app/components/text';++import type { ScheduleTemplate } from 'loot-core/server/budget/types/templates';+import type { ScheduleEntity } from 'loot-core/types/models';++import { Link } from '../../../common/Link';+import { FormField, FormLabel } from '../../../forms';+import { type Action, updateTemplate } from '../actions';++type ScheduleAutomationProps = {+ schedules: readonly ScheduleEntity[];+ template: ScheduleTemplate;+ dispatch: (action: Action) => void;+};++export const ScheduleAutomation = ({+ schedules,+ template,+ dispatch,+}: ScheduleAutomationProps) => {+ const { t } = useTranslation();++ return schedules.length ? (+ <Stack+ direction="row"+ align="center"+ spacing={10}+ style={{ marginTop: 10 }}+ >+ <FormField style={{ flex: 1 }}>+ <FormLabel title={t('Schedule')} htmlFor="schedule-field" />+ <Select+ id="schedule-field"+ key="schedule-picker"+ defaultLabel="Select a schedule"+ value={template.name}+ onChange={schedule =>+ dispatch(+ updateTemplate({+ type: 'schedule',+ name: schedule,+ }),+ )+ }+ options={schedules.flatMap(schedule =>+ schedule.name ? [[schedule.name, schedule.name]] : [],+ )}+ />+ </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>+ </Stack>+ ) : (+ <Text style={{ marginTop: 10 }}>+ <Trans>+ No schedules found, create one in the{' '}+ <Link variant="internal" to="/schedules">+ schedules+ </Link>{' '}+ page.+ </Trans>+ </Text>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomationReadOnly.tsxnew file mode 100644index 0000000000..e7e9d0459e--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomationReadOnly.tsx@@ -0,0 +1,33 @@+import { Trans } from 'react-i18next';++import type { ScheduleTemplate } from 'loot-core/server/budget/types/templates';++type ScheduleAutomationReadOnlyProps = {+ template: ScheduleTemplate;+};++export const ScheduleAutomationReadOnly = ({+ template,+}: ScheduleAutomationReadOnlyProps) => {+ if (!template.name) {+ 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 (+ <Trans>+ Save up for the schedule ‘+ {{ name: template.name }}+ ’+ </Trans>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/SimpleAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/SimpleAutomation.tsxnew file mode 100644index 0000000000..08e9c3124a--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/SimpleAutomation.tsx@@ -0,0 +1,34 @@+import { useTranslation } from 'react-i18next';++import type { SimpleTemplate } from 'loot-core/server/budget/types/templates';++import { FormField, FormLabel } from '../../../forms';+import { AmountInput } from '../../../util/AmountInput';+import { type Action, updateTemplate } from '../actions';++type SimpleAutomationProps = {+ template: SimpleTemplate;+ dispatch: (action: Action) => void;+};++export const SimpleAutomation = ({+ template,+ dispatch,+}: SimpleAutomationProps) => {+ const { t } = useTranslation();++ return (+ <FormField>+ <FormLabel title={t('Amount')} htmlFor="amount-field" />+ <AmountInput+ id="amount-field"+ key="amount-input"+ value={template.monthly ?? 0}+ zeroSign="+"+ onUpdate={(value: number) =>+ dispatch(updateTemplate({ type: 'simple', monthly: value }))+ }+ />+ </FormField>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/SimpleAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/SimpleAutomationReadOnly.tsxnew file mode 100644index 0000000000..0e073ef4df--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/SimpleAutomationReadOnly.tsx@@ -0,0 +1,18 @@+import { Trans } from 'react-i18next';++import type { SimpleTemplate } from 'loot-core/server/budget/types/templates';+import { integerToCurrency } from 'loot-core/shared/util';++type SimpleAutomationReadOnlyProps = {+ template: SimpleTemplate;+};++export const SimpleAutomationReadOnly = ({+ template,+}: SimpleAutomationReadOnlyProps) => {+ return (+ <Trans>+ Budget {{ monthly: integerToCurrency(template.monthly ?? 0) }} each month+ </Trans>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/editor/WeekAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/WeekAutomation.tsxnew file mode 100644index 0000000000..57e590216f--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/WeekAutomation.tsx@@ -0,0 +1,31 @@+import { useTranslation } from 'react-i18next';++import type { WeekTemplate } from 'loot-core/server/budget/types/templates';++import { FormField, FormLabel } from '../../../forms';+import { AmountInput } from '../../../util/AmountInput';+import { type Action, updateTemplate } from '../actions';++type WeekAutomationProps = {+ template: WeekTemplate;+ 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: 'week', 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.tsxnew file mode 100644index 0000000000..9f95ec8d4a--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/WeekAutomationReadOnly.tsx@@ -0,0 +1,18 @@+import { Trans } from 'react-i18next';++import type { WeekTemplate } from 'loot-core/server/budget/types/templates';+import { integerToCurrency } from 'loot-core/shared/util';++type WeekAutomationReadOnlyProps = {+ template: WeekTemplate;+};++export const WeekAutomationReadOnly = ({+ template,+}: WeekAutomationReadOnlyProps) => {+ return (+ <Trans>+ Budget {{ amount: integerToCurrency(template.amount) }} each week+ </Trans>+ );+};diff --git a/packages/desktop-client/src/components/budget/goals/reducer.ts b/packages/desktop-client/src/components/budget/goals/reducer.tsnew file mode 100644index 0000000000..f2bb1be44b--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/reducer.ts@@ -0,0 +1,207 @@+import { type Template } from 'loot-core/server/budget/types/templates';++import { type Action } from './actions';+import { type ReducerState, type DisplayTemplateType } from './constants';++export const getInitialState = (template: Template | null): ReducerState => {+ const type = template?.type;+ switch (type) {+ case 'simple':+ return {+ template,+ displayType: 'simple',+ };+ case 'percentage':+ return {+ template,+ displayType: 'percentage',+ };+ case 'schedule':+ return {+ template,+ displayType: 'schedule',+ };+ case 'week':+ return {+ template,+ displayType: 'week',+ };+ case 'spend':+ case 'by':+ throw new Error('Goal is not yet supported');+ case 'remainder':+ throw new Error('Remainder is not yet supported');+ case 'average':+ case 'copy':+ return {+ template,+ displayType: 'historical',+ };+ case 'goal':+ throw new Error('Goal is not yet supported');+ case 'error':+ throw new Error('An error occurred while parsing the template');+ default:+ throw new Error(`Unknown template type: ${type satisfies undefined}`);+ }+};++const changeType = (+ prevState: ReducerState,+ visualType: DisplayTemplateType,+): ReducerState => {+ switch (visualType) {+ case 'simple':+ if (prevState.template.type === 'simple') {+ return prevState;+ }+ return {+ displayType: visualType,+ template: {+ directive: '',+ type: 'simple',+ monthly: 500,+ },+ };+ case 'percentage':+ if (prevState.template.type === 'percentage') {+ return prevState;+ }+ return {+ displayType: visualType,+ template: {+ directive: '',+ type: 'percentage',+ percent: 15,+ previous: false,+ category: 'total',+ },+ };+ case 'schedule':+ if (prevState.template.type === 'schedule') {+ return prevState;+ }+ return {+ displayType: visualType,+ template: {+ directive: '',+ type: 'schedule',+ name: '',+ },+ };+ case 'week':+ if (prevState.template.type === 'week') {+ return prevState;+ }+ return {+ displayType: visualType,+ template: {+ directive: '',+ type: 'week',+ amount: 500,+ weeks: null,+ starting: '',+ },+ };+ case 'historical':+ if (+ prevState.template.type === 'copy' ||+ prevState.template.type === 'average'+ ) {+ return prevState;+ }+ return {+ displayType: visualType,+ template: {+ directive: '',+ type: 'average',+ numMonths: 3,+ },+ };+ default:+ // Make sure we're not missing any cases+ throw new Error(`Unknown display type: ${visualType satisfies never}`);+ }+};++function mapTemplateTypesForUpdate(+ state: ReducerState,+ template: Partial<Template>,+): ReducerState {+ switch (state.template.type) {+ case 'average':+ switch (template.type) {+ case 'copy':+ return {+ ...state,+ displayType: 'historical',+ template: {+ ...template,+ directive: '',+ type: 'copy',+ lookBack: state.template.numMonths,+ },+ };+ default:+ break;+ }+ break;+ case 'copy':+ switch (template.type) {+ case 'average':+ return {+ ...state,+ displayType: 'historical',+ template: {+ ...template,+ directive: '',+ type: 'average',+ numMonths: state.template.lookBack,+ },+ };+ default:+ break;+ }+ break;+ default:+ break;+ }++ if (!template.type || state.template.type === template.type) {+ const { type: _, ...rest } = template;+ return {+ ...state,+ ...getInitialState({+ ...state.template,+ ...rest,+ }),+ };+ }++ console.error(+ `Template type mismatch: ${state.template.type} !== ${template.type}`,+ );+ return state;+}++export const templateReducer = (+ state: ReducerState,+ action: Action,+): ReducerState => {+ switch (action.type) {+ case 'set-type':+ return {+ ...state,+ ...changeType(state, action.payload),+ };+ case 'set-template':+ return {+ ...state,+ ...getInitialState(action.payload),+ };+ case 'update-template':+ return mapTemplateTypesForUpdate(state, action.payload);+ default:+ return state;+ }+};diff --git a/packages/desktop-client/src/components/budget/goals/useBudgetAutomationCategories.ts b/packages/desktop-client/src/components/budget/goals/useBudgetAutomationCategories.tsnew file mode 100644index 0000000000..2208905942--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/useBudgetAutomationCategories.ts@@ -0,0 +1,29 @@+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useCategories } from '../../../hooks/useCategories';++export function useBudgetAutomationCategories() {+ const { t } = useTranslation();+ const { grouped } = useCategories();+ const categories = useMemo(() => {+ const incomeGroup = grouped.filter(group => group.name === 'Income')[0];+ return [+ {+ id: '',+ name: t('Special categories'),+ categories: [+ { id: 'total', group: '', name: t('Total of all income') },+ {+ id: 'to-budget',+ group: '',+ name: t('Available funds to budget'),+ },+ ],+ },+ { ...incomeGroup, name: t('Income categories') },+ ];+ }, [grouped, t]);++ return categories;+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal.tsxnew file mode 100644index 0000000000..b86cb3ae89--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal.tsx@@ -0,0 +1,96 @@+import { useMemo, useState } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { Stack } from '@actual-app/components/stack';+import { theme } from '@actual-app/components/theme';+import { uniqueId } from 'lodash';++import { useSchedules } from 'loot-core/client/data-hooks/schedules';+import { type Template } from 'loot-core/server/budget/types/templates';+import { q } from 'loot-core/shared/query';++import { BudgetAutomation } from '../budget/goals/BudgetAutomation';+import { useBudgetAutomationCategories } from '../budget/goals/useBudgetAutomationCategories';+import { Modal, ModalCloseButton, ModalHeader } from '../common/Modal';++type TemplateWithId = Template & { id: string };++export function BudgetAutomationsModal() {+ const { t } = useTranslation();++ // HACK: This is a placeholder for the actual data.+ // We should eventually load it using a data hook.+ const [templates, setTemplates] = useState<TemplateWithId[]>([+ {+ type: 'average',+ numMonths: 3,+ directive: '',+ id: uniqueId(),+ },+ ]);++ const schedulesQuery = useMemo(() => q('schedules').select('*'), []);+ const { schedules } = useSchedules({+ query: schedulesQuery,+ });++ const categories = useBudgetAutomationCategories();++ const onAdd = () => {+ setTemplates([+ ...templates,+ { type: 'average', numMonths: 3, directive: '', id: uniqueId() },+ ]);+ };+ const onSave = () => {};+ const onDelete = (index: number) => () => {+ setTemplates([...templates.slice(0, index), ...templates.slice(index + 1)]);+ };++ return (+ <Modal+ name="category-automations-edit"+ containerProps={{+ style: { width: 850, height: 650, paddingBottom: 20 },+ }}+ >+ {({ state: { close } }) => (+ <>+ <ModalHeader+ title={t('Budget automations')}+ rightContent={<ModalCloseButton onPress={close} />}+ />+ <Stack+ spacing={4}+ style={{+ overflowY: 'scroll',+ }}+ >+ {templates.map((template, index) => (+ <BudgetAutomation+ key={template.id}+ onSave={onSave}+ onDelete={onDelete(index)}+ template={template}+ categories={categories}+ schedules={schedules}+ readOnlyStyle={{+ color: theme.pillText,+ backgroundColor: theme.pillBackground,+ borderRadius: 4,+ padding: 16,+ paddingLeft: 30,+ paddingRight: 16,+ }}+ />+ ))}+ <Button onPress={onAdd}>+ <Trans>Add new automation</Trans>+ </Button>+ </Stack>+ </>+ )}+ </Modal>+ );+}diff --git a/upcoming-release-notes/4810.md b/upcoming-release-notes/4810.mdnew file mode 100644index 0000000000..615f645517--- /dev/null+++ b/upcoming-release-notes/4810.md@@ -0,0 +1,6 @@+---+category: Features+authors: [jfdoming]+---++Add modal for creating budget automations