A local-first personal finance app
[AI] Show clear error and configure action when GoCardless credentials are missing (#8963)
Harshil Patel1eeffe3278b4
diff --git a/packages/desktop-client/src/accounts/syncStatus.test.ts b/packages/desktop-client/src/accounts/syncStatus.test.tsindex b8f57e03ea..8be7ec34ec 100644--- a/packages/desktop-client/src/accounts/syncStatus.test.ts+++ b/packages/desktop-client/src/accounts/syncStatus.test.ts@@ -18,6 +18,7 @@ describe('syncStatus', () => {expect(isAccountFailedSync(makeAccount('rate-limit-exceeded'))).toBe(true);expect(isAccountFailedSync(makeAccount('timed-out'))).toBe(true);expect(isAccountFailedSync(makeAccount('account-missing'))).toBe(true);+ expect(isAccountFailedSync(makeAccount('not-configured'))).toBe(true);expect(isAccountFailedSync(makeAccount('pending'))).toBe(false);expect(isAccountFailedSync(makeAccount('sync-requested'))).toBe(false);expect(isAccountFailedSync(makeAccount('ok'))).toBe(false);@@ -51,6 +52,16 @@ describe('syncStatus', () => {type: 'ACCOUNT_MISSING',code: 'ACCOUNT_MISSING',});+ expect(+ getFailedSyncError(makeAccount('not-configured', 'goCardless')),+ ).toEqual({+ type: 'GOCARDLESS_NOT_CONFIGURED',+ code: 'GOCARDLESS_NOT_CONFIGURED',+ });+ expect(getFailedSyncError(makeAccount('not-configured'))).toEqual({+ type: 'NOT_CONFIGURED',+ code: 'NOT_CONFIGURED',+ });expect(getFailedSyncError(makeAccount('failed'))).toEqual({type: 'SYNC_ERROR',code: 'SYNC_ERROR',diff --git a/packages/desktop-client/src/accounts/syncStatus.ts b/packages/desktop-client/src/accounts/syncStatus.tsindex 7d39c4390f..770509fd02 100644--- a/packages/desktop-client/src/accounts/syncStatus.ts+++ b/packages/desktop-client/src/accounts/syncStatus.ts@@ -32,6 +32,14 @@ export function getFailedSyncError(return { type: 'TIMED_OUT', code: 'TIMED_OUT' };case 'account-missing':return { type: 'ACCOUNT_MISSING', code: 'ACCOUNT_MISSING' };+ case 'not-configured':+ if (account.account_sync_source === 'goCardless') {+ return {+ type: 'GOCARDLESS_NOT_CONFIGURED',+ code: 'GOCARDLESS_NOT_CONFIGURED',+ };+ }+ return { type: 'NOT_CONFIGURED', code: 'NOT_CONFIGURED' };default:return { type: 'SYNC_ERROR', code: 'SYNC_ERROR' };}diff --git a/packages/desktop-client/src/components/accounts/AccountSyncCheck.test.tsx b/packages/desktop-client/src/components/accounts/AccountSyncCheck.test.tsxnew file mode 100644index 0000000000..89d7d125f2--- /dev/null+++ b/packages/desktop-client/src/components/accounts/AccountSyncCheck.test.tsx@@ -0,0 +1,241 @@+import React from 'react';++import type { AccountEntity } from '@actual-app/core/types/models';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useAccounts } from '#hooks/useAccounts';+import { useCurrentAccess } from '#hooks/useCurrentAccess';+import { useFailedAccounts } from '#hooks/useFailedAccounts';+import { TestProviders } from '#mocks';+import { pushModal } from '#modals/modalsSlice';++import { AccountSyncCheck } from './AccountSyncCheck';++const mockDispatch = vi.fn();++vi.mock('react-router', async importOriginal => ({+ ...(await importOriginal()),+ useParams: () => ({ id: 'acc-1' }),+}));++vi.mock('#hooks/useAccounts', () => ({+ useAccounts: vi.fn(),+}));++vi.mock('#hooks/useCurrentAccess', () => ({+ useCurrentAccess: vi.fn(),+}));++vi.mock('#hooks/useFailedAccounts', () => ({+ useFailedAccounts: vi.fn(),+}));++vi.mock('#accounts', () => ({+ useUnlinkAccountMutation: () => ({ mutate: vi.fn() }),+}));++vi.mock('#redux', async importOriginal => ({+ ...(await importOriginal()),+ useDispatch: () => mockDispatch,+}));++describe('AccountSyncCheck', () => {+ const baseAccount = {+ id: 'acc-1',+ name: 'Checking',+ bank_sync_status: 'failed',+ account_sync_source: 'goCardless',+ account_id: 'gocardless-acc-1',+ bank: 'bank-1',+ } as unknown as AccountEntity;++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(useAccounts).mockReturnValue({+ data: [baseAccount],+ isLoading: false,+ } as ReturnType<typeof useAccounts>);+ vi.mocked(useCurrentAccess).mockReturnValue({+ isAdmin: true,+ isFileOwner: true,+ cloudFileId: 'file-1',+ });+ });++ it('renders clear error message and Configure button when GoCardless credentials are missing', async () => {+ vi.mocked(useFailedAccounts).mockReturnValue(+ new Map([+ [+ 'acc-1',+ {+ type: 'GOCARDLESS_NOT_CONFIGURED',+ code: 'GOCARDLESS_NOT_CONFIGURED',+ },+ ],+ ]),+ );++ render(+ <TestProviders>+ <AccountSyncCheck />+ </TestProviders>,+ );++ // Click banner to open popover+ const bannerButton = screen.getByText(+ "This account is experiencing connection problems. Let's fix it.",+ );+ await userEvent.click(bannerButton);++ // Verify error message+ expect(+ screen.getByText(+ 'Your GoCardless credentials are missing. Please re-enter them to restore bank sync.',+ ),+ ).toBeInTheDocument();++ // Verify Configure and Unlink buttons are shown+ const configureButton = screen.getByRole('button', { name: 'Configure' });+ expect(configureButton).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Unlink' })).toBeInTheDocument();++ // Clicking Configure opens gocardless-init modal+ await userEvent.click(configureButton);+ expect(mockDispatch).toHaveBeenCalledWith(+ pushModal({+ modal: {+ name: 'gocardless-init',+ options: {+ onSuccess: expect.any(Function),+ },+ },+ }),+ );+ });++ it('renders Reauthorize button for expired authentication', async () => {+ vi.mocked(useFailedAccounts).mockReturnValue(+ new Map([+ [+ 'acc-1',+ {+ type: 'ITEM_ERROR',+ code: 'ITEM_LOGIN_REQUIRED',+ },+ ],+ ]),+ );++ render(+ <TestProviders>+ <AccountSyncCheck />+ </TestProviders>,+ );++ const bannerButton = screen.getByText(+ "This account is experiencing connection problems. Let's fix it.",+ );+ await userEvent.click(bannerButton);++ expect(+ screen.getByText(+ 'Your password or something else has changed with your bank and you need to login again.',+ ),+ ).toBeInTheDocument();++ expect(+ screen.getByRole('button', { name: 'Reauthorize' }),+ ).toBeInTheDocument();+ });++ it('hides Configure button and only shows Unlink account for non-admin users', async () => {+ vi.mocked(useCurrentAccess).mockReturnValue({+ isAdmin: false,+ isFileOwner: false,+ cloudFileId: 'file-1',+ });+ vi.mocked(useFailedAccounts).mockReturnValue(+ new Map([+ [+ 'acc-1',+ {+ type: 'GOCARDLESS_NOT_CONFIGURED',+ code: 'GOCARDLESS_NOT_CONFIGURED',+ },+ ],+ ]),+ );++ render(+ <TestProviders>+ <AccountSyncCheck />+ </TestProviders>,+ );++ const bannerButton = screen.getByText(+ "This account is experiencing connection problems. Let's fix it.",+ );+ await userEvent.click(bannerButton);++ expect(+ screen.getByText(+ 'Your GoCardless credentials are missing. Please re-enter them to restore bank sync.',+ ),+ ).toBeInTheDocument();++ expect(+ screen.queryByRole('button', { name: 'Configure' }),+ ).not.toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: 'Unlink account' }),+ ).toBeInTheDocument();+ });++ it('preserves GoCardless missing credentials error and Configure button across client reloads', async () => {+ vi.mocked(useAccounts).mockReturnValue({+ data: [+ {+ ...baseAccount,+ bank_sync_status: 'not-configured',+ },+ ],+ isLoading: false,+ } as ReturnType<typeof useAccounts>);+ vi.mocked(useFailedAccounts).mockReturnValue(new Map());++ render(+ <TestProviders>+ <AccountSyncCheck />+ </TestProviders>,+ );++ const bannerButton = screen.getByText(+ "This account is experiencing connection problems. Let's fix it.",+ );+ await userEvent.click(bannerButton);++ expect(+ screen.getByText(+ 'Your GoCardless credentials are missing. Please re-enter them to restore bank sync.',+ ),+ ).toBeInTheDocument();++ const configureButton = screen.getByRole('button', { name: 'Configure' });+ expect(configureButton).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Unlink' })).toBeInTheDocument();++ await userEvent.click(configureButton);+ expect(mockDispatch).toHaveBeenCalledWith(+ pushModal({+ modal: {+ name: 'gocardless-init',+ options: {+ onSuccess: expect.any(Function),+ },+ },+ }),+ );+ });+});diff --git a/packages/desktop-client/src/components/accounts/AccountSyncCheck.tsx b/packages/desktop-client/src/components/accounts/AccountSyncCheck.tsxindex 1a76bea895..92ec7176cd 100644--- a/packages/desktop-client/src/components/accounts/AccountSyncCheck.tsx+++ b/packages/desktop-client/src/components/accounts/AccountSyncCheck.tsx@@ -15,7 +15,9 @@ import { Link } from '#components/common/Link';import { authorizeBank as authorizeEnableBanking } from '#enablebanking';import { authorizeBank as authorizeGoCardless } from '#gocardless';import { useAccounts } from '#hooks/useAccounts';+import { useCurrentAccess } from '#hooks/useCurrentAccess';import { useFailedAccounts } from '#hooks/useFailedAccounts';+import { pushModal } from '#modals/modalsSlice';import { useDispatch } from '#redux';function useErrorMessage() {@@ -47,6 +49,11 @@ function useErrorMessage() {case 'RATE_LIMIT_EXCEEDED':return t('Rate limit exceeded for this item. Please try again later.');+ case 'GOCARDLESS_NOT_CONFIGURED':+ return t(+ 'Your GoCardless credentials are missing. Please re-enter them to restore bank sync.',+ );+case 'TIMED_OUT':return t('The request timed out. Please try again later.');@@ -94,6 +101,7 @@ function useErrorMessage() {export function AccountSyncCheck() {const { data: accounts = [] } = useAccounts();const failedAccounts = useFailedAccounts();+ const { isAdmin } = useCurrentAccess();const dispatch = useDispatch();const { id } = useParams();const [open, setOpen] = useState(false);@@ -127,6 +135,22 @@ export function AccountSyncCheck() {[unlinkAccount],);+ const onConfigureGoCardless = useCallback(() => {+ setOpen(false);+ dispatch(+ pushModal({+ modal: {+ name: 'gocardless-init',+ options: {+ onSuccess: () => {+ // credentials updated+ },+ },+ },+ }),+ );+ }, [dispatch]);+if (!id) {return null;}@@ -144,6 +168,7 @@ export function AccountSyncCheck() {const showAuth =(type === 'ITEM_ERROR' && code === 'ITEM_LOGIN_REQUIRED') ||(type === 'INVALID_INPUT' && code === 'INVALID_ACCESS_TOKEN');+ const isGoCardlessNotConfigured = type === 'GOCARDLESS_NOT_CONFIGURED';return (<View>@@ -198,6 +223,20 @@ export function AccountSyncCheck() {<Trans>Reauthorize</Trans></Button></>+ ) : isGoCardlessNotConfigured && isAdmin ? (+ <>+ <Button onPress={() => unlink(account)}>+ <Trans>Unlink</Trans>+ </Button>+ <Button+ variant="primary"+ autoFocus+ onPress={onConfigureGoCardless}+ style={{ marginLeft: 5 }}+ >+ <Trans>Configure</Trans>+ </Button>+ </>) : (<Button onPress={() => unlink(account)}><Trans>Unlink account</Trans>diff --git a/packages/loot-core/src/server/accounts/app-bank-sync.test.ts b/packages/loot-core/src/server/accounts/app-bank-sync.test.tsindex c730718496..a13a142cc7 100644--- a/packages/loot-core/src/server/accounts/app-bank-sync.test.ts+++ b/packages/loot-core/src/server/accounts/app-bank-sync.test.ts@@ -274,6 +274,33 @@ describe('accountsBankSync', () => {);expect(account!.bank_sync_status).toBe('failed');});++ it('persists not-configured status after a missing credentials error', async () => {+ insertBank({ id: 'bank1', bank_id: 'gc-bank', name: 'GoCardless' });+ await db.insertAccount({+ id: 'acct1',+ name: 'Checking',+ bank: 'bank1',+ account_id: 'ext-1',+ account_sync_source: 'goCardless',+ });++ vi.mocked(bankSync.syncAccount).mockRejectedValue({+ type: 'BankSyncError',+ reason: 'credentials missing',+ category: 'GOCARDLESS_NOT_CONFIGURED',+ code: 'GOCARDLESS_NOT_CONFIGURED',+ message: 'GoCardless credentials are missing',+ });++ await accountsBankSyncHandler({ ids: ['acct1'] });++ const account = await db.first<db.DbAccount>(+ 'SELECT * FROM accounts WHERE id = ?',+ ['acct1'],+ );+ expect(account!.bank_sync_status).toBe('not-configured');+ });});describe('bank sync handlers must not nest mutators', () => {diff --git a/packages/loot-core/src/server/accounts/app.ts b/packages/loot-core/src/server/accounts/app.tsindex 1613b90a8a..1ca2951a4d 100644--- a/packages/loot-core/src/server/accounts/app.ts+++ b/packages/loot-core/src/server/accounts/app.ts@@ -1417,6 +1417,15 @@ function getBankSyncStatusFromError(if (err.category === 'ACCOUNT_MISSING') {return 'account-missing';}++ if (+ err.category === 'GOCARDLESS_NOT_CONFIGURED' ||+ err.category === 'NOT_CONFIGURED' ||+ err.code === 'GOCARDLESS_NOT_CONFIGURED' ||+ err.code === 'NOT_CONFIGURED'+ ) {+ return 'not-configured';+ }}return 'failed';diff --git a/packages/loot-core/src/server/accounts/sync.test.ts b/packages/loot-core/src/server/accounts/sync.test.tsindex ec6ef8c803..6159155fff 100644--- a/packages/loot-core/src/server/accounts/sync.test.ts+++ b/packages/loot-core/src/server/accounts/sync.test.ts@@ -957,6 +957,8 @@ describe('Account sync', () => {});describe('SimpleFin batch sync', () => {+ let previousGoCardlessTransactionsHandler;+function mockSimpleFinTransactions(response) {vi.mocked(asyncStorage.getItem).mockResolvedValue('test-token');handlers['/simplefin/transactions'] = () => response;@@ -964,6 +966,12 @@ describe('SimpleFin batch sync', () => {afterEach(() => {delete handlers['/simplefin/transactions'];+ if (previousGoCardlessTransactionsHandler) {+ handlers['/gocardless/transactions'] =+ previousGoCardlessTransactionsHandler;+ } else {+ delete handlers['/gocardless/transactions'];+ }});test('does not emit transaction CRDT messages when provider category appears later', async () => {@@ -1164,4 +1172,56 @@ describe('SimpleFin batch sync', () => {expect(missingResult.res.error_code).toBe('ACCOUNT_MISSING');expect(missingResult.res.error_type).toBe('ACCOUNT_MISSING');});++ test('preserves GOCARDLESS_NOT_CONFIGURED error through bank sync pipeline', async () => {+ vi.mocked(asyncStorage.getItem).mockResolvedValue('test-token');+ vi.mocked(asyncStorage.multiGet).mockResolvedValue({+ 'user-id': 'user-1',+ 'user-key': 'key-1',+ });++ db.runQuery(+ 'INSERT INTO banks (id, bank_id, name, tombstone) VALUES (?, ?, ?, 0)',+ ['bank-1', 'gc-bank', 'GoCardless Bank'],+ );++ const acctId = await db.insertAccount({+ id: 'acct-gc-1',+ account_id: 'ext-gc-1',+ name: 'GoCardless Checking',+ bank: 'bank-1',+ account_sync_source: 'goCardless',+ });+ await db.insertPayee({+ id: 'transfer-' + acctId,+ name: '',+ transfer_acct: acctId,+ });++ previousGoCardlessTransactionsHandler =+ handlers['/gocardless/transactions'];+ handlers['/gocardless/transactions'] = () => ({+ error_type: 'GOCARDLESS_NOT_CONFIGURED',+ error_code: 'GOCARDLESS_NOT_CONFIGURED',+ reason: 'GoCardless credentials are missing',+ });++ const result = await accountsApp.handlers['accounts-bank-sync']({+ ids: [acctId],+ });++ expect(result.errors).toHaveLength(1);+ expect(result.errors[0]).toMatchObject({+ type: 'SyncError',+ accountId: acctId,+ category: 'GOCARDLESS_NOT_CONFIGURED',+ code: 'GOCARDLESS_NOT_CONFIGURED',+ });++ const account = await db.first<db.DbAccount>(+ 'SELECT * FROM accounts WHERE id = ?',+ [acctId],+ );+ expect(account!.bank_sync_status).toBe('not-configured');+ });});diff --git a/packages/loot-core/src/server/db/types/index.ts b/packages/loot-core/src/server/db/types/index.tsindex 3a68be278f..ee0000a4ea 100644--- a/packages/loot-core/src/server/db/types/index.ts+++ b/packages/loot-core/src/server/db/types/index.ts@@ -34,6 +34,7 @@ export type DbAccount = {| 'rate-limit-exceeded'| 'timed-out'| 'account-missing'+ | 'not-configured'| null;account_group_id?: DbAccountGroup['id'] | null;};diff --git a/packages/loot-core/src/types/models/account.ts b/packages/loot-core/src/types/models/account.tsindex c07fe1f387..1896f5efb4 100644--- a/packages/loot-core/src/types/models/account.ts+++ b/packages/loot-core/src/types/models/account.ts@@ -37,4 +37,5 @@ export type BankSyncStatus =| 'attention-required'| 'rate-limit-exceeded'| 'timed-out'- | 'account-missing';+ | 'account-missing'+ | 'not-configured';diff --git a/packages/sync-server/src/app-gocardless/app-gocardless.test.ts b/packages/sync-server/src/app-gocardless/app-gocardless.test.tsindex 9289d6c096..61a183244a 100644--- a/packages/sync-server/src/app-gocardless/app-gocardless.test.ts+++ b/packages/sync-server/src/app-gocardless/app-gocardless.test.ts@@ -14,6 +14,7 @@ vi.mock('#util/middlewares', () => ({vi.mock('./services/gocardless-service', () => ({goCardlessService: {createRequisition: vi.fn(),+ isConfigured: vi.fn(() => true),},}));@@ -21,6 +22,7 @@ const { goCardlessService } = await import('./services/gocardless-service');const { handlers } = await import('./app-gocardless');const app = express();+app.use(express.json());app.use('/', handlers);describe('/create-web-token', () => {@@ -115,3 +117,38 @@ describe('/link', () => {expect(res.text).toContain('window.close()');});});++describe('when GoCardless credentials are missing (not configured)', () => {+ const isConfigured = vi.mocked(goCardlessService.isConfigured);++ beforeEach(() => {+ isConfigured.mockReturnValue(false);+ });++ afterEach(() => {+ isConfigured.mockReturnValue(true);+ });++ it('reports configured: false from /status', async () => {+ const res = await request(app).post('/status');+ expect(res.body).toEqual({+ status: 'ok',+ data: { configured: false },+ });+ });++ it('returns GOCARDLESS_NOT_CONFIGURED from POST /transactions', async () => {+ const res = await request(app)+ .post('/transactions')+ .send({ requisitionId: 'req-1', accountId: 'acc-1' });++ expect(res.body).toEqual({+ status: 'ok',+ data: {+ error_type: 'GOCARDLESS_NOT_CONFIGURED',+ error_code: 'GOCARDLESS_NOT_CONFIGURED',+ reason: 'GoCardless credentials are missing',+ },+ });+ });+});diff --git a/packages/sync-server/src/app-gocardless/app-gocardless.ts b/packages/sync-server/src/app-gocardless/app-gocardless.tsindex 85c29d7106..1f0e1bfae0 100644--- a/packages/sync-server/src/app-gocardless/app-gocardless.ts+++ b/packages/sync-server/src/app-gocardless/app-gocardless.ts@@ -1,5 +1,5 @@import express from 'express';-import type { Request } from 'express';+import type { Request, Response } from 'express';import { sha256String } from '#util/hash';import {@@ -98,6 +98,25 @@ app.post('/status', async (req, res) => {});});+const ensureConfigured = (+ _req: Request,+ res: Response,+ next: express.NextFunction,+) => {+ if (!goCardlessService.isConfigured()) {+ res.send({+ status: 'ok',+ data: {+ error_type: 'GOCARDLESS_NOT_CONFIGURED',+ error_code: 'GOCARDLESS_NOT_CONFIGURED',+ reason: 'GoCardless credentials are missing',+ },+ });+ return;+ }+ next();+};+app.post('/create-web-token',handleError(async (req, res) => {@@ -210,6 +229,7 @@ app.post(app.post('/transactions',+ ensureConfigured,handleError(async (req, res) => {const {requisitionId: rawRequisitionId,diff --git a/upcoming-release-notes/gocardless-missing-credentials-error.md b/upcoming-release-notes/gocardless-missing-credentials-error.mdnew file mode 100644index 0000000000..c9527a10d9--- /dev/null+++ b/upcoming-release-notes/gocardless-missing-credentials-error.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [Marshmellow31]+---++Show a clear error message and configuration prompt when GoCardless credentials are missing instead of an internal error