A local-first personal finance app
automation UI: reference schedule by ID not name (#8308)
Matt Fiddamanb134a132f0fe
diff --git a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsxindex 53ec0e714a..d0dd8a7501 100644--- a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx@@ -59,16 +59,21 @@ export const ScheduleAutomation = ({id="schedule-field"key="schedule-picker"defaultLabel={t('Select a schedule')}- value={template.name}- onChange={schedule =>+ value={+ template.scheduleId ??+ selectableSchedules.find(s => s.name === template.name)?.id+ }+ onChange={scheduleId => {+ const picked = selectableSchedules.find(s => s.id === scheduleId);dispatch(updateTemplate({type: 'schedule',- name: schedule,+ scheduleId,+ name: picked?.name ?? '',}),- )- }- options={selectableSchedules.map(s => [s.name, s.name] as const)}+ );+ }}+ options={selectableSchedules.map(s => [s.id, s.name] as const)}/></FormField><FormField style={{ flex: fieldFlex }}>diff --git a/packages/desktop-client/src/components/budget/goals/validateAutomation.ts b/packages/desktop-client/src/components/budget/goals/validateAutomation.tsindex fadb3bc8fa..276c512359 100644--- a/packages/desktop-client/src/components/budget/goals/validateAutomation.ts+++ b/packages/desktop-client/src/components/budget/goals/validateAutomation.ts@@ -46,20 +46,24 @@ export function validateAutomation(validPercentageSources?: ReadonlySet<string>,): AutomationErrorKind | null {switch (displayType) {- case 'schedule':+ case 'schedule': {if (template.type !== 'schedule') return null;- if (!template.name) return { kind: 'schedule-not-found', name: '' };- if (- !schedules.some(- s => s.name === template.name && !s.completed && !s.tombstone,- )- ) {- return { kind: 'schedule-not-found', name: template.name };+ if (!template.scheduleId && !template.name) {+ return { kind: 'schedule-not-found', name: '' };+ }+ const match = schedules.find(s =>+ template.scheduleId+ ? s.id === template.scheduleId+ : s.name === template.name,+ );+ if (!match || match.completed || match.tombstone) {+ return { kind: 'schedule-not-found', name: template.name ?? '' };}if (isAdjustmentOutOfRange(template)) {return { kind: 'adjustment-out-of-range' };}return null;+ }case 'historical':if (isAdjustmentOutOfRange(template)) {return { kind: 'adjustment-out-of-range' };diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.test.ts b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.test.tsindex dd587731d0..1952d14b04 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.test.ts+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.test.ts@@ -1,7 +1,27 @@+import type { ScheduleEntity } from '@actual-app/core/types/models';import type { Template } from '@actual-app/core/types/models/templates';import { migrateTemplatesToAutomations } from './migrateTemplatesToAutomations';+function schedule(id: string, name: string): ScheduleEntity {+ return {+ id,+ name,+ rule: 'rule-1',+ next_date: '2026-01-01',+ completed: false,+ posts_transaction: false,+ tombstone: false,+ _payee: 'payee-1',+ _account: 'account-1',+ _amount: 0,+ _amountOp: 'is',+ _date: '2026-01-01',+ _conditions: [],+ _actions: [],+ };+}+describe('migrateTemplatesToAutomations', () => {it('drops simple templates that have no limit and no monthly amount', () => {// these would otherwise be pushed as a phantom 'fixed' entry that@@ -268,4 +288,60 @@ describe('migrateTemplatesToAutomations', () => {expect(result[0].displayType).toBe('schedule');expect(result[0].template).toEqual(scheduleTemplate);});++ it('fills in scheduleId for a name-only schedule template', () => {+ const scheduleTemplate = {+ type: 'schedule',+ directive: 'template',+ priority: 1,+ name: 'Rent',+ } satisfies Template;++ const result = migrateTemplatesToAutomations(+ [scheduleTemplate],+ [schedule('sched-1', 'Rent')],+ );++ expect(result[0].template).toMatchObject({+ scheduleId: 'sched-1',+ name: 'Rent',+ });+ });++ it('refreshes a stale name from scheduleId after a rename', () => {+ const scheduleTemplate = {+ type: 'schedule',+ directive: 'template',+ priority: 1,+ scheduleId: 'sched-1',+ name: 'Old Name',+ } satisfies Template;++ const result = migrateTemplatesToAutomations(+ [scheduleTemplate],+ [schedule('sched-1', 'New Name')],+ );++ expect(result[0].template).toMatchObject({+ scheduleId: 'sched-1',+ name: 'New Name',+ });+ });++ it('leaves a schedule template untouched when no schedule matches', () => {+ const scheduleTemplate = {+ type: 'schedule',+ directive: 'template',+ priority: 1,+ scheduleId: 'missing',+ name: 'Gone',+ } satisfies Template;++ const result = migrateTemplatesToAutomations(+ [scheduleTemplate],+ [schedule('sched-1', 'Rent')],+ );++ expect(result[0].template).toEqual(scheduleTemplate);+ });});diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsxindex 4629052b13..f2c0bf887c 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx@@ -57,7 +57,9 @@ export function BudgetAutomationsModal({onLoaded,});- const { schedules } = useSchedules({ query: q('schedules').select('*') });+ const { schedules, isLoading: schedulesLoading } = useSchedules({+ query: q('schedules').select('*'),+ });const categories = useBudgetAutomationCategories();@@ -66,7 +68,7 @@ export function BudgetAutomationsModal({source,onLoaded: setParsedCleanup,});- const loading = templatesLoading || cleanupLoading;+ const loading = templatesLoading || cleanupLoading || schedulesLoading;const hasErrorTemplate =parsedTemplates?.some(t => t.type === 'error') ?? false;@@ -85,7 +87,7 @@ export function BudgetAutomationsModal({});const initialEntries =resolved && !hasUnsupportedDirective- ? migrateTemplatesToAutomations(resolved)+ ? migrateTemplatesToAutomations(resolved, schedules): null;return (diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.tsindex 35e0065330..9ebf0e224f 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts@@ -1,5 +1,9 @@import { dayFromDate, firstDayOfMonth } from '@actual-app/core/shared/months';-import type { Template } from '@actual-app/core/types/models/templates';+import type { ScheduleEntity } from '@actual-app/core/types/models';+import type {+ ScheduleTemplate,+ Template,+} from '@actual-app/core/types/models/templates';import { createAutomationEntry } from '#components/budget/goals/automationExamples';import type { AutomationEntry } from '#components/budget/goals/automationExamples';@@ -39,12 +43,42 @@ function getDisplayTypeFromTemplate(template: Template): DisplayTemplateType {}}+// Fill in scheduleId from name (or refresh a stale name from scheduleId) so+// the editor and engine consistently see both.+function hydrateScheduleTemplate(+ template: ScheduleTemplate,+ schedules: readonly ScheduleEntity[],+): ScheduleTemplate {+ const schedule = template.scheduleId+ ? schedules.find(s => s.id === template.scheduleId)+ : template.name+ ? schedules.find(s => s.name?.trim() === template.name?.trim())+ : undefined;+ if (!schedule) return template;+ return {+ ...template,+ scheduleId: schedule.id,+ name: schedule.name ?? template.name,+ };+}+export function migrateTemplatesToAutomations(templates: Template[],+ schedules: readonly ScheduleEntity[] = [],): AutomationEntry[] {const entries: AutomationEntry[] = [];templates.forEach(template => {+ if (template.type === 'schedule') {+ entries.push(+ createAutomationEntry(+ hydrateScheduleTemplate(template, schedules),+ 'schedule',+ ),+ );+ return;+ }+if (template.type === 'simple') {const monthly = template.monthly;const hasMonthly = monthly != null && monthly !== 0;diff --git a/packages/desktop-client/src/hooks/useCategoryScheduleGoalTemplates.ts b/packages/desktop-client/src/hooks/useCategoryScheduleGoalTemplates.tsindex 93585de01e..e836e13f54 100644--- a/packages/desktop-client/src/hooks/useCategoryScheduleGoalTemplates.ts+++ b/packages/desktop-client/src/hooks/useCategoryScheduleGoalTemplates.ts@@ -12,7 +12,8 @@ import type { ScheduleStatusLabels } from './useSchedules';type ScheduleGoalDefinition = {type: 'schedule';- name: ScheduleEntity['name'];+ name?: ScheduleEntity['name'];+ scheduleId?: ScheduleEntity['id'];};type UseCategoryScheduleGoalTemplatesProps = {@@ -69,7 +70,9 @@ export function useCategoryScheduleGoalTemplates({}const schedules = allSchedules.filter(s =>- scheduleGoalDefinitions.some(g => g.name === s.name),+ scheduleGoalDefinitions.some(g =>+ g.scheduleId ? g.scheduleId === s.id : g.name === s.name,+ ),);const scheduleIds = new Set(schedules.map(s => s.id));diff --git a/packages/loot-core/src/server/budget/category-template-context.ts b/packages/loot-core/src/server/budget/category-template-context.tsindex a03bb3ed52..609f46dbf6 100644--- a/packages/loot-core/src/server/budget/category-template-context.ts+++ b/packages/loot-core/src/server/budget/category-template-context.ts@@ -15,6 +15,7 @@ import type {PeriodicTemplate,RefillTemplate,RemainderTemplate,+ ScheduleTemplate,SimpleTemplate,SpendTemplate,Template,@@ -159,7 +160,7 @@ export class CategoryTemplateContext {let byFlag = false;let remainder = 0;let scheduleFlag = false;- let schedulePerTemplate: Map<string, number> | null = null;+ let schedulePerTemplate: Map<ScheduleTemplate, number> | null = null;let byPerTemplate: Map<ByTemplate, number> | null = null;// switch on template type and calculate the amount for the linefor (const template of t) {@@ -263,7 +264,7 @@ export class CategoryTemplateContext {// schedule's real cost rather than an equal split.redistributeBatch(perTemplateLocal, t, 'schedule', template => {if (template.type !== 'schedule') return 0;- const monthly = schedulePerTemplate?.get(template.name.trim()) ?? 0;+ const monthly = schedulePerTemplate?.get(template) ?? 0;return Math.max(0, monthly);});@@ -477,15 +478,27 @@ export class CategoryTemplateContext {) {return;}- //check schedule names- const scheduleNames = (await getActiveSchedules()).map(({ name }) =>- name.trim(),+ //check schedule existence (prefer scheduleId, fall back to name)+ const activeSchedules = await getActiveSchedules();+ const scheduleIds = new Set(activeSchedules.map(s => s.id));+ const scheduleNames = new Set(+ activeSchedules.map(s => s.name?.trim()).filter(Boolean),);templates.filter(t => t.type === 'schedule').forEach(t => {- if (!scheduleNames.includes(t.name.trim())) {- throw new Error(`Schedule ${t.name.trim()} does not exist`);+ if (t.scheduleId) {+ if (!scheduleIds.has(t.scheduleId)) {+ throw new Error(+ `Schedule ${t.name ?? t.scheduleId} does not exist`,+ );+ }+ } else if (t.name) {+ if (!scheduleNames.has(t.name.trim())) {+ throw new Error(`Schedule ${t.name.trim()} does not exist`);+ }+ } else {+ throw new Error('Schedule template has no scheduleId or name');}});//find lowest prioritydiff --git a/packages/loot-core/src/server/budget/schedule-template.test.ts b/packages/loot-core/src/server/budget/schedule-template.test.tsindex 21ab50ca95..0bca932015 100644--- a/packages/loot-core/src/server/budget/schedule-template.test.ts+++ b/packages/loot-core/src/server/budget/schedule-template.test.ts@@ -169,7 +169,7 @@ describe('runSchedule', () => {expect(result.remainder).toBe(0);});- it('returns a per-template monthly attribution map keyed by trimmed template name', async () => {+ it('returns a per-template monthly attribution map keyed by template', async () => {const template_lines = [{type: 'schedule',@@ -196,7 +196,7 @@ describe('runSchedule', () => {defaultCurrency,);- expect(result.perScheduleMonthly.get('Test Schedule')).toBe(10000);+ expect(result.perScheduleMonthly.get(template_lines[0])).toBe(10000);expect(result.to_budget).toBe(10000);});@@ -237,8 +237,8 @@ describe('runSchedule', () => {);expect(result.errors).toHaveLength(0);- const internet = result.perScheduleMonthly.get('Internet') ?? 0;- const insurance = result.perScheduleMonthly.get('Insurance') ?? 0;+ const internet = result.perScheduleMonthly.get(template_lines[0]) ?? 0;+ const insurance = result.perScheduleMonthly.get(template_lines[1]) ?? 0;expect(internet).toBe(10000); // pay-month-of: full targetexpect(insurance).toBeGreaterThan(0);expect(insurance).toBeLessThan(internet);@@ -273,7 +273,7 @@ describe('runSchedule', () => {defaultCurrency,);expect(result.to_budget).toBe(0);- expect(result.perScheduleMonthly.get('Insurance')).toBeUndefined();+ expect(result.perScheduleMonthly.get(template_lines[0])).toBeUndefined();});it('only attributes contribution to schedules occurring this month when full: true is used', async () => {@@ -315,8 +315,8 @@ describe('runSchedule', () => {);expect(result.to_budget).toBe(10000);- expect(result.perScheduleMonthly.get('Schedule A')).toBe(10000);- expect(result.perScheduleMonthly.get('Schedule B')).toBeUndefined();+ expect(result.perScheduleMonthly.get(template_lines[0])).toBe(10000);+ expect(result.perScheduleMonthly.get(template_lines[1])).toBeUndefined();});it('applies a percent adjustment to the schedule amount', async () => {diff --git a/packages/loot-core/src/server/budget/schedule-template.ts b/packages/loot-core/src/server/budget/schedule-template.tsindex 4b4c23bd84..4faf40a9b1 100644--- a/packages/loot-core/src/server/budget/schedule-template.ts+++ b/packages/loot-core/src/server/budget/schedule-template.ts@@ -18,6 +18,7 @@ import type { ScheduleTemplate, Template } from '#types/models/templates';import { getSheetValue, isTrackingBudget } from './actions';type ScheduleTemplateTarget = {+ template: ScheduleTemplate;name: string;target: number;next_date_string: string;@@ -41,11 +42,18 @@ async function createScheduleList(const accountsMap = new Map(accounts.map(a => [a.id, a]));for (const template of templates) {- const { id: sid, completed } = await db.first<- Pick<db.DbSchedule, 'id' | 'completed'>- >(- 'SELECT id, completed FROM schedules WHERE TRIM(name) = ? AND tombstone = 0',- [template.name],+ // Prefer scheduleId so renames don't break the lookup; fall back to name+ // for notes-source templates (and legacy ui-source data) that only carry+ // the name.+ const {+ id: sid,+ name: scheduleName,+ completed,+ } = await db.first<Pick<db.DbSchedule, 'id' | 'name' | 'completed'>>(+ template.scheduleId+ ? 'SELECT id, name, completed FROM schedules WHERE id = ? AND tombstone = 0'+ : 'SELECT id, name, completed FROM schedules WHERE TRIM(name) = ? AND tombstone = 0',+ [template.scheduleId ?? template.name],);const rule = await getRuleForSchedule(sid);const conditions = rule.serialize().conditions;@@ -134,11 +142,13 @@ async function createScheduleList(next_date_string,current_month,);+ const displayName = scheduleName ?? template.name ?? '';if (num_months < 0) {//non-repeating schedules could be negative- errors.push(`Schedule ${template.name} is in the Past.`);+ errors.push(`Schedule ${displayName} is in the Past.`);} else {t.push({+ template,target,next_date_string,target_interval,@@ -148,7 +158,7 @@ async function createScheduleList(//started,full: template.full === null ? false : template.full,repeat: isRepeating,- name: template.name,+ name: displayName,});if (!completed) {if (isRepeating) {@@ -200,7 +210,7 @@ async function createScheduleList(}} else {errors.push(- `Schedule ${template.name} is not active during the month in question.`,+ `Schedule ${displayName} is not active during the month in question.`,);}}@@ -227,7 +237,7 @@ function getSinkingContributionBreakdown(// contribution so the caller can attribute the batch back to individual// templates. Total math is unchanged.let total = 0;- const perSchedule = new Map<string, number>();+ const perSchedule = new Map<ScheduleTemplate, number>();for (const [index, schedule] of t.entries()) {remainder =index === 0@@ -244,8 +254,8 @@ function getSinkingContributionBreakdown(const contribution = tg / (schedule.num_months + 1);total += contribution;perSchedule.set(- schedule.name.trim(),- (perSchedule.get(schedule.name.trim()) ?? 0) + contribution,+ schedule.template,+ (perSchedule.get(schedule.template) ?? 0) + contribution,);}return { total, perSchedule };@@ -353,14 +363,14 @@ export async function runSchedule(// haven't been paid yet, or if we can use the leftover balance for this month// First option: check if the previous month doesn't have its monthly schedules paid yet// Second option: check if the previous month needed less than this month and hasn't paid yet- // Accumulate per-schedule contributions (keyed by trimmed template name) so+ // Accumulate per-schedule contributions, keyed by the source template, so// callers can attribute the batched to_budget back to individual schedule// templates for UI projections.- const perScheduleMonthly = new Map<string, number>();- const addContribution = (name: string, amount: number) => {+ const perScheduleMonthly = new Map<ScheduleTemplate, number>();+ const addContribution = (template: ScheduleTemplate, amount: number) => {perScheduleMonthly.set(- name.trim(),- (perScheduleMonthly.get(name.trim()) ?? 0) + amount,+ template,+ (perScheduleMonthly.get(template) ?? 0) + amount,);};@@ -374,11 +384,11 @@ export async function runSchedule(to_budget += Math.round(totalPayMonthOf + totalSinkingBaseContribution);for (const c of t_payMonthOf) {if (c.num_months === 0) {- addContribution(c.name, c.target);+ addContribution(c.template, c.target);}}for (const c of t_sinking) {- addContribution(c.name, getMonthlyBaseContribution(c));+ addContribution(c.template, getMonthlyBaseContribution(c));}} else {const { total: totalSinkingContribution, perSchedule: sinkingPerSchedule } =@@ -392,11 +402,11 @@ export async function runSchedule(}for (const c of t_payMonthOf) {if (c.num_months === 0) {- addContribution(c.name, c.target);+ addContribution(c.template, c.target);}}- for (const [name, amount] of sinkingPerSchedule) {- addContribution(name, amount);+ for (const [template, amount] of sinkingPerSchedule) {+ addContribution(template, amount);}}return { to_budget, errors, remainder, perScheduleMonthly };diff --git a/packages/loot-core/src/server/budget/template-notes.ts b/packages/loot-core/src/server/budget/template-notes.tsindex 33d8b66931..9b9a500ea9 100644--- a/packages/loot-core/src/server/budget/template-notes.ts+++ b/packages/loot-core/src/server/budget/template-notes.ts@@ -53,6 +53,7 @@ export async function checkTemplateNotes(): Promise<Notification> {}} else if (template.type === 'schedule' &&+ template.name &&!scheduleNames.includes(template.name)) {errors.push(`${name}: Schedule "${template.name}" does not exist`);diff --git a/packages/loot-core/src/types/models/templates.ts b/packages/loot-core/src/types/models/templates.tsindex 2b2ddaad4a..b71f7ccac2 100644--- a/packages/loot-core/src/types/models/templates.ts+++ b/packages/loot-core/src/types/models/templates.ts@@ -62,7 +62,8 @@ export type SimpleTemplate = {export type ScheduleTemplate = {type: 'schedule';- name: string;+ name?: string;+ scheduleId?: string;full?: boolean;adjustment?: number;adjustmentType?: 'percent' | 'fixed';diff --git a/upcoming-release-notes/schedule-automation-id.md b/upcoming-release-notes/schedule-automation-id.mdnew file mode 100644index 0000000000..617536685e--- /dev/null+++ b/upcoming-release-notes/schedule-automation-id.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [matt-fidd]+---++Budget automations now link to schedules by ID, so they still remain linked when a schedule is renamed