A local-first personal finance app
[Issue-3831] - Auto bank sync (#8744)
Emil George9732a4463aac
diff --git a/packages/desktop-client/src/components/FinancesApp.tsx b/packages/desktop-client/src/components/FinancesApp.tsxindex ff7f86c31c..62cc80172d 100644--- a/packages/desktop-client/src/components/FinancesApp.tsx+++ b/packages/desktop-client/src/components/FinancesApp.tsx@@ -12,6 +12,7 @@ import * as undo from '@actual-app/core/platform/client/undo';import { getLatestAppVersion, sync } from '#app/appSlice';import { ProtectedRoute } from '#auth/ProtectedRoute';import { Permissions } from '#auth/types';+import { useAutomaticBankSync } from '#hooks/useAutomaticBankSync';import { useGlobalPref } from '#hooks/useGlobalPref';import { useLocalPref } from '#hooks/useLocalPref';import { useMetaThemeColor } from '#hooks/useMetaThemeColor';@@ -108,6 +109,7 @@ export function FinancesApp() {const multiuserEnabled = useMultiuserEnabled();+ useAutomaticBankSync();useNewsNotification();const init = useEffectEvent(() => {diff --git a/packages/desktop-client/src/components/banksync/AutomaticSyncSettings.test.tsx b/packages/desktop-client/src/components/banksync/AutomaticSyncSettings.test.tsxnew file mode 100644index 0000000000..ddf6e82f56--- /dev/null+++ b/packages/desktop-client/src/components/banksync/AutomaticSyncSettings.test.tsx@@ -0,0 +1,145 @@+import { render, screen, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { vi } from 'vitest';++import { useSyncedPref } from '#hooks/useSyncedPref';+import { TestProviders } from '#mocks';++import { AutomaticSyncSettings } from './AutomaticSyncSettings';++vi.mock('#hooks/useSyncedPref', () => ({+ useSyncedPref: vi.fn(),+}));++const setPref = vi.fn();++/** Stands in for the synced pref, which can also change from another device. */+function mockInterval(value: string | undefined) {+ vi.mocked(useSyncedPref).mockReturnValue([value, setPref]);+}++// A fresh element each time: React can skip re-rendering when handed a+// referentially identical one, which would defeat the rerender test below.+const settings = () => (+ <TestProviders>+ <AutomaticSyncSettings />+ </TestProviders>+);++// `Select` renders a button showing the selected option's label plus a popover+// menu, so it is driven by clicking rather than selectOptions().+const intervalTrigger = () => screen.getByLabelText('Sync accounts');+const unitTrigger = () =>+ document.getElementById('bank-sync-interval-unit') as HTMLElement;+const numberField = () => screen.getByLabelText('every');++async function chooseOption(trigger: HTMLElement, label: string) {+ await userEvent.click(trigger);+ const menu = await screen.findByRole('menu');+ await userEvent.click(within(menu).getByRole('button', { name: label }));+}++describe('AutomaticSyncSettings', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockInterval('0');+ });++ it('hides the custom fields for a preset interval', () => {+ mockInterval('1440');+ render(settings());++ expect(intervalTrigger()).toHaveTextContent('Every day');+ expect(screen.queryByLabelText('every')).not.toBeInTheDocument();+ });++ it('shows the custom fields for a stored non-preset interval', () => {+ mockInterval('30');+ render(settings());++ expect(intervalTrigger()).toHaveTextContent('Custom interval');+ expect(numberField()).toHaveValue(30);+ expect(unitTrigger()).toHaveTextContent('minutes');+ });++ it('opens the custom fields when the pref becomes custom after mount', () => {+ mockInterval('1440');+ const { rerender } = render(settings());++ expect(screen.queryByLabelText('every')).not.toBeInTheDocument();++ // A custom value arriving from another device, or the pref loading late.+ mockInterval('45');+ rerender(settings());++ expect(intervalTrigger()).toHaveTextContent('Custom interval');+ expect(numberField()).toHaveValue(45);+ });++ it('does not persist a partly typed number', async () => {+ mockInterval('30');+ render(settings());++ // "30" -> "4": on its own this is below the floor, and clamping here would+ // stop the user ever reaching 45.+ await userEvent.clear(numberField());+ await userEvent.type(numberField(), '4');++ expect(setPref).not.toHaveBeenCalled();+ expect(numberField()).toHaveValue(4);+ });++ it('persists the completed number on blur', async () => {+ mockInterval('30');+ render(settings());++ await userEvent.clear(numberField());+ await userEvent.type(numberField(), '45');+ await userEvent.tab();++ expect(setPref).toHaveBeenCalledWith('45');+ });++ it('keeps the stored interval when the number is cleared and blurred', async () => {+ mockInterval('30');+ render(settings());++ await userEvent.clear(numberField());+ await userEvent.tab();++ expect(setPref).not.toHaveBeenCalled();+ expect(numberField()).toHaveValue(30);+ });++ it('clamps a completed number below the floor', async () => {+ mockInterval('30');+ render(settings());++ await userEvent.clear(numberField());+ await userEvent.type(numberField(), '5');+ await userEvent.tab();++ expect(setPref).toHaveBeenCalledWith('15');+ });++ it('converts the value when the unit changes', async () => {+ mockInterval('30');+ render(settings());++ await chooseOption(unitTrigger(), 'hours');++ expect(setPref).toHaveBeenCalledWith('1800');+ });++ it('keeps the custom fields open when Custom is chosen from a preset', async () => {+ mockInterval('1440');+ render(settings());++ await chooseOption(intervalTrigger(), 'Custom interval');++ // 1440 is itself a preset, so the fields only stay open because the+ // explicit choice is remembered.+ expect(setPref).toHaveBeenCalledWith('1440');+ expect(numberField()).toBeInTheDocument();+ });+});diff --git a/packages/desktop-client/src/components/banksync/AutomaticSyncSettings.tsx b/packages/desktop-client/src/components/banksync/AutomaticSyncSettings.tsxnew file mode 100644index 0000000000..ed86d1669c--- /dev/null+++ b/packages/desktop-client/src/components/banksync/AutomaticSyncSettings.tsx@@ -0,0 +1,169 @@+import { useState } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { Input } from '@actual-app/components/input';+import { Paragraph } from '@actual-app/components/paragraph';+import { Select } from '@actual-app/components/select';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import { MIN_CUSTOM_INTERVAL_MINUTES } from '#hooks/useAutomaticBankSync';+import { useSyncedPref } from '#hooks/useSyncedPref';++import type { BankSyncIntervalUnit } from './bankSyncInterval';+import {+ isPresetInterval,+ minutesToParts,+ partsToMinutes,+} from './bankSyncInterval';++const CUSTOM = 'custom';++export function AutomaticSyncSettings() {+ const { t } = useTranslation();+ const [interval, setIntervalPref] = useSyncedPref('bank-sync-interval');++ const currentInterval = interval || '0';++ // Set when the user explicitly picks "Custom interval". Kept separate from+ // the derivation below so choosing Custom while the interval happens to+ // equal a preset (say a whole day) doesn't immediately collapse the fields.+ const [choseCustom, setChoseCustom] = useState(false);++ // `bank-sync-interval` is a synced pref, so a value can arrive from another+ // device — or simply load — after mount. Deriving from it rather than+ // snapshotting keeps the fields in step with whatever is stored.+ const showCustom = choseCustom || !isPresetInterval(currentInterval);++ // Uncommitted text in the number field. Without this, clamping on every+ // keystroke makes multi-digit minute values impossible to type: the "3" of+ // "30" would be rewritten to the 15-minute floor.+ const [draft, setDraft] = useState<string | null>(null);++ const intervals: Array<[string, string]> = [+ ['0', t('Never')],+ ['720', t('Every 12 hours')],+ ['1440', t('Every day')],+ ['10080', t('Every week')],+ [CUSTOM, t('Custom interval')],+ ];++ const units: Array<[BankSyncIntervalUnit, string]> = [+ ['minute', t('minutes')],+ ['hour', t('hours')],+ ['day', t('days')],+ ['week', t('weeks')],+ ];++ const customParts = minutesToParts(parseInt(currentInterval, 10));++ function onChangeInterval(value: string) {+ if (value === CUSTOM) {+ setChoseCustom(true);+ // Write the interval straight away, so the value shown in the custom+ // fields is the one actually in effect.+ setIntervalPref(+ String(partsToMinutes(customParts.value, customParts.unit)),+ );+ return;+ }++ setChoseCustom(false);+ setDraft(null);+ setIntervalPref(value);+ }++ function onChangeCustom(value: number, unit: BankSyncIntervalUnit) {+ setDraft(null);+ setIntervalPref(String(partsToMinutes(value, unit)));+ }++ function commitDraft(value: string) {+ const parsed = Number(value);+ if (value.trim() === '' || !Number.isFinite(parsed)) {+ setDraft(null);+ return;+ }++ onChangeCustom(parsed, customParts.unit);+ }++ return (+ <View+ style={{+ border: `1px solid ${theme.tableBorder}`,+ borderRadius: 8,+ padding: 16,+ backgroundColor: theme.tableBackground,+ gap: 12,+ }}+ >+ <View style={{ gap: 4 }}>+ <Text style={{ fontSize: 17, fontWeight: 600 }}>+ <Trans>Automatic syncing</Trans>+ </Text>+ <Paragraph+ style={{ fontSize: 15, color: theme.pageTextSubdued, margin: 0 }}+ >+ <Trans>+ Download new transactions from your linked accounts in the+ background while Actual is open. A sync runs when any account hasn't+ synced within the chosen interval, including syncs from other+ devices.+ </Trans>+ </Paragraph>+ </View>++ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ gap: 8,+ flexWrap: 'wrap',+ }}+ >+ <label htmlFor="bank-sync-interval">+ <Trans>Sync accounts</Trans>+ </label>+ <Select+ id="bank-sync-interval"+ value={showCustom ? CUSTOM : currentInterval}+ onChange={onChangeInterval}+ options={intervals}+ style={{ flexShrink: 0 }}+ />++ {showCustom && (+ <>+ <label htmlFor="bank-sync-interval-value">+ <Trans>every</Trans>+ </label>+ <Input+ id="bank-sync-interval-value"+ type="number"+ min={+ customParts.unit === 'minute' ? MIN_CUSTOM_INTERVAL_MINUTES : 1+ }+ style={{ width: 70, flexShrink: 0 }}+ value={draft ?? String(customParts.value)}+ onChangeValue={setDraft}+ // Persist once the value is complete, not per keystroke.+ onUpdate={commitDraft}+ onEnter={commitDraft}+ />+ {/* Select drops unknown props, so this cannot carry an aria-label;+ the button's own text ("minutes", "hours", …) names it. */}+ <Select+ id="bank-sync-interval-unit"+ value={customParts.unit}+ onChange={unit => onChangeCustom(customParts.value, unit)}+ options={units}+ style={{ flexShrink: 0 }}+ />+ </>+ )}+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/banksync/bankSyncInterval.test.ts b/packages/desktop-client/src/components/banksync/bankSyncInterval.test.tsnew file mode 100644index 0000000000..c95a14310f--- /dev/null+++ b/packages/desktop-client/src/components/banksync/bankSyncInterval.test.ts@@ -0,0 +1,87 @@+import { MIN_CUSTOM_INTERVAL_MINUTES } from '#hooks/useAutomaticBankSync';++import {+ isPresetInterval,+ minutesToParts,+ partsToMinutes,+} from './bankSyncInterval';++describe('minutesToParts', () => {+ it('uses the largest unit that divides evenly', () => {+ expect(minutesToParts(30)).toEqual({ value: 30, unit: 'minute' });+ expect(minutesToParts(60)).toEqual({ value: 1, unit: 'hour' });+ expect(minutesToParts(360)).toEqual({ value: 6, unit: 'hour' });+ expect(minutesToParts(1440)).toEqual({ value: 1, unit: 'day' });+ expect(minutesToParts(4320)).toEqual({ value: 3, unit: 'day' });+ expect(minutesToParts(10080)).toEqual({ value: 1, unit: 'week' });+ expect(minutesToParts(20160)).toEqual({ value: 2, unit: 'week' });+ });++ it('steps down to a smaller unit when the larger one does not divide', () => {+ // Just over a week, but a whole number of hours.+ expect(minutesToParts(10140)).toEqual({ value: 169, unit: 'hour' });+ // Over a day, but not a whole number of days.+ expect(minutesToParts(1500)).toEqual({ value: 25, unit: 'hour' });+ });++ it('falls back to minutes when no larger unit divides evenly', () => {+ expect(minutesToParts(90)).toEqual({ value: 90, unit: 'minute' });+ expect(minutesToParts(1450)).toEqual({ value: 1450, unit: 'minute' });+ });++ it('defaults to one hour for values that are not a usable interval', () => {+ expect(minutesToParts(0)).toEqual({ value: 1, unit: 'hour' });+ expect(minutesToParts(-5)).toEqual({ value: 1, unit: 'hour' });+ expect(minutesToParts(NaN)).toEqual({ value: 1, unit: 'hour' });+ });+});++describe('partsToMinutes', () => {+ it('converts each unit', () => {+ expect(partsToMinutes(30, 'minute')).toBe(30);+ expect(partsToMinutes(6, 'hour')).toBe(360);+ expect(partsToMinutes(2, 'day')).toBe(2880);+ expect(partsToMinutes(1, 'week')).toBe(10080);+ expect(partsToMinutes(3, 'week')).toBe(30240);+ });++ it('treats an empty or invalid number as one of the unit', () => {+ expect(partsToMinutes(NaN, 'hour')).toBe(60);+ expect(partsToMinutes(0, 'day')).toBe(1440);+ });++ it('ignores a fractional value', () => {+ expect(partsToMinutes(2.7, 'hour')).toBe(120);+ });++ it('never returns an interval below the floor', () => {+ expect(partsToMinutes(1, 'minute')).toBe(MIN_CUSTOM_INTERVAL_MINUTES);+ expect(partsToMinutes(14, 'minute')).toBe(MIN_CUSTOM_INTERVAL_MINUTES);+ expect(partsToMinutes(NaN, 'minute')).toBe(MIN_CUSTOM_INTERVAL_MINUTES);+ expect(partsToMinutes(-3, 'minute')).toBe(MIN_CUSTOM_INTERVAL_MINUTES);+ });++ it('leaves values at or above the floor alone', () => {+ expect(partsToMinutes(15, 'minute')).toBe(15);+ expect(partsToMinutes(30, 'minute')).toBe(30);+ });++ it('round-trips with minutesToParts', () => {+ for (const minutes of [15, 30, 60, 360, 720, 1440, 4320, 10080, 30240]) {+ const { value, unit } = minutesToParts(minutes);+ expect(partsToMinutes(value, unit)).toBe(minutes);+ }+ });+});++describe('isPresetInterval', () => {+ it('recognises the dropdown presets', () => {+ expect(isPresetInterval('0')).toBe(true);+ expect(isPresetInterval('1440')).toBe(true);+ });++ it('treats anything else as custom', () => {+ expect(isPresetInterval('30')).toBe(false);+ expect(isPresetInterval('60')).toBe(false);+ });+});diff --git a/packages/desktop-client/src/components/banksync/bankSyncInterval.ts b/packages/desktop-client/src/components/banksync/bankSyncInterval.tsnew file mode 100644index 0000000000..d045297314--- /dev/null+++ b/packages/desktop-client/src/components/banksync/bankSyncInterval.ts@@ -0,0 +1,66 @@+/**+ * The `bank-sync-interval` preference is stored as a whole number of minutes.+ * These helpers convert between that and the number + unit pair the custom+ * interval control shows.+ */++import { MIN_CUSTOM_INTERVAL_MINUTES } from '#hooks/useAutomaticBankSync';++// Months and years are deliberately absent: they have no fixed length in+// minutes, which is how this preference is stored.+export type BankSyncIntervalUnit = 'minute' | 'hour' | 'day' | 'week';++const MINUTES_PER_UNIT: Record<BankSyncIntervalUnit, number> = {+ minute: 1,+ hour: 60,+ day: 60 * 24,+ week: 60 * 24 * 7,+};++/** Interval values (in minutes) offered as presets in the dropdown. */+export const PRESET_INTERVAL_MINUTES = ['0', '720', '1440', '10080'];++export function isPresetInterval(minutes: string) {+ return PRESET_INTERVAL_MINUTES.includes(minutes);+}++/**+ * Split minutes into the largest unit that divides evenly, so 120 reads as+ * "2 hours" rather than "120 minutes".+ */+export function minutesToParts(minutes: number): {+ value: number;+ unit: BankSyncIntervalUnit;+} {+ if (!Number.isFinite(minutes) || minutes <= 0) {+ return { value: 1, unit: 'hour' };+ }++ if (minutes % MINUTES_PER_UNIT.week === 0) {+ return { value: minutes / MINUTES_PER_UNIT.week, unit: 'week' };+ }++ if (minutes % MINUTES_PER_UNIT.day === 0) {+ return { value: minutes / MINUTES_PER_UNIT.day, unit: 'day' };+ }++ if (minutes % MINUTES_PER_UNIT.hour === 0) {+ return { value: minutes / MINUTES_PER_UNIT.hour, unit: 'hour' };+ }++ return { value: minutes, unit: 'minute' };+}++export function partsToMinutes(+ value: number,+ unit: BankSyncIntervalUnit,+): number {+ const minutes =+ Number.isFinite(value) && value >= 1+ ? Math.floor(value) * MINUTES_PER_UNIT[unit]+ : MINUTES_PER_UNIT[unit];++ // Only ever bites for the minute unit — an hour or more is already above+ // the floor.+ return Math.max(minutes, MIN_CUSTOM_INTERVAL_MINUTES);+}diff --git a/packages/desktop-client/src/components/banksync/index.tsx b/packages/desktop-client/src/components/banksync/index.tsxindex 88c8d5a8d1..e6cea18ac3 100644--- a/packages/desktop-client/src/components/banksync/index.tsx+++ b/packages/desktop-client/src/components/banksync/index.tsx@@ -16,6 +16,7 @@ import { useDispatch } from '#redux';import { AccountsHeader } from './AccountsHeader';import { AccountsList } from './AccountsList';+import { AutomaticSyncSettings } from './AutomaticSyncSettings';import {getGroupedBankSyncEntries,getSyncSourceReadable,@@ -50,6 +51,7 @@ export function BankSync() {() => accounts.filter(account => !account.closed),[accounts],);+ const hasLinkedAccounts = openAccounts.some(account => !!account.bank);const onAction = async (account: AccountEntity, action: 'link' | 'edit') => {switch (action) {@@ -100,6 +102,8 @@ export function BankSync() {permissionWarning={permissionWarning}/>+ {hasLinkedAccounts && <AutomaticSyncSettings />}+{openAccounts.length === 0 && (<Text style={{ fontSize: '1.1rem' }}><Trans>diff --git a/packages/desktop-client/src/components/mobile/banksync/MobileBankSyncPage.tsx b/packages/desktop-client/src/components/mobile/banksync/MobileBankSyncPage.tsxindex 8adcc8530f..e35680fc88 100644--- a/packages/desktop-client/src/components/mobile/banksync/MobileBankSyncPage.tsx+++ b/packages/desktop-client/src/components/mobile/banksync/MobileBankSyncPage.tsx@@ -7,6 +7,7 @@ import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';import type { AccountEntity } from '@actual-app/core/types/models';+import { AutomaticSyncSettings } from '#components/banksync/AutomaticSyncSettings';import {getGroupedBankSyncEntries,getSyncSourceReadable,@@ -48,6 +49,8 @@ export function MobileBankSyncPage() {[openAccounts],);+ const hasLinkedAccounts = openAccounts.some(account => !!account.bank);+const filteredGroupedAccounts = useMemo(() => {if (!filter) return groupedAccounts;@@ -108,6 +111,11 @@ export function MobileBankSyncPage() {onToggleCollapse={() => setProvidersCollapsed(!providersCollapsed)}/></View>+ {hasLinkedAccounts && (+ <View style={{ padding: '0 15px 15px', flexShrink: 0 }}>+ <AutomaticSyncSettings />+ </View>+ )}{openAccounts.length > 0 && (<Viewstyle={{diff --git a/packages/desktop-client/src/hooks/useAutomaticBankSync.test.ts b/packages/desktop-client/src/hooks/useAutomaticBankSync.test.tsnew file mode 100644index 0000000000..85de174fe7--- /dev/null+++ b/packages/desktop-client/src/hooks/useAutomaticBankSync.test.ts@@ -0,0 +1,207 @@+import type { AccountEntity } from '@actual-app/core/types/models';++import {+ isAutomaticSyncDue,+ parseBankSyncInterval,+} from './useAutomaticBankSync';++const MINUTE = 60 * 1000;+const HOUR = 60 * 60 * 1000;+const NOW = 1_700_000_000_000;++function account(overrides: Partial<AccountEntity> = {}): AccountEntity {+ return {+ id: 'account-1',+ account_group_id: null,+ name: 'Checking',+ offbudget: 0,+ closed: 0,+ sort_order: 0,+ last_reconciled: null,+ tombstone: 0,+ account_id: 'bank-account-1',+ bank: 'bank-1',+ bankName: 'Bank',+ bankId: 'bank-1',+ mask: '1234',+ official_name: 'Checking',+ balance_current: 0,+ balance_available: 0,+ balance_limit: null,+ account_sync_source: 'goCardless',+ last_sync: null,+ bank_sync_status: 'ok',+ ...overrides,+ };+}++describe('parseBankSyncInterval', () => {+ it('treats unset, zero and invalid values as disabled', () => {+ expect(parseBankSyncInterval(undefined)).toBe(0);+ expect(parseBankSyncInterval('')).toBe(0);+ expect(parseBankSyncInterval('0')).toBe(0);+ expect(parseBankSyncInterval('not a number')).toBe(0);+ expect(parseBankSyncInterval('-60')).toBe(0);+ });++ it('converts minutes to milliseconds', () => {+ expect(parseBankSyncInterval('60')).toBe(HOUR);+ expect(parseBankSyncInterval('1440')).toBe(24 * HOUR);+ });+});++describe('isAutomaticSyncDue', () => {+ const base = {+ now: NOW,+ intervalMs: HOUR,+ lastAutomaticRun: undefined,+ accounts: [account()],+ isServerOnline: true,+ };++ it('is not due while the sync server is unreachable', () => {+ expect(isAutomaticSyncDue({ ...base, isServerOnline: false })).toBe(false);+ });++ it('becomes due again as soon as the server is reachable', () => {+ // Being offline must not consume the interval: the caller only records an+ // attempt when this returns true, so a sync fires on the next check rather+ // than waiting out another interval.+ expect(isAutomaticSyncDue({ ...base, isServerOnline: false })).toBe(false);+ expect(isAutomaticSyncDue({ ...base, isServerOnline: true })).toBe(true);+ });++ it('is not due when automatic syncing is disabled', () => {+ expect(isAutomaticSyncDue({ ...base, intervalMs: 0 })).toBe(false);+ });++ it('is not due when there are no linked accounts', () => {+ expect(isAutomaticSyncDue({ ...base, accounts: [] })).toBe(false);+ expect(+ isAutomaticSyncDue({ ...base, accounts: [account({ bank: null })] }),+ ).toBe(false);+ expect(+ isAutomaticSyncDue({ ...base, accounts: [account({ closed: 1 })] }),+ ).toBe(false);+ expect(+ isAutomaticSyncDue({ ...base, accounts: [account({ tombstone: 1 })] }),+ ).toBe(false);+ });++ it('is due when a linked account has never synced', () => {+ expect(isAutomaticSyncDue(base)).toBe(true);+ });++ it('is not due when a sync happened within the interval', () => {+ expect(+ isAutomaticSyncDue({+ ...base,+ accounts: [account({ last_sync: String(NOW - 30 * 60 * 1000) })],+ }),+ ).toBe(false);+ });++ it('is due when one account is overdue even if another just synced', () => {+ expect(+ isAutomaticSyncDue({+ ...base,+ accounts: [+ account({ id: 'recent', last_sync: String(NOW - MINUTE) }),+ account({ id: 'stale', last_sync: String(NOW - 2 * HOUR) }),+ ],+ }),+ ).toBe(true);+ });++ it('is not due while every account has synced within the interval', () => {+ expect(+ isAutomaticSyncDue({+ ...base,+ accounts: [+ account({ id: 'a', last_sync: String(NOW - MINUTE) }),+ account({ id: 'b', last_sync: String(NOW - 30 * MINUTE) }),+ ],+ }),+ ).toBe(false);+ });++ it('is due when one account has never synced', () => {+ expect(+ isAutomaticSyncDue({+ ...base,+ accounts: [+ account({ id: 'a', last_sync: String(NOW - MINUTE) }),+ account({ id: 'never', last_sync: null }),+ ],+ }),+ ).toBe(true);+ });++ it('does not let a closed account force a sync', () => {+ // A closed account with an ancient last_sync must not force a sync.+ expect(+ isAutomaticSyncDue({+ ...base,+ accounts: [+ account({ id: 'a', last_sync: String(NOW - MINUTE) }),+ account({+ id: 'closed',+ closed: 1,+ last_sync: String(NOW - 5 * HOUR),+ }),+ ],+ }),+ ).toBe(false);+ });++ it('is due once the last sync is older than the interval', () => {+ expect(+ isAutomaticSyncDue({+ ...base,+ accounts: [account({ last_sync: String(NOW - HOUR) })],+ }),+ ).toBe(true);+ });++ it('uses the oldest synced account as the reference point', () => {+ expect(+ isAutomaticSyncDue({+ ...base,+ accounts: [+ account({ id: 'a', last_sync: String(NOW - 5 * HOUR) }),+ account({ id: 'b', last_sync: String(NOW - 10 * MINUTE) }),+ ],+ }),+ ).toBe(true);+ });++ it('ignores unlinked accounts when looking for the last sync', () => {+ expect(+ isAutomaticSyncDue({+ ...base,+ accounts: [+ account({ id: 'a', last_sync: String(NOW - 5 * HOUR) }),+ account({ id: 'b', bank: null, last_sync: String(NOW) }),+ ],+ }),+ ).toBe(true);+ });++ it('does not retry within the interval after a failed attempt', () => {+ // A failed sync leaves `last_sync` untouched, so only the local+ // last-attempt timestamp prevents a retry storm.+ expect(+ isAutomaticSyncDue({+ ...base,+ lastAutomaticRun: NOW - 10 * 60 * 1000,+ }),+ ).toBe(false);++ expect(+ isAutomaticSyncDue({+ ...base,+ lastAutomaticRun: NOW - HOUR,+ }),+ ).toBe(true);+ });+});diff --git a/packages/desktop-client/src/hooks/useAutomaticBankSync.ts b/packages/desktop-client/src/hooks/useAutomaticBankSync.tsnew file mode 100644index 0000000000..f4ad99aee5--- /dev/null+++ b/packages/desktop-client/src/hooks/useAutomaticBankSync.ts@@ -0,0 +1,145 @@+import { useEffect, useEffectEvent } from 'react';++import type { AccountEntity } from '@actual-app/core/types/models';++import { useSyncAndDownloadMutation } from '#accounts';+import { useAccounts } from '#hooks/useAccounts';+import { useLocalPref } from '#hooks/useLocalPref';+import { useSyncedPref } from '#hooks/useSyncedPref';+import { useSyncServerStatus } from '#hooks/useSyncServerStatus';++// How often we check whether a sync is due. A sync can only ever be late by up+// to one check, so this just needs to stay comfortably shorter than+// MIN_CUSTOM_INTERVAL_MINUTES below. Checking every minute keeps the timer+// cheap while staying well inside that.+const CHECK_INTERVAL_MS = 60 * 1000;++const MINUTE_MS = 60 * 1000;++/**+ * Shortest interval the custom interval control will produce. Banks rate-limit+ * how often accounts can be refreshed, and syncing more often than this mostly+ * burns that allowance without returning anything new.+ *+ * Lives here rather than with the control so it sits next to CHECK_INTERVAL_MS:+ * lowering it below that would make syncs land noticeably late.+ */+export const MIN_CUSTOM_INTERVAL_MINUTES = 15;++/** Converts the `bank-sync-interval` preference (in minutes) to milliseconds. */+export function parseBankSyncInterval(interval: string | undefined) {+ const minutes = parseInt(interval ?? '0', 10);+ return Number.isFinite(minutes) && minutes > 0 ? minutes * MINUTE_MS : 0;+}++type IsAutomaticSyncDueArgs = {+ now: number;+ intervalMs: number;+ /** Epoch ms of the last automatic sync attempted by this device. */+ lastAutomaticRun: number | undefined;+ accounts: AccountEntity[];+ /** Bank sync goes through the sync server, so it must be reachable. */+ isServerOnline: boolean;+};++/**+ * Decides whether an automatic bank sync should run right now.+ *+ * The *oldest* successful sync across linked accounts is the reference point,+ * so a single account being refreshed does not hold back the others.+ *+ * A sync covers every linked account rather than just the overdue ones, because+ * the underlying sync mutation takes one account or all of them and refuses to+ * run in parallel. So an account that synced recently can be swept along early+ * — bounded at one extra refresh per interval, which is the lesser problem.+ *+ * Because `last_sync` is synced between devices, manual syncs and syncs from+ * other devices still count, so several open devices don't multiply the number+ * of requests made to the bank.+ */+export function isAutomaticSyncDue({+ now,+ intervalMs,+ lastAutomaticRun,+ accounts,+ isServerOnline,+}: IsAutomaticSyncDueArgs) {+ if (intervalMs <= 0) {+ return false;+ }++ if (!isServerOnline) {+ return false;+ }++ const linkedAccounts = accounts.filter(+ ({ bank, closed, tombstone }) => !!bank && !closed && !tombstone,+ );++ if (linkedAccounts.length === 0) {+ return false;+ }++ // Don't retry immediately if the previous attempt failed — a failed sync+ // never updates `last_sync`, so without this an account that consistently+ // errors would be retried on every check.+ if (lastAutomaticRun != null && now - lastAutomaticRun < intervalMs) {+ return false;+ }++ // No zero seed here: an account that has never synced parses to 0, which is+ // already the oldest possible value and makes the sync due.+ const oldestSync = Math.min(+ ...linkedAccounts.map(+ ({ last_sync }) => parseInt(last_sync ?? '0', 10) || 0,+ ),+ );++ return now - oldestSync >= intervalMs;+}++/**+ * Periodically runs bank sync while the app is open, based on the+ * `bank-sync-interval` preference.+ */+export function useAutomaticBankSync() {+ const [interval] = useSyncedPref('bank-sync-interval');+ const [lastAutomaticRun, setLastAutomaticRun] = useLocalPref(+ 'bankSync.lastAutomaticRun',+ );+ const { data: accounts = [] } = useAccounts();+ const syncAndDownload = useSyncAndDownloadMutation();+ const serverStatus = useSyncServerStatus();++ const intervalMs = parseBankSyncInterval(interval);++ const maybeSync = useEffectEvent(() => {+ const now = Date.now();++ if (+ !isAutomaticSyncDue({+ now,+ intervalMs,+ lastAutomaticRun,+ accounts,+ isServerOnline: serverStatus === 'online',+ })+ ) {+ return;+ }++ setLastAutomaticRun(now);+ syncAndDownload.mutate({});+ });++ useEffect(() => {+ if (intervalMs <= 0) {+ return;+ }++ maybeSync();++ const timer = setInterval(maybeSync, CHECK_INTERVAL_MS);+ return () => clearInterval(timer);+ }, [intervalMs]);+}diff --git a/packages/docs/docs/advanced/bank-sync.md b/packages/docs/docs/advanced/bank-sync.mdindex 1fc204ff19..3af0e4cae9 100644--- a/packages/docs/docs/advanced/bank-sync.md+++ b/packages/docs/docs/advanced/bank-sync.md@@ -21,7 +21,31 @@ Here are a couple of considerations to know about before making the decision to### Retrieve Transactions-Actual does **not** sync bank data automatically. To fetch new transactions manually:+You can fetch new transactions [automatically](#automatic-syncing) or manually.++#### Automatic Syncing++Actual can download new transactions from your linked accounts in the background. Automatic syncing is off by default.++To turn it on:++1. Open **Bank Sync** from the sidebar (on mobile, find it in the navigation menu).+2. In the **Automatic syncing** section, choose how often Actual should sync: **Every 12 hours**, **Every day** or **Every week**.+3. To use a different schedule, choose **Custom interval**, then enter a number and pick the unit (minutes, hours, days or weeks).++The **Automatic syncing** section only appears once at least one account is linked to a bank.++A few things to know:++- Syncing only happens while Actual is open. If you close Actual, it catches up the next time you open it.+- The shortest custom interval is 15 minutes. Banks limit how often accounts can be refreshed, so syncing more often than you need can use up that allowance.+- A sync runs when any linked account hasn't synced within the chosen interval. Syncs you start manually, and syncs from your other devices, count towards this, so having Actual open on several devices doesn't multiply the requests sent to your bank.+- Each automatic sync covers all of your linked accounts, not only the ones that are overdue.+- Automatic syncing is skipped while the sync server can't be reached, and tries again once the connection is back.++#### Manual Syncing++To fetch new transactions manually:#### On Desktopdiff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.tsindex b0e57a605e..7e6ff34368 100644--- a/packages/loot-core/src/types/prefs.ts+++ b/packages/loot-core/src/types/prefs.ts@@ -43,6 +43,9 @@ export type SyncedPrefs = Partial<| `transaction-table-columns-${string}`| `show-group-${string}`| 'sync-transfer-date'+ // Number of minutes between automatic bank syncs. '0' (or unset) disables+ // automatic syncing.+ | 'bank-sync-interval'// TODO: pull from src/components/modals/ImportTransactions.js| `parse-date-${string}-${'csv' | 'qif'}`| `import-reimport-deleted-${string}`@@ -108,6 +111,12 @@ export type LocalPrefs = Partial<{sidebarWidth: number;'mobile.showSpentColumn': boolean;'mobile.bankSyncProvidersCollapsed': boolean;+ /**+ * Timestamp (epoch ms) of the last automatic bank sync attempted by this+ * device. Tracked locally so a failing account can't cause repeated+ * back-to-back sync attempts.+ */+ 'bankSync.lastAutomaticRun': number;}>;export type Theme = 'light' | 'dark' | 'auto' | 'midnight' | string;diff --git a/upcoming-release-notes/automatic-bank-sync.md b/upcoming-release-notes/automatic-bank-sync.mdnew file mode 100644index 0000000000..2565e99d03--- /dev/null+++ b/upcoming-release-notes/automatic-bank-sync.md@@ -0,0 +1,6 @@+---+category: Features+authors: [emilgeo]+---++Add a setting to sync linked bank accounts automatically at a chosen interval