A local-first personal finance app
[AI] Fix scheduled split transfer previews (#8699)
JerryNee435f2d51ee31
diff --git a/packages/desktop-client/e2e/schedules.test.ts b/packages/desktop-client/e2e/schedules.test.tsindex 3975553a81..66e9ac2deb 100644--- a/packages/desktop-client/e2e/schedules.test.ts+++ b/packages/desktop-client/e2e/schedules.test.ts@@ -85,6 +85,99 @@ test.describe('Schedules', () => {await expect(page).toMatchThemeScreenshots();});+ test('shows a scheduled split transfer in its destination account', async () => {+ await page.evaluate(async () => {+ const $send = (+ window as unknown as {+ $send: <T>(type: string, args?: unknown) => Promise<T>;+ }+ ).$send;+ const query = <T>(+ table: string,+ filterExpressions: unknown[],+ selectExpressions: string[],+ ) =>+ $send<{ data: T[] }>('query', {+ table,+ tableOptions: {},+ filterExpressions,+ selectExpressions,+ groupExpressions: [],+ orderExpressions: [],+ calculation: false,+ rawMode: false,+ withDead: false,+ validateRefs: true,+ limit: null,+ offset: null,+ });++ const {+ data: [destinationAccount],+ } = await query<{ id: string }>(+ 'accounts',+ [{ name: 'Ally Savings' }],+ ['id'],+ );+ const {+ data: [destinationPayee],+ } = await query<{ id: string }>(+ 'payees',+ [{ transfer_acct: destinationAccount.id }],+ ['id'],+ );+ const {+ data: [schedule],+ } = await query<{ rule: string }>(+ 'schedules',+ [{ name: 'Phone bills' }],+ ['rule'],+ );+ const rule = await $send<{+ actions: unknown[];+ conditions: unknown[];+ conditionsOp: 'and' | 'or';+ id: string;+ stage: 'pre' | 'post' | null;+ }>('rule-get', { id: schedule.rule });++ await $send('rule-update', {+ ...rule,+ actions: [+ ...rule.actions,+ {+ op: 'set-split-amount',+ value: -7_000,+ options: { splitIndex: 1, method: 'fixed-amount' },+ },+ {+ op: 'set-split-amount',+ value: null,+ options: { splitIndex: 2, method: 'remainder' },+ },+ {+ op: 'set',+ field: 'payee',+ value: destinationPayee.id,+ options: { splitIndex: 2 },+ },+ ],+ });+ });++ const destinationAccountPage =+ await navigation.goToAccountPage('Ally Savings');+ const previewTransfer = destinationAccountPage.transactionTableRow.filter({+ has: page.getByTestId('schedule-icon'),+ hasText: 'Bank of America',+ });++ await expect(previewTransfer).toHaveCount(1);+ await expect(previewTransfer.getByTestId('category')).toContainText('Due');+ await expect(previewTransfer.getByTestId('debit')).toHaveText('');+ await expect(previewTransfer.getByTestId('credit')).toHaveText('50.00');+ });+test('creates two new schedules, posts both transactions and later completes one', async () => {// Adding two schedules with the same payee and account and amount, mimicking two different subscriptionslet scheduleEditModal = await schedulesPage.addNewSchedule();diff --git a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.test.ts b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.test.tsnew file mode 100644index 0000000000..6555fa9755--- /dev/null+++ b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.test.ts@@ -0,0 +1,195 @@+import type {+ AccountEntity,+ PayeeEntity,+ ScheduleEntity,+ TransactionEntity,+} from '@actual-app/core/types/models';+import { describe, expect, test } from 'vitest';++import {+ inverseBasedOnAccount,+ isScheduleRelevantToAccount,+} from './useAccountPreviewTransactions';++function makeAccount(id: string): AccountEntity {+ return {+ id,+ name: id,+ offbudget: 0,+ closed: 0,+ sort_order: 0,+ last_reconciled: null,+ tombstone: 0,+ account_id: null,+ bank: null,+ bankName: null,+ bankId: null,+ mask: null,+ official_name: null,+ balance_current: null,+ balance_available: null,+ balance_limit: null,+ account_sync_source: null,+ last_sync: null,+ bank_sync_status: null,+ };+}++const checking = makeAccount('checking');+const savings = makeAccount('savings');+const unrelated = makeAccount('unrelated');++const payees: PayeeEntity[] = [+ { id: 'employer', name: 'Employer' },+ { id: 'insurance', name: 'Insurance' },+ { id: 'to-checking', name: 'Transfer: checking', transfer_acct: checking.id },+ { id: 'to-savings', name: 'Transfer: savings', transfer_acct: savings.id },+];++function getPayeeByTransferAccount(accountId?: string | null) {+ return payees.find(payee => payee.transfer_acct === accountId) || null;+}++function getTransferAccountByPayee(payeeId?: string | null) {+ const transferAccountId = payees.find(+ payee => payee.id === payeeId,+ )?.transfer_acct;+ return (+ [checking, savings, unrelated].find(+ account => account.id === transferAccountId,+ ) || null+ );+}++function makeSplitSchedule(): ScheduleEntity {+ return {+ id: 'paycheck',+ rule: 'paycheck-rule',+ next_date: '2026-08-15',+ completed: false,+ posts_transaction: true,+ tombstone: false,+ _payee: 'employer',+ _account: checking.id,+ _amount: -100_000,+ _amountOp: 'is',+ _date: '2026-08-15',+ _conditions: [],+ _actions: [+ {+ op: 'set',+ field: 'description',+ value: 'to-savings',+ options: { splitIndex: 2 },+ },+ ],+ };+}++describe('isScheduleRelevantToAccount', () => {+ test('includes a split schedule for its transfer destination', () => {+ expect(+ isScheduleRelevantToAccount({+ accountId: savings.id,+ schedule: makeSplitSchedule(),+ getTransferAccountByPayee,+ }),+ ).toBe(true);+ });++ test('excludes a split schedule from unrelated accounts', () => {+ expect(+ isScheduleRelevantToAccount({+ accountId: unrelated.id,+ schedule: makeSplitSchedule(),+ getTransferAccountByPayee,+ }),+ ).toBe(false);+ });+});++describe('inverseBasedOnAccount', () => {+ const parentId = 'preview/paycheck/2026-08-15';+ const transactions: TransactionEntity[] = [+ {+ id: parentId,+ account: checking.id,+ amount: -100_000,+ date: '2026-08-15',+ payee: 'employer',+ category: 'upcoming',+ is_parent: true,+ schedule: 'paycheck',+ },+ {+ id: 'preview/deduction',+ account: checking.id,+ amount: -60_000,+ date: '2026-08-15',+ payee: 'insurance',+ is_child: true,+ parent_id: parentId,+ schedule: 'paycheck',+ },+ {+ id: 'preview/savings-transfer',+ account: checking.id,+ amount: -40_000,+ date: '2026-08-15',+ payee: 'to-savings',+ category: 'old-category',+ is_child: true,+ parent_id: parentId,+ schedule: 'paycheck',+ },+ ];++ test('projects only the transfer child as a destination-account deposit', () => {+ const result = inverseBasedOnAccount({+ accountId: savings.id,+ transactions,+ startingBalance: 500_000,+ runningBalances: new Map(),+ getPayeeByTransferAccount,+ getTransferAccountByPayee,+ });++ expect(result.transactions).toEqual([+ expect.objectContaining({+ id: 'preview/savings-transfer',+ account: savings.id,+ amount: 40_000,+ payee: 'to-checking',+ category: 'upcoming',+ inversed: true,+ }),+ ]);+ expect(result.transactions[0]).not.toHaveProperty('is_child');+ expect(result.transactions[0]).not.toHaveProperty('parent_id');+ expect(result.runningBalances.get('preview/savings-transfer')).toBe(+ 540_000,+ );+ });++ test('preserves the complete split in its source account', () => {+ const runningBalances = new Map([[parentId, 400_000]]);+ const result = inverseBasedOnAccount({+ accountId: checking.id,+ transactions,+ startingBalance: 500_000,+ runningBalances,+ getPayeeByTransferAccount,+ getTransferAccountByPayee,+ });++ expect(result.transactions.map(transaction => transaction.id)).toEqual(+ transactions.map(transaction => transaction.id),+ );+ expect(result.transactions[2]).toMatchObject({+ amount: -40_000,+ is_child: true,+ parent_id: parentId,+ });+ expect(result.runningBalances).toBe(runningBalances);+ });+});diff --git a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.tsindex a1db76b4f7..b362ae4c60 100644--- a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts+++ b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts@@ -62,9 +62,11 @@ export function useAccountPreviewTransactions({const accountSchedulesFilter = useCallback((schedule: ScheduleEntity) =>- !accountId ||- schedule._account === accountId ||- getTransferAccountByPayee(schedule._payee)?.id === accountId,+ isScheduleRelevantToAccount({+ accountId,+ schedule,+ getTransferAccountByPayee,+ }),[accountId, getTransferAccountByPayee],);@@ -152,7 +154,86 @@ type InverseBasedOnAccountProps = {) => AccountEntity | null;};-function inverseBasedOnAccount({+type AccountPreviewTransaction = TransactionEntity & {+ inversed: boolean;+};++type ScheduleRelevantToAccountProps = Pick<+ InverseBasedOnAccountProps,+ 'accountId' | 'getTransferAccountByPayee'+> & {+ schedule: ScheduleEntity;+};++export function isScheduleRelevantToAccount({+ accountId,+ schedule,+ getTransferAccountByPayee,+}: ScheduleRelevantToAccountProps): boolean {+ if (!accountId) {+ return true;+ }++ if (+ schedule._account === accountId ||+ getTransferAccountByPayee(schedule._payee)?.id === accountId+ ) {+ return true;+ }++ return schedule._actions.some(action => {+ if (+ action.op !== 'set' ||+ (action.field !== 'payee' && action.field !== 'description') ||+ !action.options?.splitIndex+ ) {+ return false;+ }++ if (+ action.options.formula != null ||+ action.options.template != null ||+ typeof action.value !== 'string'+ ) {+ return true;+ }++ return getTransferAccountByPayee(action.value)?.id === accountId;+ });+}++function inverseTransferForAccount({+ accountId,+ previewStatus,+ transaction,+ getPayeeByTransferAccount,+}: Pick<+ InverseBasedOnAccountProps,+ 'accountId' | 'getPayeeByTransferAccount'+> & {+ previewStatus?: TransactionEntity['category'];+ transaction: TransactionEntity;+}): AccountPreviewTransaction {+ const {+ category: _category,+ is_child: _isChild,+ is_parent: _isParent,+ parent_id: _parentId,+ subtransactions: _subtransactions,+ ...standaloneTransaction+ } = transaction;++ return {+ ...standaloneTransaction,+ inversed: true,+ amount: -transaction.amount,+ payee: getPayeeByTransferAccount(transaction.account)?.id || '',+ account: accountId || '',+ ...(previewStatus != null && { category: previewStatus }),+ };+}++export function inverseBasedOnAccount({accountId,transactions,runningBalances,@@ -163,31 +244,40 @@ function inverseBasedOnAccount({transactions: TransactionEntity[];runningBalances: Map<TransactionEntity['id'], IntegerAmount>;} {- const mappedTransactions = transactions.map(transaction => {- const inverse = transaction.account !== accountId;- const subtransactions = transaction.subtransactions?.map(st => ({- ...st,- amount: inverse ? -st.amount : st.amount,- payee:- (inverse ? getPayeeByTransferAccount(st.account)?.id : st.payee) || '',- account: inverse- ? getTransferAccountByPayee(st.payee)?.id || ''- : st.account,- }));- return {- inversed: inverse,- ...transaction,- amount: inverse ? -transaction.amount : transaction.amount,- payee:- (inverse- ? getPayeeByTransferAccount(transaction.account)?.id- : transaction.payee) || '',- account: inverse- ? getTransferAccountByPayee(transaction.payee)?.id || ''- : transaction.account,- ...(subtransactions && { subtransactions }),- };- });+ const parentPreviewStatuses = new Map(+ transactions+ .filter(transaction => transaction.is_parent)+ .map(transaction => [transaction.id, transaction.category]),+ );+ const mappedTransactions: AccountPreviewTransaction[] = transactions.flatMap(+ transaction => {+ if (transaction.account === accountId) {+ return [{ inversed: false, ...transaction }];+ }++ const candidates = transaction.subtransactions+ ? transaction.subtransactions+ : transaction.is_parent+ ? []+ : [transaction];++ return candidates+ .filter(+ candidate =>+ getTransferAccountByPayee(candidate.payee)?.id === accountId,+ )+ .map(candidate =>+ inverseTransferForAccount({+ accountId,+ previewStatus: candidate.parent_id+ ? parentPreviewStatuses.get(candidate.parent_id)+ : candidate.category,+ transaction: candidate,+ getPayeeByTransferAccount,+ }),+ );+ },+ );// Recalculate running balances if any transaction was inversed.// This is necessary because the running balances are calculated based on thediff --git a/packages/desktop-client/src/hooks/useSchedules.test.ts b/packages/desktop-client/src/hooks/useSchedules.test.tsindex cb2df0566e..c71b2b7485 100644--- a/packages/desktop-client/src/hooks/useSchedules.test.ts+++ b/packages/desktop-client/src/hooks/useSchedules.test.ts@@ -5,7 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { liveQuery } from '#queries/liveQuery';import type { LiveQuery } from '#queries/liveQuery';-import { useSchedules } from './useSchedules';+import { getSchedulesQuery, useSchedules } from './useSchedules';vi.mock('#queries/liveQuery', () => ({liveQuery: vi.fn(),@@ -80,3 +80,17 @@ describe('useSchedules', () => {expect(calls[1].unsubscribe).toHaveBeenCalled();});});++describe('getSchedulesQuery', () => {+ it('loads split schedules for concrete account views', () => {+ const query = getSchedulesQuery('savings');++ expect(query.state.filterExpressions).toContainEqual({+ $or: [+ { _account: 'savings' },+ { '_payee.transfer_acct': 'savings' },+ { _has_splits: true },+ ],+ });+ });+});diff --git a/packages/desktop-client/src/hooks/useSchedules.ts b/packages/desktop-client/src/hooks/useSchedules.tsindex fb326f0580..73348f81bf 100644--- a/packages/desktop-client/src/hooks/useSchedules.ts+++ b/packages/desktop-client/src/hooks/useSchedules.ts@@ -1,7 +1,7 @@import { useEffect, useRef, useState } from 'react';import { q } from '@actual-app/core/shared/query';-import type { Query } from '@actual-app/core/shared/query';+import type { ObjectExpression, Query } from '@actual-app/core/shared/query';import {getHasTransactionsQuery,getStatus,@@ -164,8 +164,19 @@ export function getSchedulesQuery(if (view === 'uncategorized') {query = query.filter({ next_date: null });} else {+ const scheduleFilters: ObjectExpression[] = [+ filterByAccount,+ filterByPayee,+ ].filter(filter => filter !== null);++ if (view !== 'onbudget' && view !== 'offbudget') {+ scheduleFilters.push({+ _has_splits: true,+ });+ }+query = query.filter({- $or: [filterByAccount, filterByPayee],+ $or: scheduleFilters,});}}diff --git a/packages/loot-core/src/server/aql/schema/index.ts b/packages/loot-core/src/server/aql/schema/index.tsindex cb5e4710b0..ecada54515 100644--- a/packages/loot-core/src/server/aql/schema/index.ts+++ b/packages/loot-core/src/server/aql/schema/index.ts@@ -124,6 +124,7 @@ export const schema = {_date: f('json/fallback'),_conditions: f('json'),_actions: f('json'),+ _has_splits: f('boolean'),},rules: {id: f('id'),@@ -344,6 +345,11 @@ export const schemaConfig: SchemaConfig = {_date: `json_extract(_rules.conditions, _paths.date || '.value')`,_conditions: '_rules.conditions',_actions: '_rules.actions',+ _has_splits: `EXISTS (+ SELECT 1+ FROM json_each(_rules.actions) action+ WHERE json_extract(action.value, '$.options.splitIndex') > 0+ )`,});return `diff --git a/packages/loot-core/src/server/db/types/index.ts b/packages/loot-core/src/server/db/types/index.tsindex 0dccc5f77f..54c851d68d 100644--- a/packages/loot-core/src/server/db/types/index.ts+++ b/packages/loot-core/src/server/db/types/index.ts@@ -353,6 +353,7 @@ export type DbViewSchedule = {_date: JsonString;_conditions: JsonString;_actions: JsonString;+ _has_splits: 0 | 1;};export type DbTag = {diff --git a/packages/loot-core/src/server/schedules/app.test.ts b/packages/loot-core/src/server/schedules/app.test.tsindex 47e97f402d..4c90047ea2 100644--- a/packages/loot-core/src/server/schedules/app.test.ts+++ b/packages/loot-core/src/server/schedules/app.test.ts@@ -162,6 +162,52 @@ describe('schedule app', () => {).rejects.toThrow(/date condition is required/);});+ it('identifies schedules with split actions', async () => {+ const id = await createSchedule({+ conditions: [{ op: 'is', field: 'date', value: '2020-12-20' }],+ });+ const { data: ruleId } = await aqlQuery(+ q('schedules').filter({ id }).calculate('rule'),+ );++ await updateRule({+ id: ruleId,+ actions: [+ {+ op: 'set',+ field: 'payee',+ value: 'destination-payee',+ options: { splitIndex: 0 },+ },+ { op: 'link-schedule', value: id },+ ],+ });++ const { data: parentActionMatches } = await aqlQuery(+ q('schedules').filter({ _has_splits: true }).select(['id']),+ );+ expect(parentActionMatches).toEqual([]);++ await updateRule({+ id: ruleId,+ actions: [+ {+ op: 'set',+ field: 'payee',+ value: 'destination-payee',+ options: { splitIndex: 1 },+ },+ { op: 'link-schedule', value: id },+ ],+ });++ const { data: splitActionMatches } = await aqlQuery(+ q('schedules').filter({ _has_splits: true }).select(['id']),+ );++ expect(splitActionMatches).toEqual([{ id }]);+ });+it('trims schedule names when creating and updating schedules', async () => {const id = await createSchedule({schedule: { name: ' Rent ' },diff --git a/packages/loot-core/src/types/models/schedule.ts b/packages/loot-core/src/types/models/schedule.tsindex 66e90ff606..ecf222a065 100644--- a/packages/loot-core/src/types/models/schedule.ts+++ b/packages/loot-core/src/types/models/schedule.ts@@ -1,6 +1,6 @@import type { AccountEntity } from './account';import type { PayeeEntity } from './payee';-import type { RuleConditionEntity, RuleEntity } from './rule';+import type { RuleActionEntity, RuleConditionEntity, RuleEntity } from './rule';export type RecurPattern = {value: number;@@ -38,7 +38,8 @@ export type ScheduleEntity = {_amountOp: string;_date: RecurConfig | string;_conditions: RuleConditionEntity[];- _actions: Array<{ op: unknown }>;+ _actions: RuleActionEntity[];+ _has_splits?: boolean;};export type DiscoverScheduleEntity = {diff --git a/upcoming-release-notes/fix-scheduled-split-transfer-previews.md b/upcoming-release-notes/fix-scheduled-split-transfer-previews.mdnew file mode 100644index 0000000000..94c609dc47--- /dev/null+++ b/upcoming-release-notes/fix-scheduled-split-transfer-previews.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [JerryNee]+---++Show upcoming split transfers as deposits in their destination accounts