A local-first personal finance app
automation UI: add cleanup functionality (#7815)
Matt Fiddaman6bfc299d28be
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex 65404b59bf..183949ee64 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -42,6 +42,7 @@"#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/cleanupModel": "./src/components/budget/goals/cleanupModel.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",diff --git a/packages/desktop-client/src/components/budget/SidebarCategoryButtons.tsx b/packages/desktop-client/src/components/budget/SidebarCategoryButtons.tsxindex a523e6dce3..8b91926ced 100644--- a/packages/desktop-client/src/components/budget/SidebarCategoryButtons.tsx+++ b/packages/desktop-client/src/components/budget/SidebarCategoryButtons.tsx@@ -43,7 +43,7 @@ export const SidebarCategoryButtons = ({showPlaceholder={!goalsShown &&isGoalTemplatesUIEnabled &&- !!category.goal_def?.length+ (!!category.goal_def?.length || !!category.cleanup_def?.length)}/></View>diff --git a/packages/desktop-client/src/components/budget/goals/CategoryAutomationButton.tsx b/packages/desktop-client/src/components/budget/goals/CategoryAutomationButton.tsxindex 7b8fea5c2c..a31cfd0248 100644--- a/packages/desktop-client/src/components/budget/goals/CategoryAutomationButton.tsx+++ b/packages/desktop-client/src/components/budget/goals/CategoryAutomationButton.tsx@@ -38,7 +38,8 @@ export function CategoryAutomationButton({const goalTemplatesEnabled = useFeatureFlag('goalTemplatesEnabled');const goalTemplatesUIEnabled = useFeatureFlag('goalTemplatesUIEnabled');const [budgetType = 'envelope'] = useSyncedPref('budgetType');- const hasAutomations = !!category.goal_def?.length;+ const hasAutomations =+ !!category.goal_def?.length || !!category.cleanup_def?.length;if (!goalTemplatesEnabled || !goalTemplatesUIEnabled) {return null;diff --git a/packages/desktop-client/src/components/budget/goals/cleanupModel.ts b/packages/desktop-client/src/components/budget/goals/cleanupModel.tsnew file mode 100644index 0000000000..c65f2d494d--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/cleanupModel.ts@@ -0,0 +1,136 @@+import type { CleanupTemplate } from '@actual-app/core/types/models/cleanup-templates';++export type GlobalCleanup = {+ send: boolean;+ take: boolean;+ weight: number;+};++export type GroupCleanup = {+ groupId: string;+ send: boolean;+ take: boolean;+ weight: number;+ overspendOnly: boolean;+};++export type CleanupConfig = {+ global: GlobalCleanup;+ groups: GroupCleanup[];+};++export const emptyCleanupConfig = (): CleanupConfig => ({+ global: { send: false, take: false, weight: 1 },+ groups: [],+});++export function isCleanupConfigured(config: CleanupConfig): boolean {+ return (+ config.global.send ||+ config.global.take ||+ config.groups.some(group => group.send || group.take)+ );+}++function ensureGroup(+ map: Map<string, GroupCleanup>,+ groupId: string,+): GroupCleanup {+ const existing = map.get(groupId);+ if (existing) return existing;+ const fresh: GroupCleanup = {+ groupId,+ send: false,+ take: false,+ weight: 1,+ overspendOnly: false,+ };+ map.set(groupId, fresh);+ return fresh;+}++export function cleanupDefToEditor(cleanup: CleanupTemplate[]): CleanupConfig {+ const config = emptyCleanupConfig();+ const groupScopes = new Map<string, GroupCleanup>();++ for (const row of cleanup) {+ if (row.role === 'source') {+ if (row.groupId === null) {+ config.global.send = true;+ } else {+ const group = ensureGroup(groupScopes, row.groupId);+ group.send = true;+ }+ } else if (row.role === 'sink') {+ if (row.groupId === null) {+ config.global.take = true;+ config.global.weight = row.weight;+ } else {+ const group = ensureGroup(groupScopes, row.groupId);+ group.take = true;+ group.weight = row.weight;+ // a sink wins over a stray prior overspend row for the same group+ group.overspendOnly = false;+ }+ } else {+ const group = ensureGroup(groupScopes, row.groupId);+ // don't downgrade a real sink row already recorded for this group+ if (!group.take) {+ group.take = true;+ group.overspendOnly = true;+ }+ }+ }++ config.groups = Array.from(groupScopes.values());+ return config;+}++export function editorToCleanupDef(config: CleanupConfig): CleanupTemplate[] {+ if (!isCleanupConfigured(config)) return [];++ const rows: CleanupTemplate[] = [];++ if (config.global.send) rows.push({ role: 'source', groupId: null });+ if (config.global.take) {+ rows.push({ role: 'sink', groupId: null, weight: config.global.weight });+ }++ for (const group of config.groups) {+ if (group.send) rows.push({ role: 'source', groupId: group.groupId });+ if (group.take) {+ rows.push(+ group.overspendOnly+ ? { role: 'overspend', groupId: group.groupId }+ : { role: 'sink', groupId: group.groupId, weight: group.weight },+ );+ }+ }++ return rows;+}++export function cleanupToNotes(+ cleanup: CleanupTemplate[],+ groupName: (groupId: string) => string | null,+): string {+ return cleanup+ .flatMap(row => {+ if (row.role === 'overspend') {+ const name = groupName(row.groupId);+ return name ? [`#cleanup ${name}`] : [];+ }+ let scope = '';+ if (row.groupId !== null) {+ const name = groupName(row.groupId);+ if (!name) return [];+ scope = `${name} `;+ }+ if (row.role === 'source') {+ return [`#cleanup ${scope}source`];+ }+ const weight = row.weight !== 1 ? ` ${row.weight}` : '';+ return [`#cleanup ${scope}sink${weight}`];+ })+ .join('\n');+}diff --git a/packages/desktop-client/src/components/budget/goals/editor/CleanupAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/CleanupAutomation.tsxnew file mode 100644index 0000000000..37c94911af--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/CleanupAutomation.tsx@@ -0,0 +1,290 @@+import { useState } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgDelete } from '@actual-app/components/icons/v0';+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 { View } from '@actual-app/components/view';++import type {+ CleanupConfig,+ GroupCleanup,+} from '#components/budget/goals/cleanupModel';+import { Link } from '#components/common/Link';+import { FormLabel } from '#components/forms';+import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';+import type { CleanupGroup } from '#hooks/useCleanupGroups';++import { CleanupGroupPicker } from './CleanupGroupPicker';++type CleanupAutomationProps = {+ config: CleanupConfig;+ groups: CleanupGroup[];+ onChange: (next: CleanupConfig) => void;+ onCreateGroup: (name: string) => Promise<string>;+};++export function CleanupAutomation({+ config,+ groups,+ onChange,+ onCreateGroup,+}: CleanupAutomationProps) {+ const { t } = useTranslation();+ const [pickingGroup, setPickingGroup] = useState(false);++ const updateGlobal = (patch: Partial<CleanupConfig['global']>) =>+ onChange({ ...config, global: { ...config.global, ...patch } });++ const updateGroup = (groupId: string, patch: Partial<GroupCleanup>) =>+ onChange({+ ...config,+ groups: config.groups.map(group =>+ group.groupId === groupId ? { ...group, ...patch } : group,+ ),+ });++ const removeGroup = (groupId: string) =>+ onChange({+ ...config,+ groups: config.groups.filter(group => group.groupId !== groupId),+ });++ const addGroup = (groupId: string) => {+ if (config.groups.some(group => group.groupId === groupId)) return;+ onChange({+ ...config,+ groups: [+ ...config.groups,+ {+ groupId,+ send: false,+ take: false,+ weight: 1,+ overspendOnly: false,+ },+ ],+ });+ };++ return (+ <View style={{ gap: 14 }}>+ <Text style={{ fontSize: 12, color: theme.pageTextSubdued }}>+ <Trans>+ End of month cleanup is a one-click reallocation of funds. Categories+ you choose to <strong>send leftover</strong> return their surplus to a+ pool; categories you mark to <strong>receive leftover</strong> receive+ part or all of that pool back. By default, the pool is To Budget. You+ can also create named pools so the surplus only moves between+ categories set to use that pool.{' '}+ <Link+ variant="external"+ to="https://actualbudget.org/docs/experimental/monthly-cleanup#local-group-source-and-sinks"+ >+ Learn more+ </Link>+ </Trans>+ </Text>++ <ScopeCard+ title={t('Global')}+ sendLabel={t('Send leftover')}+ takeLabel={t('Receive leftover')}+ send={config.global.send}+ take={config.global.take}+ weight={config.global.weight}+ overspendOnly={false}+ showOverspendOnly={false}+ onChangeSend={send => updateGlobal({ send })}+ onChangeTake={take => updateGlobal({ take })}+ onChangeWeight={weight => updateGlobal({ weight })}+ onChangeOverspendOnly={() => undefined}+ />++ {config.groups.map(group => {+ const groupName =+ groups.find(g => g.id === group.groupId)?.name ?? t('Unknown pool');+ return (+ <ScopeCard+ key={group.groupId}+ title={t('Pool: {{groupName}}', { groupName })}+ sendLabel={t('Send leftover to pool')}+ takeLabel={t('Receive leftover from pool')}+ send={group.send}+ take={group.take}+ weight={group.weight}+ overspendOnly={group.overspendOnly}+ showOverspendOnly+ onChangeSend={send => updateGroup(group.groupId, { send })}+ onChangeTake={take => updateGroup(group.groupId, { take })}+ onChangeWeight={weight => updateGroup(group.groupId, { weight })}+ onChangeOverspendOnly={overspendOnly =>+ updateGroup(group.groupId, { overspendOnly })+ }+ onRemove={() => removeGroup(group.groupId)}+ />+ );+ })}++ {/* The engine accepts multiple pool scopes per category but the result+ depends on category sort order, so the editor caps it at one. */}+ {config.groups.length === 0 &&+ (pickingGroup ? (+ <View style={{ gap: 6 }}>+ <FormLabel+ title={t('Pick or create a pool')}+ htmlFor="cleanup-add-group-field"+ />+ <CleanupGroupPicker+ id="cleanup-add-group-field"+ groups={groups}+ autoFocus+ onSelect={groupId => {+ addGroup(groupId);+ setPickingGroup(false);+ }}+ onCreate={onCreateGroup}+ />+ </View>+ ) : (+ <Button+ variant="bare"+ onPress={() => setPickingGroup(true)}+ style={{ alignSelf: 'flex-start', color: theme.pageTextPositive }}+ >+ + <Trans>Add to a pool</Trans>+ </Button>+ ))}+ </View>+ );+}++type ScopeCardProps = {+ title: string;+ sendLabel: string;+ takeLabel: string;+ send: boolean;+ take: boolean;+ weight: number;+ overspendOnly: boolean;+ showOverspendOnly: boolean;+ onChangeSend: (send: boolean) => void;+ onChangeTake: (take: boolean) => void;+ onChangeWeight: (weight: number) => void;+ onChangeOverspendOnly: (overspendOnly: boolean) => void;+ onRemove?: () => void;+};++function ScopeCard({+ title,+ sendLabel,+ takeLabel,+ send,+ take,+ weight,+ overspendOnly,+ showOverspendOnly,+ onChangeSend,+ onChangeTake,+ onChangeWeight,+ onChangeOverspendOnly,+ onRemove,+}: ScopeCardProps) {+ const { t } = useTranslation();+ return (+ <View+ style={{+ padding: 12,+ backgroundColor: theme.tableBackground,+ borderRadius: 6,+ border: `1px solid ${theme.tableBorder}`,+ gap: 8,+ }}+ >+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}+ >+ <Text+ style={{+ fontSize: 11,+ textTransform: 'uppercase',+ color: theme.pageTextSubdued,+ fontWeight: 600,+ letterSpacing: '0.04em',+ }}+ >+ {title}+ </Text>+ {onRemove && (+ <Button+ variant="bare"+ onPress={onRemove}+ aria-label={t('Remove pool')}+ style={{ color: theme.pageTextSubdued, padding: 2 }}+ >+ <SvgDelete width={10} height={10} style={{ color: 'inherit' }} />+ </Button>+ )}+ </View>++ <LabeledCheckbox+ id={`cleanup-send-${title}`}+ checked={send}+ onChange={e => onChangeSend(e.target.checked)}+ >+ <span style={{ marginLeft: 6, fontSize: 12 }}>{sendLabel}</span>+ </LabeledCheckbox>++ <LabeledCheckbox+ id={`cleanup-take-${title}`}+ checked={take}+ onChange={e => onChangeTake(e.target.checked)}+ >+ <span style={{ marginLeft: 6, fontSize: 12 }}>{takeLabel}</span>+ </LabeledCheckbox>++ {take && (+ <View style={{ marginLeft: 22, gap: 6 }}>+ {showOverspendOnly && (+ <LabeledCheckbox+ id={`cleanup-overspend-${title}`}+ checked={overspendOnly}+ onChange={e => onChangeOverspendOnly(e.target.checked)}+ >+ <span style={{ marginLeft: 6, fontSize: 12 }}>+ <Trans>Only enough to cover any overspending</Trans>+ </span>+ </LabeledCheckbox>+ )}+ {!overspendOnly && (+ <SpaceBetween align="center" gap={10}>+ <FormLabel+ title={t('Weight')}+ htmlFor={`cleanup-weight-${title}`}+ />+ <Input+ id={`cleanup-weight-${title}`}+ type="number"+ min={1}+ step={1}+ style={{ width: 80 }}+ value={String(weight)}+ onChangeValue={value => {+ const parsed = Math.max(1, Math.trunc(Number(value)) || 1);+ onChangeWeight(parsed);+ }}+ />+ </SpaceBetween>+ )}+ </View>+ )}+ </View>+ );+}diff --git a/packages/desktop-client/src/components/budget/goals/editor/CleanupAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/CleanupAutomationReadOnly.tsxnew file mode 100644index 0000000000..6996726b91--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/CleanupAutomationReadOnly.tsx@@ -0,0 +1,34 @@+import { Trans, useTranslation } from 'react-i18next';++import type { CleanupConfig } from '#components/budget/goals/cleanupModel';+import type { CleanupGroup } from '#hooks/useCleanupGroups';++type CleanupAutomationReadOnlyProps = {+ config: CleanupConfig;+ groups: CleanupGroup[];+};++export function CleanupAutomationReadOnly({+ config,+ groups,+}: CleanupAutomationReadOnlyProps) {+ const { t } = useTranslation();+ const isGlobal = config.global.send || config.global.take;+ const groupNames: string[] = [];+ for (const group of config.groups) {+ if (!group.send && !group.take) continue;+ const name =+ groups.find(g => g.id === group.groupId)?.name ?? t('Unknown pool');+ groupNames.push(name);+ }++ const total = (isGlobal ? 1 : 0) + groupNames.length;+ if (total === 0) return <Trans>No cleanup configured</Trans>;+ if (total > 1) {+ const count = total;+ return <Trans count={count}>Active in {{ count }} scopes</Trans>;+ }+ if (isGlobal) return <Trans>Active globally</Trans>;+ const scope = groupNames[0];+ return <Trans>Active in {{ scope }}</Trans>;+}diff --git a/packages/desktop-client/src/components/budget/goals/editor/CleanupGroupPicker.tsx b/packages/desktop-client/src/components/budget/goals/editor/CleanupGroupPicker.tsxnew file mode 100644index 0000000000..57cd2582dc--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/CleanupGroupPicker.tsx@@ -0,0 +1,154 @@+import { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { Input } from '@actual-app/components/input';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import type { CleanupGroup } from '#hooks/useCleanupGroups';++type CleanupGroupPickerProps = {+ id?: string;+ groups: CleanupGroup[];+ onSelect: (groupId: string) => void;+ onCreate: (name: string) => Promise<string>;+ placeholder?: string;+ autoFocus?: boolean;+};++export function CleanupGroupPicker({+ id,+ groups,+ onSelect,+ onCreate,+ placeholder,+ autoFocus,+}: CleanupGroupPickerProps) {+ const { t } = useTranslation();+ const [query, setQuery] = useState('');+ const [open, setOpen] = useState(false);+ const [highlight, setHighlight] = useState(0);+ const containerRef = useRef<HTMLDivElement>(null);++ const trimmed = query.trim();+ const matches = groups.filter(g =>+ g.name.toLowerCase().includes(trimmed.toLowerCase()),+ );+ const exact = matches.find(+ g => g.name.toLowerCase() === trimmed.toLowerCase(),+ );+ const showCreate = trimmed.length > 0 && !exact;+ type Item = { kind: 'group'; group: CleanupGroup } | { kind: 'create' };+ const items: Item[] = [+ ...matches.map(group => ({ kind: 'group' as const, group })),+ ...(showCreate ? [{ kind: 'create' as const }] : []),+ ];++ useEffect(() => {+ if (highlight >= items.length) setHighlight(Math.max(0, items.length - 1));+ }, [items.length, highlight]);++ useEffect(() => {+ if (!open) return;+ const handleClick = (e: MouseEvent) => {+ if (!containerRef.current?.contains(e.target as Node)) {+ setOpen(false);+ }+ };+ document.addEventListener('mousedown', handleClick);+ return () => document.removeEventListener('mousedown', handleClick);+ }, [open]);++ const pick = async (item: Item) => {+ if (item.kind === 'group') {+ onSelect(item.group.id);+ } else {+ const newId = await onCreate(trimmed);+ onSelect(newId);+ }+ setQuery('');+ setOpen(false);+ };++ return (+ <View ref={containerRef} style={{ position: 'relative' }}>+ <Input+ id={id}+ autoFocus={autoFocus}+ value={query}+ placeholder={placeholder ?? t('Type to search or create…')}+ onChangeValue={value => {+ setQuery(value);+ setOpen(true);+ setHighlight(0);+ }}+ onFocus={() => setOpen(true)}+ onKeyDown={e => {+ if (!open) return;+ if (e.key === 'ArrowDown') {+ e.preventDefault();+ setHighlight(h => Math.min(items.length - 1, h + 1));+ } else if (e.key === 'ArrowUp') {+ e.preventDefault();+ setHighlight(h => Math.max(0, h - 1));+ } else if (e.key === 'Enter' && items[highlight]) {+ e.preventDefault();+ void pick(items[highlight]);+ } else if (e.key === 'Escape') {+ setOpen(false);+ }+ }}+ />+ {open && items.length > 0 && (+ <View+ style={{+ position: 'absolute',+ top: '100%',+ left: 0,+ right: 0,+ marginTop: 2,+ backgroundColor: theme.menuBackground,+ border: `1px solid ${theme.menuBorder}`,+ borderRadius: 6,+ boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',+ zIndex: 10,+ maxHeight: 240,+ overflowY: 'auto',+ }}+ >+ {items.map((item, i) => {+ const active = i === highlight;+ const isCreate = item.kind === 'create';+ return (+ <View+ key={item.kind === 'group' ? item.group.id : '__create__'}+ onClick={() => void pick(item)}+ onMouseEnter={() => setHighlight(i)}+ style={{+ padding: '8px 10px',+ cursor: 'pointer',+ backgroundColor: active+ ? theme.menuAutoCompleteBackgroundHover+ : 'transparent',+ fontSize: 12,+ fontWeight: isCreate ? 500 : undefined,+ color: isCreate+ ? active+ ? theme.menuAutoCompleteTextHover+ : theme.noticeTextMenu+ : active+ ? theme.menuAutoCompleteTextHover+ : theme.menuItemText,+ }}+ >+ {item.kind === 'group'+ ? item.group.name+ : `+ ${t('Create "{{name}}"', { name: trimmed })}`}+ </View>+ );+ })}+ </View>+ )}+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationListRow.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationListRow.tsxindex 2817f9016a..1de3044da7 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationListRow.tsx+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationListRow.tsx@@ -77,7 +77,6 @@ export function AutomationListRow({alignItems: 'center',gap: 10,padding: 10,- marginBottom: 4,borderRadius: 6,border: `1px solid ${borderColor}`,backgroundColor,diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsxindex efe6f893b1..0d3c63fbe6 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsx+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsx@@ -1,8 +1,9 @@-import { useEffect, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import type { CSSProperties, ReactNode } from 'react';import { Trans } from 'react-i18next';import { Button } from '@actual-app/components/button';+import { SvgDelete } from '@actual-app/components/icons/v0';import { SvgInformationCircle } from '@actual-app/components/icons/v2';import { Text } from '@actual-app/components/text';import { theme } from '@actual-app/components/theme';@@ -13,6 +14,7 @@ import type {CategoryGroupEntity,ScheduleEntity,} from '@actual-app/core/types/models';+import type { CleanupTemplate } from '@actual-app/core/types/models/cleanup-templates';import { css } from '@emotion/css';import debounce from 'lodash/debounce';@@ -21,12 +23,21 @@ import {getAutomationExamples,} from '#components/budget/goals/automationExamples';import type { AutomationEntry } from '#components/budget/goals/automationExamples';+import {+ cleanupDefToEditor,+ editorToCleanupDef,+ emptyCleanupConfig,+ isCleanupConfigured,+} from '#components/budget/goals/cleanupModel';+import type { CleanupConfig } from '#components/budget/goals/cleanupModel';+import { CleanupAutomation } from '#components/budget/goals/editor/CleanupAutomation';import { formatMonthLabel } from '#components/budget/goals/formatMonthLabel';import {validateAutomation,validatePercentageAllocation,} from '#components/budget/goals/validateAutomation';import { Link } from '#components/common/Link';+import { useCleanupGroups } from '#hooks/useCleanupGroups';import { useFormat } from '#hooks/useFormat';import { useLocale } from '#hooks/useLocale';import { pushModal } from '#modals/modalsSlice';@@ -35,6 +46,7 @@ import { useDispatch } from '#redux';import { AutomationEditorPane } from './AutomationEditorPane';import { AutomationListRow } from './AutomationListRow';import { BudgetAutomationMigrationWarning } from './BudgetAutomationMigrationWarning';+import { CleanupListRow } from './CleanupListRow';import { ConflictBanner } from './ConflictBanner';import { EmptyState } from './EmptyState';import { NON_CONTRIBUTION_TYPES } from './TypePicker';@@ -99,7 +111,6 @@ function SidebarAddButton({style={{flexShrink: 0,width: '100%',- marginTop: 8,padding: 10,border: `1px dashed ${theme.tableBorder}`,borderRadius: 6,@@ -114,41 +125,40 @@ function SidebarAddButton({);}-function SidebarPlaceholderRow({ children }: { children: ReactNode }) {- return (- <View- style={{- flexShrink: 0,- padding: '8px 10px',- marginTop: 4,- borderRadius: 6,- border: `1px dashed ${theme.tableBorder}`,- color: theme.pageTextSubdued,- fontSize: 12,- opacity: 0.6,- }}- >- <Text>{children}</Text>- </View>- );-}-type BudgetAutomationsBodyProps = {categoryId: string;categoryName: string;needsMigration: boolean;initialEntries: AutomationEntry[];+ initialCleanup: CleanupTemplate[];schedules: readonly ScheduleEntity[];categories: CategoryGroupEntity[];month: string;onClose: () => void;};+type ActiveSelection = { kind: 'entry'; idx: number } | { kind: 'cleanup' };++function pickInitialSelection(+ entries: AutomationEntry[],+ cleanup: CleanupConfig,+): ActiveSelection {+ if (entries.length > 0) {+ const idx = entries.findIndex(+ e => !NON_CONTRIBUTION_TYPES.has(e.displayType),+ );+ return { kind: 'entry', idx: idx >= 0 ? idx : 0 };+ }+ if (isCleanupConfigured(cleanup)) return { kind: 'cleanup' };+ return { kind: 'entry', idx: 0 };+}+export function BudgetAutomationsBody({categoryId,categoryName,needsMigration,initialEntries,+ initialCleanup,schedules,categories,month,@@ -157,13 +167,14 @@ export function BudgetAutomationsBody({const dispatch = useDispatch();const format = useFormat();const locale = useLocale();+ const { groups: cleanupGroups, createGroup: createCleanupGroup } =+ useCleanupGroups();const [entries, setEntries] = useState<AutomationEntry[]>(initialEntries);- const initialContributionIdx = initialEntries.findIndex(- e => !NON_CONTRIBUTION_TYPES.has(e.displayType),- );- const [activeIdx, setActiveIdx] = useState(- initialContributionIdx >= 0 ? initialContributionIdx : 0,+ const initialCleanupConfig = cleanupDefToEditor(initialCleanup);+ const [cleanup, setCleanup] = useState<CleanupConfig>(initialCleanupConfig);+ const [active, setActive] = useState<ActiveSelection>(() =>+ pickInitialSelection(initialEntries, initialCleanupConfig),);const [saving, setSaving] = useState(false);const [dryRun, setDryRun] = useState<{@@ -179,7 +190,7 @@ export function BudgetAutomationsBody({if (!entry) return;setEntries(prev => {const next = [...prev, entry];- setActiveIdx(next.length - 1);+ setActive({ kind: 'entry', idx: next.length - 1 });return next;});};@@ -198,7 +209,7 @@ export function BudgetAutomationsBody({);setEntries(prev => {const next = [...prev, entry];- setActiveIdx(next.length - 1);+ setActive({ kind: 'entry', idx: next.length - 1 });return next;});};@@ -214,18 +225,30 @@ export function BudgetAutomationsBody({);setEntries(prev => {const next = [...prev, entry];- setActiveIdx(next.length - 1);+ setActive({ kind: 'entry', idx: next.length - 1 });return next;});};+ const onAddCleanup = () => {+ if (!isCleanupConfigured(cleanup)) setCleanup(emptyCleanupConfig());+ setActive({ kind: 'cleanup' });+ };++ const onDeleteCleanup = () => {+ setCleanup(emptyCleanupConfig());+ setActive({ kind: 'entry', idx: 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;+ setActive(currentActive => {+ if (currentActive.kind !== 'entry') return currentActive;+ if (next.length === 0) return { kind: 'entry', idx: 0 };+ const idx = currentActive.idx;+ if (idx >= next.length) return { kind: 'entry', idx: next.length - 1 };+ if (idx > index) return { kind: 'entry', idx: idx - 1 };return currentActive;});return next;@@ -239,7 +262,11 @@ export function BudgetAutomationsBody({const templatesToSave = entries.map(({ template }) => template);await send('budget/set-category-automations', {categoriesWithTemplates: [- { id: categoryId, templates: templatesToSave },+ {+ id: categoryId,+ templates: templatesToSave,+ cleanup: editorToCleanupDef(cleanup),+ },],source: 'ui',});@@ -257,13 +284,16 @@ export function BudgetAutomationsBody({options: {categoryId,templates: entries.map(({ template }) => template),+ cleanup: editorToCleanupDef(cleanup),},},}),);};- const templates = entries.map(e => e.template);+ // the react compiler wasn't memoising this properly and causing infinite+ // re-renders+ const templates = useMemo(() => entries.map(e => e.template), [entries]);const validPercentageSources = new Set<string>(['all income',@@ -338,7 +368,12 @@ export function BudgetAutomationsBody({);const optionEntries = indexedEntries.filter(({ entry }) => isOption(entry));- const safeActiveIdx = Math.min(activeIdx, Math.max(0, entries.length - 1));+ const safeActiveIdx =+ active.kind === 'entry'+ ? Math.min(active.idx, Math.max(0, entries.length - 1))+ : -1;+ const cleanupActive = active.kind === 'cleanup';+ const setActiveIdx = (idx: number) => setActive({ kind: 'entry', idx });return (<View style={{ flex: 1, flexDirection: 'column', minHeight: 0 }}>@@ -446,6 +481,7 @@ export function BudgetAutomationsBody({borderRight: `1px solid ${theme.tableBorder}`,padding: 10,overflowY: 'scroll',+ gap: 4,}}><SidebarSectionHeader>@@ -492,13 +528,63 @@ export function BudgetAutomationsBody({+ <Trans>Add long-term goal</Trans></SidebarAddButton>)}- <SidebarPlaceholderRow>- <Trans>End of month cleanup (coming soon)</Trans>- </SidebarPlaceholderRow>+ {isCleanupConfigured(cleanup) ? (+ <CleanupListRow+ config={cleanup}+ groups={cleanupGroups}+ isActive={cleanupActive}+ onSelect={() => setActive({ kind: 'cleanup' })}+ />+ ) : (+ <SidebarAddButton onPress={onAddCleanup}>+ + <Trans>Add end of month cleanup</Trans>+ </SidebarAddButton>+ )}</View><View style={{ flex: 1, minWidth: 0 }}>- {entries.length === 0 ? (+ {cleanupActive ? (+ <View+ style={{+ flex: 1,+ padding: 20,+ overflowY: 'auto',+ gap: 14,+ }}+ >+ <CleanupAutomation+ config={cleanup}+ groups={cleanupGroups}+ onChange={setCleanup}+ onCreateGroup={createCleanupGroup}+ />+ <View+ style={{ flexDirection: 'row', gap: 12, alignItems: 'center' }}+ >+ <View style={{ flex: 1 }} />+ <Button+ variant="bare"+ onPress={onDeleteCleanup}+ style={{ color: theme.errorText }}+ >+ <span+ style={{+ display: 'inline-flex',+ alignItems: 'center',+ gap: 6,+ }}+ >+ <SvgDelete+ width={10}+ height={10}+ style={{ color: 'inherit' }}+ />+ <Trans>Remove cleanup</Trans>+ </span>+ </Button>+ </View>+ </View>+ ) : entries.length === 0 ? (<EmptyState onAdd={onAddAutomation} />) : (<AutomationEditorPanediff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsxindex 8ad8243f23..c056c3b2f3 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx@@ -4,21 +4,19 @@ 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 { CleanupTemplate } from '@actual-app/core/types/models/cleanup-templates';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 { useCategoryCleanup } from '#hooks/useCategoryCleanup';import { useSchedules } from '#hooks/useSchedules';import { BudgetAutomationsBody } from './BudgetAutomationsBody';import { migrateTemplatesToAutomations } from './migrateTemplatesToAutomations';-import {- hasCleanupLine,- UnsupportedDirectivesNotice,-} from './UnsupportedDirectivesNotice';+import { UnsupportedDirectivesNotice } from './UnsupportedDirectivesNotice';const MODAL_WIDTH = 960;const MODAL_HEIGHT = 760;@@ -33,32 +31,45 @@ export function BudgetAutomationsModal({const [parsedTemplates, setParsedTemplates] = useState<Template[] | null>(null,);+ const [parsedCleanup, setParsedCleanup] = useState<CleanupTemplate[] | null>(+ null,+ );const effectiveMonth = month ?? currentMonth();const onLoaded = (result: Record<string, Template[]>) => {setParsedTemplates(result[categoryId] ?? []);};- const { loading } = useBudgetAutomations({ categoryId, onLoaded });+ const { data: currentCategory } = useCategory(categoryId);+ // default to 'ui' while the category is still resolving so we don't fire a+ // notes-mode migration on a category that may turn out to be ui-managed+ const needsMigration =+ currentCategory != null &&+ currentCategory.template_settings?.source !== 'ui';+ const source = needsMigration ? 'notes' : 'ui';++ const { loading: templatesLoading } = useBudgetAutomations({+ categoryId,+ source,+ 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 { loading: cleanupLoading } = useCategoryCleanup({+ categoryId,+ source,+ onLoaded: setParsedCleanup,+ });+ const loading = templatesLoading || cleanupLoading;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 =- hasErrorTemplate || hasSpendTemplate || hasCleanupDirective;+ const hasUnsupportedDirective = hasErrorTemplate || hasSpendTemplate;const incomeNameToId = new Map<string, string>();for (const group of categories) {@@ -94,7 +105,7 @@ export function BudgetAutomationsModal({>{({ state }) => (<View style={{ flex: 1, minHeight: 0 }}>- {loading || parsedTemplates === null ? (+ {loading || parsedTemplates === null || parsedCleanup === null ? (<Viewstyle={{flex: 1,@@ -107,7 +118,6 @@ export function BudgetAutomationsModal({) : hasUnsupportedDirective ? (<UnsupportedDirectivesNoticehasErrorTemplate={hasErrorTemplate}- hasSpendTemplate={hasSpendTemplate}onClose={() => state.close()}/>) : (@@ -116,6 +126,7 @@ export function BudgetAutomationsModal({categoryName={currentCategory?.name ?? ''}needsMigration={needsMigration}initialEntries={initialEntries ?? []}+ initialCleanup={parsedCleanup}schedules={schedules}categories={categories}month={effectiveMonth}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/CleanupListRow.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/CleanupListRow.tsxnew file mode 100644index 0000000000..907f7fa158--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/CleanupListRow.tsx@@ -0,0 +1,92 @@+import { Trans, useTranslation } from 'react-i18next';++import { SvgRefresh } from '@actual-app/components/icons/v1';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import type { CleanupConfig } from '#components/budget/goals/cleanupModel';+import { CleanupAutomationReadOnly } from '#components/budget/goals/editor/CleanupAutomationReadOnly';+import type { CleanupGroup } from '#hooks/useCleanupGroups';++type CleanupListRowProps = {+ config: CleanupConfig;+ groups: CleanupGroup[];+ isActive: boolean;+ onSelect: () => void;+};++export function CleanupListRow({+ config,+ groups,+ isActive,+ onSelect,+}: CleanupListRowProps) {+ const { t } = useTranslation();+ const borderColor = isActive ? theme.tableBorderSelected : 'transparent';+ const backgroundColor = isActive ? theme.upcomingBackground : 'transparent';++ return (+ <View+ role="button"+ tabIndex={0}+ onClick={onSelect}+ onKeyDown={e => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onSelect();+ }+ }}+ aria-label={t('Select cleanup')}+ style={{+ flexShrink: 0,+ flexDirection: 'row',+ alignItems: 'center',+ gap: 10,+ padding: 10,+ borderRadius: 6,+ border: `1px solid ${borderColor}`,+ backgroundColor,+ cursor: 'pointer',+ }}+ >+ <View+ style={{+ width: 28,+ height: 28,+ borderRadius: 6,+ backgroundColor: isActive+ ? theme.upcomingBackground+ : theme.pillBackground,+ color: isActive ? theme.pageTextPositive : theme.pageTextSubdued,+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ }}+ >+ <SvgRefresh width={14} height={14} style={{ color: 'inherit' }} />+ </View>+ <View style={{ minWidth: 0, flex: 1 }}>+ <Text+ style={{+ fontSize: 12,+ fontWeight: 600,+ color: theme.pageText,+ display: 'block',+ }}+ >+ <Trans>End of month cleanup</Trans>+ </Text>+ <Text+ style={{+ fontSize: 11,+ color: theme.pageTextSubdued,+ display: 'block',+ }}+ >+ <CleanupAutomationReadOnly config={config} groups={groups} />+ </Text>+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsxindex fa9fbe488b..87a7462952 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsx+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/UnsupportedDirectivesNotice.tsx@@ -8,11 +8,9 @@ import { View } from '@actual-app/components/view';export function UnsupportedDirectivesNotice({hasErrorTemplate,- hasSpendTemplate,onClose,}: {hasErrorTemplate: boolean;- hasSpendTemplate: boolean;onClose: () => void;}) {return (@@ -54,15 +52,9 @@ export function UnsupportedDirectivesNotice({notes couldn’t be parsed. Fix them as text first, then re-openthis 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>) : (<Trans>- This category uses a <code>#cleanup</code> directive, which the+ This category uses a <code>spend from</code> template, which thebudget automations UI doesn’t handle yet. Keep editing it astext in the category’s notes.</Trans>@@ -74,10 +66,3 @@ export function UnsupportedDirectivesNotice({</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/UnmigrateBudgetAutomationsModal.tsx b/packages/desktop-client/src/components/modals/UnmigrateBudgetAutomationsModal.tsxindex 20b6cc18d2..2242ff697f 100644--- a/packages/desktop-client/src/components/modals/UnmigrateBudgetAutomationsModal.tsx+++ b/packages/desktop-client/src/components/modals/UnmigrateBudgetAutomationsModal.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useState } from 'react';+import { useEffect, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';@@ -6,13 +6,16 @@ import { AnimatedLoading } from '@actual-app/components/icons/AnimatedLoading';import { SpaceBetween } from '@actual-app/components/space-between';import { View } from '@actual-app/components/view';import { send } from '@actual-app/core/platform/client/connection';+import type { CleanupTemplate } from '@actual-app/core/types/models/cleanup-templates';import type { Template } from '@actual-app/core/types/models/templates';+import { cleanupToNotes } from '#components/budget/goals/cleanupModel';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 { useCleanupGroups } from '#hooks/useCleanupGroups';import { useNotes } from '#hooks/useNotes';// The UI's CategoryAutocomplete stores the income category id on a@@ -34,13 +37,16 @@ function sanitizePercentageCategoriesForNotes(export function UnmigrateBudgetAutomationsModal({categoryId,templates,+ cleanup,}: {categoryId: string;templates: Template[];+ cleanup: CleanupTemplate[];}) {const { t } = useTranslation();const { data: category } = useCategory(categoryId);const { data: categoryData } = useCategories();+ const { groups: cleanupGroups } = useCleanupGroups();const existingNotes = useNotes(categoryId) || '';const [editedNotes, setEditedNotes] = useState<string>('');@@ -54,6 +60,8 @@ export function UnmigrateBudgetAutomationsModal({idToName.set(cat.id, cat.name);}const sanitized = sanitizePercentageCategoriesForNotes(templates, idToName);+ const groupName = (groupId: string) =>+ cleanupGroups.find(g => g.id === groupId)?.name ?? null;let mounted = true;void (async () => {try {@@ -61,7 +69,9 @@ export function UnmigrateBudgetAutomationsModal({'budget/render-note-templates',sanitized,);- if (mounted) setRendered(text);+ const cleanupText = cleanupToNotes(cleanup, groupName);+ const combined = [text, cleanupText].filter(Boolean).join('\n');+ if (mounted) setRendered(combined);} catch {if (mounted) setRendered('');}@@ -69,7 +79,7 @@ export function UnmigrateBudgetAutomationsModal({return () => {mounted = false;};- }, [templates, categoryData]);+ }, [templates, cleanup, categoryData, cleanupGroups]);// Seed editable notes once templates rendereduseEffect(() => {@@ -98,16 +108,17 @@ export function UnmigrateBudgetAutomationsModal({if (newLines.length === 0) {setEditedNotes(base);} else {- const needsNewline = base && !base.endsWith('\n') ? '\n' : '';+ const separator = base ? (base.endsWith('\n') ? '\n' : '\n\n') : '';setEditedNotes(base +- needsNewline +- '\nExport from automations UI:\n' ++ separator ++ t('Export from automations UI:') ++ '\n' +newLines.join('\n'),);}}- }, [rendered, existingNotes]);+ }, [rendered, existingNotes, t]);async function onSave(close: () => void) {setSaving(true);@@ -118,10 +129,13 @@ export function UnmigrateBudgetAutomationsModal({// 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: [] }],+ categoriesWithTemplates: [+ { id: categoryId, templates: [], cleanup: [] },+ ],source: 'notes',});await send('budget/store-note-templates');+ await send('budget/store-note-cleanups');close();} finally {setSaving(false);diff --git a/packages/desktop-client/src/hooks/useBudgetAutomations.ts b/packages/desktop-client/src/hooks/useBudgetAutomations.tsindex 2a420d29e0..75eda3c17a 100644--- a/packages/desktop-client/src/hooks/useBudgetAutomations.ts+++ b/packages/desktop-client/src/hooks/useBudgetAutomations.ts@@ -5,9 +5,11 @@ import type { Template } from '@actual-app/core/types/models/templates';export function useBudgetAutomations({categoryId,+ source,onLoaded,}: {categoryId: string;+ source: 'notes' | 'ui';onLoaded: (automations: Record<string, Template[]>) => void;}) {const [automations, setAutomations] = useState<Record<string, Template[]>>(@@ -20,8 +22,11 @@ export function useBudgetAutomations({async function fetchAutomations() {setLoading(true);- // Always import notes first; the query will automatically ignore UI-based categories.- await send('budget/store-note-templates');+ // notes based #template/#goal lines may have been edited since they were+ // last parsed into the DB. ui-managed categories own goal_def directly, so skip.+ if (source !== 'ui') {+ await send('budget/store-note-templates', [categoryId]);+ }const result = await send('budget/get-category-automations', categoryId);if (mounted) {@@ -34,7 +39,7 @@ export function useBudgetAutomations({return () => {mounted = false;};- }, [categoryId, onLoaded]);+ }, [categoryId, source, onLoaded]);return { automations, loading };}diff --git a/packages/desktop-client/src/hooks/useCategoryCleanup.ts b/packages/desktop-client/src/hooks/useCategoryCleanup.tsnew file mode 100644index 0000000000..7cb61edea4--- /dev/null+++ b/packages/desktop-client/src/hooks/useCategoryCleanup.ts@@ -0,0 +1,51 @@+import { useEffect, useState } from 'react';++import { send } from '@actual-app/core/platform/client/connection';+import { q } from '@actual-app/core/shared/query';+import type { CleanupTemplate } from '@actual-app/core/types/models/cleanup-templates';++import { aqlQuery } from '#queries/aqlQuery';++export function useCategoryCleanup({+ categoryId,+ source,+ onLoaded,+}: {+ categoryId: string;+ source: 'notes' | 'ui';+ onLoaded?: (cleanup: CleanupTemplate[]) => void;+}) {+ const [cleanup, setCleanup] = useState<CleanupTemplate[]>([]);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ let mounted = true;+ async function load() {+ setLoading(true);+ // notes based #cleanup lines may have been edited since they were last+ // parsed into the DB. ui-managed categories own cleanup_def directly, so skip.+ if (source !== 'ui') {+ await send('budget/store-note-cleanups', [categoryId]);+ }++ const result = await aqlQuery(+ q('categories').filter({ id: categoryId }).select(['cleanup_def']),+ );+ const row = Array.isArray(result.data) ? result.data[0] : null;+ const raw =+ row && typeof row.cleanup_def === 'string' ? row.cleanup_def : null;+ const parsed: CleanupTemplate[] = raw ? JSON.parse(raw) : [];+ if (mounted) {+ setCleanup(parsed);+ onLoaded?.(parsed);+ setLoading(false);+ }+ }+ void load();+ return () => {+ mounted = false;+ };+ }, [categoryId, source, onLoaded]);++ return { cleanup, loading };+}diff --git a/packages/desktop-client/src/hooks/useCleanupGroups.ts b/packages/desktop-client/src/hooks/useCleanupGroups.tsnew file mode 100644index 0000000000..c45171e45e--- /dev/null+++ b/packages/desktop-client/src/hooks/useCleanupGroups.ts@@ -0,0 +1,40 @@+import { useEffect, useState } from 'react';++import { send } from '@actual-app/core/platform/client/connection';+import { q } from '@actual-app/core/shared/query';++import { aqlQuery } from '#queries/aqlQuery';++export type CleanupGroup = { id: string; name: string };++export function useCleanupGroups() {+ const [groups, setGroups] = useState<CleanupGroup[]>([]);+ const [loading, setLoading] = useState(true);++ async function reload() {+ const result = await aqlQuery(+ q('cleanup_groups').filter({ tombstone: false }).select(['id', 'name']),+ );+ const rows = Array.isArray(result.data) ? result.data : [];+ setGroups(+ rows.flatMap(row =>+ row && typeof row.id === 'string' && typeof row.name === 'string'+ ? [{ id: row.id, name: row.name }]+ : [],+ ),+ );+ setLoading(false);+ }++ useEffect(() => {+ void reload();+ }, []);++ async function createGroup(name: string) {+ const { id } = await send('budget/create-cleanup-group', { name });+ await reload();+ return id;+ }++ return { groups, loading, createGroup };+}diff --git a/packages/desktop-client/src/modals/modalsSlice.ts b/packages/desktop-client/src/modals/modalsSlice.tsindex 7db2dc3105..c61088f62b 100644--- a/packages/desktop-client/src/modals/modalsSlice.ts+++ b/packages/desktop-client/src/modals/modalsSlice.ts@@ -16,6 +16,7 @@ import type {UserAccessEntity,UserEntity,} from '@actual-app/core/types/models';+import type { CleanupTemplate } from '@actual-app/core/types/models/cleanup-templates';import type { Template } from '@actual-app/core/types/models/templates';import { createSlice } from '@reduxjs/toolkit';import type { PayloadAction } from '@reduxjs/toolkit';@@ -644,6 +645,7 @@ export type Modal =options: {categoryId: CategoryEntity['id'];templates: Template[];+ cleanup: CleanupTemplate[];};};diff --git a/packages/loot-core/src/server/budget/app.ts b/packages/loot-core/src/server/budget/app.tsindex b05003345b..9b5b476c23 100644--- a/packages/loot-core/src/server/budget/app.ts+++ b/packages/loot-core/src/server/budget/app.ts@@ -14,7 +14,9 @@ import type { CategoryEntity, CategoryGroupEntity } from '#types/models';import * as actions from './actions';import * as budget from './base';+import * as cleanupGroupActions from './cleanup-groups';import * as cleanupActions from './cleanup-template';+import { storeNoteCleanups } from './cleanup-template-notes';import * as goalActions from './goal-template';import * as goalNoteActions from './template-notes';@@ -60,7 +62,9 @@ export type BudgetHandlers = {'budget/set-category-automations': typeof goalActions.storeTemplates;'budget/dry-run-category-template': typeof goalActions.dryRunCategoryTemplate;'budget/store-note-templates': typeof goalNoteActions.storeNoteTemplates;+ 'budget/store-note-cleanups': typeof storeNoteCleanups;'budget/render-note-templates': typeof goalNoteActions.unparse;+ 'budget/create-cleanup-group': typeof cleanupGroupActions.createCleanupGroup;};export const app = createApp<BudgetHandlers>();@@ -167,7 +171,12 @@ app.method('budget/store-note-templates',mutator(goalNoteActions.storeNoteTemplates),);+app.method('budget/store-note-cleanups', mutator(storeNoteCleanups));app.method('budget/render-note-templates', goalNoteActions.unparse);+app.method(+ 'budget/create-cleanup-group',+ mutator(undoable(cleanupGroupActions.createCleanupGroup)),+);// Server must return AQL entities not the raw DB dataasync function getCategories({ hidden }: { hidden?: boolean } = {}) {diff --git a/packages/loot-core/src/server/budget/cleanup-groups.ts b/packages/loot-core/src/server/budget/cleanup-groups.tsnew file mode 100644index 0000000000..ac1bcf5bd9--- /dev/null+++ b/packages/loot-core/src/server/budget/cleanup-groups.ts@@ -0,0 +1,54 @@+import { v4 as uuidv4 } from 'uuid';++import * as db from '#server/db';++export async function resolveCleanupGroup(name: string): Promise<string> {+ const trimmed = name.trim();+ if (trimmed.length === 0) {+ throw new Error('Cleanup group name cannot be empty');+ }+ const key = trimmed.toLowerCase();+ const existing = await db.first<{ id: string; tombstone: 0 | 1 }>(+ `SELECT id, tombstone FROM cleanup_groups WHERE lower(name) = ? LIMIT 1`,+ [key],+ );+ if (existing) {+ if (existing.tombstone) {+ await db.update('cleanup_groups', { id: existing.id, tombstone: 0 });+ }+ return existing.id;+ }+ const id = uuidv4();+ await db.insertWithSchema('cleanup_groups', {+ id,+ name: trimmed,+ tombstone: 0,+ });+ return id;+}++export async function createCleanupGroup({+ name,+}: {+ name: string;+}): Promise<{ id: string }> {+ const id = await resolveCleanupGroup(name);+ return { id };+}++export async function tombstoneOrphanCleanupGroups(): Promise<void> {+ await db.run(+ `+ UPDATE cleanup_groups+ SET tombstone = 1+ WHERE tombstone = 0+ AND id NOT IN (+ SELECT json_extract(je.value, '$.groupId') AS group_id+ FROM categories c, json_each(c.cleanup_def) je+ WHERE c.tombstone = 0+ AND c.cleanup_def IS NOT NULL+ AND json_extract(je.value, '$.groupId') IS NOT NULL+ )+ `,+ );+}diff --git a/packages/loot-core/src/server/budget/cleanup-template-notes.ts b/packages/loot-core/src/server/budget/cleanup-template-notes.tsindex f7c5e68c6b..c1757ab007 100644--- a/packages/loot-core/src/server/budget/cleanup-template-notes.ts+++ b/packages/loot-core/src/server/budget/cleanup-template-notes.ts@@ -1,8 +1,10 @@-import { v4 as uuidv4 } from 'uuid';-import * as db from '#server/db';import type { CleanupTemplate } from '#types/models/cleanup-templates';+import {+ resolveCleanupGroup,+ tombstoneOrphanCleanupGroups,+} from './cleanup-groups';import { parse } from './cleanup-template.pegjs';export const CLEANUP_PREFIX = '#cleanup ';@@ -121,43 +123,12 @@ async function resolveCleanupGroups(): Promise<Map<string, string>> {const map = new Map<string, string>();for (const name of names) {- const key = name.toLowerCase();- const existing = await db.first<{ id: string; tombstone: 0 | 1 }>(- `SELECT id, tombstone FROM cleanup_groups WHERE lower(name) = ? LIMIT 1`,- [key],- );- if (existing) {- // Resurrect a tombstoned row so the id stays stable across edits.- if (existing.tombstone === 1) {- await db.update('cleanup_groups', { id: existing.id, tombstone: 0 });- }- map.set(key, existing.id);- continue;- }- const id = uuidv4();- await db.insertWithSchema('cleanup_groups', { id, name, tombstone: 0 });- map.set(key, id);+ const id = await resolveCleanupGroup(name);+ map.set(name.toLowerCase(), id);}return map;}-async function tombstoneOrphanCleanupGroups(): Promise<void> {- await db.run(- `- UPDATE cleanup_groups- SET tombstone = 1- WHERE tombstone = 0- AND id NOT IN (- SELECT json_extract(je.value, '$.groupId') AS group_id- FROM categories c, json_each(c.cleanup_def) je- WHERE c.tombstone = 0- AND c.cleanup_def IS NOT NULL- AND json_extract(je.value, '$.groupId') IS NOT NULL- )- `,- );-}-// Scoped to non-ui-managed categories so a migrated category is not// overwritten by stale note text.async function getCategoriesWithCleanupNotes(diff --git a/packages/loot-core/src/server/budget/goal-template.ts b/packages/loot-core/src/server/budget/goal-template.tsindex f9ffd87f34..dee1bd87d6 100644--- a/packages/loot-core/src/server/budget/goal-template.ts+++ b/packages/loot-core/src/server/budget/goal-template.ts@@ -5,11 +5,12 @@ import { batchMessages } from '#server/sync';import * as monthUtils from '#shared/months';import { q } from '#shared/query';import type { CategoryEntity, CategoryGroupEntity } from '#types/models';+import type { CleanupTemplate } from '#types/models/cleanup-templates';import type { Template } from '#types/models/templates';import { getSheetValue, isTrackingBudget, setBudget, setGoal } from './actions';import { CategoryTemplateContext } from './category-template-context';-import { storeNoteCleanups } from './cleanup-template-notes';+import { tombstoneOrphanCleanupGroups } from './cleanup-groups';import { checkTemplateNotes, storeNoteTemplates } from './template-notes';export function distributeRemainder(@@ -48,21 +49,30 @@ export async function storeTemplates({categoriesWithTemplates: {id: string;templates: Template[];+ cleanup?: CleanupTemplate[];}[];source: 'notes' | 'ui';}): Promise<void> {- await storeNoteCleanups(categoriesWithTemplates.map(c => c.id));+ let touchedCleanup = false;await batchMessages(async () => {- for (const { id, templates } of categoriesWithTemplates) {+ for (const { id, templates, cleanup } of categoriesWithTemplates) {const goalDefs = templates.length > 0 ? JSON.stringify(templates) : null;-- await db.updateWithSchema('categories', {+ const update: Record<string, unknown> = {id,goal_def: goalDefs,template_settings: { source },- });+ };+ if (cleanup !== undefined) {+ update.cleanup_def =+ cleanup.length > 0 ? JSON.stringify(cleanup) : null;+ touchedCleanup = true;+ }+ await db.updateWithSchema('categories', update);}});+ if (touchedCleanup) {+ await tombstoneOrphanCleanupGroups();+ }}export async function applyTemplate({diff --git a/packages/loot-core/src/server/budget/statements.ts b/packages/loot-core/src/server/budget/statements.tsindex 08ac15d3b3..e91be5bba5 100644--- a/packages/loot-core/src/server/budget/statements.ts+++ b/packages/loot-core/src/server/budget/statements.ts@@ -3,7 +3,13 @@ import type { DbSchedule } from '#server/db';import { GOAL_PREFIX, TEMPLATE_PREFIX } from './template-notes';-export async function resetCategoryGoalDefsWithNoTemplates(): Promise<void> {+export async function resetCategoryGoalDefsWithNoTemplates(+ categoryIds?: string[],+): Promise<void> {+ if (categoryIds?.length === 0) return;+ const scopeClause = categoryIds+ ? `AND id IN (${categoryIds.map(() => '?').join(',')})`+ : '';await db.run(`UPDATE categories@@ -13,7 +19,9 @@ export async function resetCategoryGoalDefsWithNoTemplates(): Promise<void> {WHERE lower(note) LIKE '%${TEMPLATE_PREFIX}%'OR lower(note) LIKE '%${GOAL_PREFIX}%')AND COALESCE(JSON_EXTRACT(template_settings, '$.source'), 'notes') <> 'ui'+ ${scopeClause}`,+ categoryIds ?? [],);}@@ -23,9 +31,13 @@ export type CategoryWithTemplateNote = {note: string;};-export async function getCategoriesWithTemplateNotes(): Promise<- CategoryWithTemplateNote[]-> {+export async function getCategoriesWithTemplateNotes(+ categoryIds?: string[],+): Promise<CategoryWithTemplateNote[]> {+ if (categoryIds?.length === 0) return [];+ const scopeClause = categoryIds+ ? `AND c.id IN (${categoryIds.map(() => '?').join(',')})`+ : '';return await db.all<Pick<db.DbCategory, 'id' | 'name'> & Pick<db.DbNote, 'note'>>(@@ -38,7 +50,9 @@ export async function getCategoriesWithTemplateNotes(): Promise<AND COALESCE(JSON_EXTRACT(c.template_settings, '$.source'), 'notes') <> 'ui'AND (lower(note) LIKE '%${TEMPLATE_PREFIX}%'OR lower(note) LIKE '%${GOAL_PREFIX}%')+ ${scopeClause}`,+ categoryIds ?? [],);}diff --git a/packages/loot-core/src/server/budget/template-notes.ts b/packages/loot-core/src/server/budget/template-notes.tsindex 65ddc0644d..dc1cb6602b 100644--- a/packages/loot-core/src/server/budget/template-notes.ts+++ b/packages/loot-core/src/server/budget/template-notes.ts@@ -19,12 +19,14 @@ type Notification = {export const TEMPLATE_PREFIX = '#template';export const GOAL_PREFIX = '#goal';-export async function storeNoteTemplates(): Promise<void> {- const categoriesWithTemplates = await getCategoriesWithTemplates();+export async function storeNoteTemplates(+ categoryIds?: string[],+): Promise<void> {+ const categoriesWithTemplates = await getCategoriesWithTemplates(categoryIds);await storeTemplates({ categoriesWithTemplates, source: 'notes' });- await resetCategoryGoalDefsWithNoTemplates();+ await resetCategoryGoalDefsWithNoTemplates(categoryIds);}type CategoryWithTemplateNotes = {@@ -71,11 +73,11 @@ export async function checkTemplateNotes(): Promise<Notification> {};}-async function getCategoriesWithTemplates(): Promise<- CategoryWithTemplateNotes[]-> {+async function getCategoriesWithTemplates(+ categoryIds?: string[],+): Promise<CategoryWithTemplateNotes[]> {const templatesForCategory: CategoryWithTemplateNotes[] = [];- const templateNotes = await getCategoriesWithTemplateNotes();+ const templateNotes = await getCategoriesWithTemplateNotes(categoryIds);templateNotes.forEach(({ id, name, note }: CategoryWithTemplateNote) => {if (!note) {diff --git a/upcoming-release-notes/7815.md b/upcoming-release-notes/7815.mdnew file mode 100644index 0000000000..cfa418261d--- /dev/null+++ b/upcoming-release-notes/7815.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [matt-fidd]+---++Automation UI: add end-of-month cleanup functionality