A local-first personal finance app
Feature: Add Akahu New Zealand bank sync (#6041)
ItsThatDudef1c0960fee7b
diff --git a/packages/desktop-client/src/accounts/mutations.ts b/packages/desktop-client/src/accounts/mutations.tsindex 6581cc5633..5448a3dac9 100644--- a/packages/desktop-client/src/accounts/mutations.ts+++ b/packages/desktop-client/src/accounts/mutations.ts@@ -5,6 +5,7 @@ import type { SyncResponseWithErrors } from '@actual-app/core/server/accounts/apimport type {AccountEntity,CategoryEntity,+ SyncServerAkahuAccount,SyncServerEnableBankingAccount,SyncServerGoCardlessAccount,SyncServerPluggyAiAccount,@@ -500,6 +501,46 @@ export function useLinkAccountPluggyAiMutation() {});}+type LinkAccountAkahuPayload = LinkAccountBasePayload & {+ externalAccount: SyncServerAkahuAccount;+};++export function useLinkAccountAkahuMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({+ externalAccount,+ upgradingId,+ offBudget,+ startingDate,+ startingBalance,+ }: LinkAccountAkahuPayload) => {+ await send('akahu-accounts-link', {+ externalAccount,+ upgradingId,+ offBudget,+ startingDate,+ startingBalance,+ });+ },+ onSuccess: () => {+ invalidateQueries(queryClient);+ invalidateQueries(queryClient, payeeQueries.lists());+ },+ onError: error => {+ console.error('Error linking account to Akahu:', error);+ dispatchErrorNotification(+ dispatch,+ t('There was an error linking the account to Akahu. Please try again.'),+ error,+ );+ },+ });+}+type LinkAccountEnableBankingPayload = LinkAccountBasePayload & {externalAccount: SyncServerEnableBankingAccount;};diff --git a/packages/desktop-client/src/components/Modals.tsx b/packages/desktop-client/src/components/Modals.tsxindex 7b4d21c7f6..5badb78f99 100644--- a/packages/desktop-client/src/components/Modals.tsx+++ b/packages/desktop-client/src/components/Modals.tsx@@ -14,6 +14,7 @@ import { useDispatch } from '#redux';import { EditSyncAccount } from './banksync/EditSyncAccount';import { AccountAutocompleteModal } from './modals/AccountAutocompleteModal';import { AccountMenuModal } from './modals/AccountMenuModal';+import { AkahuInitialiseModal } from './modals/AkahuInitialiseModal';import { BudgetAutomationsModal } from './modals/BudgetAutomationsModal';import { BudgetPageMenuModal } from './modals/BudgetPageMenuModal';import { CategoryAutocompleteModal } from './modals/CategoryAutocompleteModal';@@ -189,6 +190,9 @@ export function Modals() {case 'pluggyai-init':return <PluggyAiInitialiseModal key={key} {...modal.options} />;+ case 'akahu-init':+ return <AkahuInitialiseModal key={key} {...modal.options} />;+case 'enablebanking-init':return <EnableBankingInitialiseModal key={key} {...modal.options} />;diff --git a/packages/desktop-client/src/components/banksync/EditSyncAccount.tsx b/packages/desktop-client/src/components/banksync/EditSyncAccount.tsxindex 91b4671bbe..6f6bdae038 100644--- a/packages/desktop-client/src/components/banksync/EditSyncAccount.tsx+++ b/packages/desktop-client/src/components/banksync/EditSyncAccount.tsx@@ -70,6 +70,7 @@ const mappableFields: MappableField[] = ['creditor.name','debtor.name','account_servicer.name',+ 'meta.other_account',],},{@@ -93,6 +94,11 @@ const mappableFields: MappableField[] = ['merchant.cnpj','entry_reference','transaction_id',+ 'meta.particulars',+ 'meta.code',+ 'meta.reference',+ 'meta.other_account',+ 'meta.card_suffix',],},];diff --git a/packages/desktop-client/src/components/banksync/bankSyncUtils.ts b/packages/desktop-client/src/components/banksync/bankSyncUtils.tsindex 4a0e6e3bb5..6d8b2f99f9 100644--- a/packages/desktop-client/src/components/banksync/bankSyncUtils.ts+++ b/packages/desktop-client/src/components/banksync/bankSyncUtils.ts@@ -17,6 +17,7 @@ export const BUILT_IN_BANK_SYNC_PROVIDERS = [const SYNC_PROVIDER_KEYS = [...BUILT_IN_BANK_SYNC_PROVIDERS,'enableBanking',+ 'akahu','unlinked',] as const satisfies readonly SyncProviders[];@@ -34,6 +35,7 @@ export function getSyncSourceReadable(simpleFin: 'SimpleFIN',pluggyai: 'Pluggy.ai',enableBanking: 'Enable Banking',+ akahu: 'Akahu',unlinked: translate('Unlinked'),};}diff --git a/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts b/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.tsindex 934176c5de..d99ce865fc 100644--- a/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts+++ b/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts@@ -13,6 +13,7 @@ import { Permissions } from '#auth/types';import { useMultiuserEnabled } from '#components/ServerContext';import { authorizeBank as authorizeEnableBanking } from '#enablebanking';import { authorizeBank } from '#gocardless';+import { useAkahuStatus } from '#hooks/useAkahuStatus';import { useEnableBankingStatus } from '#hooks/useEnableBankingStatus';import { useFeatureFlag } from '#hooks/useFeatureFlag';import { useGoCardlessStatus } from '#hooks/useGoCardlessStatus';@@ -108,13 +109,19 @@ export function useBuiltInBankSyncProviders({>(null);const [isEnableBankingSetupComplete, setIsEnableBankingSetupComplete] =useState<boolean | null>(null);+ const [isAkahuSetupComplete, setIsAkahuSetupComplete] = useState<+ boolean | null+ >(null);const [loadingSimpleFinAccounts, setLoadingSimpleFinAccounts] =useState(false);+ const [loadingAkahuAccounts, setLoadingAkahuAccounts] = useState(false);const enableBankingEnabled = useFeatureFlag('enableBanking');+ const akahuEnabled = useFeatureFlag('akahuBankSync');const { configuredGoCardless } = useGoCardlessStatus();const { configuredSimpleFin } = useSimpleFinStatus();const { configuredPluggyAi } = usePluggyAiStatus();+ const { configuredAkahu } = useAkahuStatus(akahuEnabled);const { configuredEnableBanking, isLoading: isEnableBankingLoading } =useEnableBankingStatus(enableBankingEnabled);@@ -134,6 +141,10 @@ export function useBuiltInBankSyncProviders({setIsEnableBankingSetupComplete(configuredEnableBanking);}, [configuredEnableBanking]);+ useEffect(() => {+ setIsAkahuSetupComplete(configuredAkahu);+ }, [configuredAkahu]);+const onGoCardlessInit = useCallback(() => {dispatch(pushModal({@@ -186,6 +197,19 @@ export function useBuiltInBankSyncProviders({);}, [dispatch]);+ const onAkahuInit = useCallback(() => {+ dispatch(+ pushModal({+ modal: {+ name: 'akahu-init',+ options: {+ onSuccess: () => setIsAkahuSetupComplete(true),+ },+ },+ }),+ );+ }, [dispatch]);+const notifyResetFailure = useCallback((providerName: string, error: unknown) => {dispatch(@@ -299,6 +323,29 @@ export function useBuiltInBankSyncProviders({}}, [notifyResetFailure]);+ const onAkahuReset = useCallback(async () => {+ try {+ await ensureSuccessResponse(+ await send('secret-set', {+ name: 'akahu_userToken',+ value: null,+ }),+ 'Failed to clear Akahu user token',+ );+ await ensureSuccessResponse(+ await send('secret-set', {+ name: 'akahu_appToken',+ value: null,+ }),+ 'Failed to clear Akahu app token',+ );+ setIsAkahuSetupComplete(false);+ } catch (error) {+ console.log(error);+ notifyResetFailure('Akahu', error);+ }+ }, [notifyResetFailure]);+const onConnectGoCardless = useCallback(() => {if (!isGoCardlessSetupComplete) {onGoCardlessInit();@@ -464,11 +511,93 @@ export function useBuiltInBankSyncProviders({upgradingAccountId,]);+ const onConnectAkahu = useCallback(async () => {+ if (!isAkahuSetupComplete) {+ onAkahuInit();+ return;+ }++ if (loadingAkahuAccounts) {+ return;+ }++ setLoadingAkahuAccounts(true);++ try {+ const results = await send('akahu-accounts');+ if (results.error_code) {+ throw new Error(results.reason);+ }+ if ('error' in results && results.error) {+ throw new Error(results.reason || results.error);+ }++ const newAccounts = [];++ type NormalizedAccount = {+ account_id: string;+ name: string;+ institution: string;+ orgDomain: string;+ orgId: string;+ balance: number;+ };++ for (const oldAccount of results.accounts ?? []) {+ const newAccount: NormalizedAccount = {+ account_id: oldAccount._id,+ name: oldAccount.name,+ institution: oldAccount.connection.name,+ orgDomain: oldAccount.connection.name,+ orgId: oldAccount.connection._id,+ balance: oldAccount.balance.current,+ };++ newAccounts.push(newAccount);+ }++ dispatch(+ pushModal({+ modal: {+ name: 'select-linked-accounts',+ options: {+ externalAccounts: newAccounts,+ syncSource: 'akahu',+ upgradingAccountId,+ },+ },+ }),+ );+ } catch (error) {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ title: t('Error when trying to contact Akahu'),+ message: error instanceof Error ? error.message : String(error),+ timeout: 5000,+ },+ }),+ );+ onAkahuInit();+ }++ setLoadingAkahuAccounts(false);+ }, [+ dispatch,+ isAkahuSetupComplete,+ loadingAkahuAccounts,+ onAkahuInit,+ upgradingAccountId,+ t,+ ]);+const configuredProviders = {goCardless: Boolean(isGoCardlessSetupComplete),simpleFin: Boolean(isSimpleFinSetupComplete),pluggyai: Boolean(isPluggyAiSetupComplete),enableBanking: Boolean(isEnableBankingSetupComplete),+ akahu: Boolean(isAkahuSetupComplete),} satisfies Record<BankSyncProviders, boolean>;const providers = useMemo<BuiltInBankSyncProviderState[]>(() => {@@ -519,6 +648,22 @@ export function useBuiltInBankSyncProviders({};});+ if (akahuEnabled) {+ baseProviders.push({+ id: 'akahu',+ displayName: 'Akahu',+ description: t(+ 'Link a New Zealand bank account to automatically download transactions.',+ ),+ isConfigured: configuredProviders.akahu,+ canConfigure: canConfigureProviders,+ isLoading: loadingAkahuAccounts,+ onConfigure: onAkahuInit,+ onLink: onConnectAkahu,+ onReset: onAkahuReset,+ });+ }+if (enableBankingEnabled) {baseProviders.push({id: 'enableBanking',@@ -542,13 +687,19 @@ export function useBuiltInBankSyncProviders({configuredProviders.goCardless,configuredProviders.pluggyai,configuredProviders.simpleFin,+ configuredProviders.akahu,enableBankingEnabled,+ akahuEnabled,isEnableBankingLoading,loadingSimpleFinAccounts,+ loadingAkahuAccounts,+ onConnectAkahu,onConnectEnableBanking,onConnectGoCardless,onConnectPluggyAi,onConnectSimpleFin,+ onAkahuInit,+ onAkahuReset,onEnableBankingInit,onEnableBankingReset,onGoCardlessInit,diff --git a/packages/desktop-client/src/components/modals/AkahuInitialiseModal.tsx b/packages/desktop-client/src/components/modals/AkahuInitialiseModal.tsxnew file mode 100644index 0000000000..7a8618e34e--- /dev/null+++ b/packages/desktop-client/src/components/modals/AkahuInitialiseModal.tsx@@ -0,0 +1,153 @@+import React, { useState } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { ButtonWithLoading } from '@actual-app/components/button';+import { Input } from '@actual-app/components/input';+import { Text } from '@actual-app/components/text';+import { View } from '@actual-app/components/view';+import { send } from '@actual-app/core/platform/client/connection';++import { Error as ErrorAlert } from '#components/alerts';+import { Link } from '#components/common/Link';+import {+ Modal,+ ModalButtons,+ ModalCloseButton,+ ModalHeader,+} from '#components/common/Modal';+import { FormField, FormLabel } from '#components/forms';+import type { Modal as ModalType } from '#modals/modalsSlice';+import { getSecretsError } from '#util/error';++type AkahuInitialiseModalProps = Extract<+ ModalType,+ { name: 'akahu-init' }+>['options'];++export const AkahuInitialiseModal = ({+ onSuccess,+}: AkahuInitialiseModalProps) => {+ const { t } = useTranslation();+ const [userToken, setUserToken] = useState('');+ const [appToken, setAppToken] = useState('');+ const [isValid, setIsValid] = useState(true);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState(+ t('It is required to provide a User Token and an App Token.'),+ );++ const onSubmit = async (close: () => void) => {+ if (!userToken || !appToken) {+ setIsValid(false);+ return;+ }++ setIsLoading(true);+ let hasError = false;++ const { error, reason } =+ (await send('secret-set', {+ name: 'akahu_userToken',+ value: userToken,+ })) || {};++ if (error) {+ setIsValid(false);+ setError(getSecretsError(error, reason));+ hasError = true;+ } else {+ const { error, reason } =+ (await send('secret-set', {+ name: 'akahu_appToken',+ value: appToken,+ })) || {};++ if (error) {+ setIsValid(false);+ setError(getSecretsError(error, reason));+ hasError = true;+ } else {+ onSuccess();+ }+ }+ setIsLoading(false);++ if (!hasError) {+ close();+ }+ };++ return (+ <Modal name="akahu-init" containerProps={{ style: { width: 300 } }}>+ {({ state }) => (+ <>+ <ModalHeader+ title={t('Set-up Akahu')}+ rightContent={<ModalCloseButton onPress={() => state.close()} />}+ />+ <View style={{ display: 'flex', gap: 10 }}>+ <Text>+ <Trans>+ In order to enable bank sync via Akahu (only for New Zealand+ banks), you will need to create a token. This can be done by+ creating an account with{' '}+ <Link+ variant="external"+ to="https://my.akahu.nz/"+ linkColor="purple"+ >+ Akahu+ </Link>+ .+ </Trans>+ </Text>++ <FormField>+ <FormLabel title={t('App ID Token:')} htmlFor="appToken-field" />+ <Input+ id="appToken-field"+ type="password"+ value={appToken}+ onChangeValue={value => {+ setAppToken(value);+ setIsValid(true);+ }}+ />+ </FormField>++ <FormField>+ <FormLabel+ title={t('User Access Token:')}+ htmlFor="userToken-field"+ />+ <Input+ id="userToken-field"+ type="password"+ value={userToken}+ onChangeValue={value => {+ setUserToken(value);+ setIsValid(true);+ }}+ />+ </FormField>++ {!isValid && <ErrorAlert>{error}</ErrorAlert>}+ </View>++ <ModalButtons>+ <ButtonWithLoading+ variant="primary"+ autoFocus+ isLoading={isLoading}+ onPress={() => {+ void onSubmit(() => state.close());+ }}+ >+ <Trans>Save and continue</Trans>+ </ButtonWithLoading>+ </ModalButtons>+ </>+ )}+ </Modal>+ );+};diff --git a/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.tsx b/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.tsxindex 088c2d8b0a..52fc6e6397 100644--- a/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.tsx+++ b/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.tsx@@ -13,6 +13,7 @@ import { View } from '@actual-app/components/view';import { currentDay, subDays } from '@actual-app/core/shared/months';import type {AccountEntity,+ SyncServerAkahuAccount,SyncServerEnableBankingAccount,SyncServerGoCardlessAccount,SyncServerPluggyAiAccount,@@ -21,6 +22,7 @@ import type {import { format as formatDate, parseISO } from 'date-fns';import {+ useLinkAccountAkahuMutation,useLinkAccountEnableBankingMutation,useLinkAccountMutation,useLinkAccountPluggyAiMutation,@@ -95,6 +97,12 @@ export type SelectLinkedAccountsModalProps =externalAccounts: SyncServerEnableBankingAccount[];syncSource: 'enableBanking';upgradingAccountId?: string;+ }+ | {+ requisitionId?: undefined;+ externalAccounts: SyncServerAkahuAccount[];+ syncSource: 'akahu';+ upgradingAccountId?: string;};export function SelectLinkedAccountsModal({@@ -124,6 +132,12 @@ export function SelectLinkedAccountsModal({externalAccounts: toSort as SyncServerPluggyAiAccount[],upgradingAccountId,};+ case 'akahu':+ return {+ syncSource: 'akahu',+ externalAccounts: toSort as SyncServerAkahuAccount[],+ upgradingAccountId,+ };case 'goCardless':return {syncSource: 'goCardless',@@ -206,6 +220,7 @@ export function SelectLinkedAccountsModal({const unlinkAccount = useUnlinkAccountMutation();const linkAccountSimpleFin = useLinkAccountSimpleFinMutation();const linkAccountPluggyAi = useLinkAccountPluggyAiMutation();+ const linkAccountAkahu = useLinkAccountAkahuMutation();const linkAccountEnableBanking = useLinkAccountEnableBankingMutation();async function onNext() {@@ -272,6 +287,21 @@ export function SelectLinkedAccountsModal({startingDate,startingBalance,});+ } else if (propsWithSortedExternalAccounts.syncSource === 'akahu') {+ linkAccountAkahu.mutate({+ externalAccount:+ propsWithSortedExternalAccounts.externalAccounts[+ externalAccountIndex+ ],+ upgradingId:+ chosenLocalAccountId !== addOnBudgetAccountOption.id &&+ chosenLocalAccountId !== addOffBudgetAccountOption.id+ ? chosenLocalAccountId+ : undefined,+ offBudget,+ startingDate,+ startingBalance,+ });} else if (propsWithSortedExternalAccounts.syncSource === 'enableBanking') {@@ -320,7 +350,8 @@ export function SelectLinkedAccountsModal({externalAccount:| SyncServerGoCardlessAccount| SyncServerSimpleFinAccount- | SyncServerPluggyAiAccount,+ | SyncServerPluggyAiAccount+ | SyncServerAkahuAccount,localAccountId: string | null | undefined,) {setChosenAccounts(accounts => {@@ -545,6 +576,7 @@ type ExternalAccount =| SyncServerGoCardlessAccount| SyncServerSimpleFinAccount| SyncServerPluggyAiAccount+ | SyncServerAkahuAccount| SyncServerEnableBankingAccount;type StartingBalanceInfo = {diff --git a/packages/desktop-client/src/components/settings/Experimental.tsx b/packages/desktop-client/src/components/settings/Experimental.tsxindex 62aaccfd86..7239bba3e2 100644--- a/packages/desktop-client/src/components/settings/Experimental.tsx+++ b/packages/desktop-client/src/components/settings/Experimental.tsx@@ -238,6 +238,12 @@ export function ExperimentalFeatures() {><Trans>Enable Banking sync (EU banks)</Trans></FeatureToggle>+ <FeatureToggle+ flag="akahuBankSync"+ feedbackLink="https://github.com/actualbudget/actual/issues/8020"+ >+ <Trans>Akahu Bank Sync (NZ banks)</Trans>+ </FeatureToggle>{showServerPrefs && (<ServerFeatureToggleprefName="flags.plugins"diff --git a/packages/desktop-client/src/hooks/useAkahuStatus.ts b/packages/desktop-client/src/hooks/useAkahuStatus.tsnew file mode 100644index 0000000000..14c59af781--- /dev/null+++ b/packages/desktop-client/src/hooks/useAkahuStatus.ts@@ -0,0 +1,33 @@+import { useEffect, useState } from 'react';++import { send } from '@actual-app/core/platform/client/connection';++import { useSyncServerStatus } from './useSyncServerStatus';++export function useAkahuStatus(enabled = true) {+ const [configuredAkahu, setConfiguredAkahu] = useState<boolean | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const status = useSyncServerStatus();++ useEffect(() => {+ if (!enabled) return;++ async function fetch() {+ setIsLoading(true);++ const results = await send('akahu-status');++ setConfiguredAkahu(results.configured || false);+ setIsLoading(false);+ }++ if (status === 'online') {+ void fetch();+ }+ }, [status, enabled]);++ return {+ configuredAkahu,+ isLoading,+ };+}diff --git a/packages/desktop-client/src/hooks/useFeatureFlag.ts b/packages/desktop-client/src/hooks/useFeatureFlag.tsindex d1620124fe..e96becc595 100644--- a/packages/desktop-client/src/hooks/useFeatureFlag.ts+++ b/packages/desktop-client/src/hooks/useFeatureFlag.ts@@ -15,6 +15,7 @@ const DEFAULT_FEATURE_FLAG_STATE: Record<FeatureFlag, boolean> = {payeeLocations: false,enableBanking: false,sankeyReport: false,+ akahuBankSync: false,};export function useFeatureFlag(name: FeatureFlag): boolean {diff --git a/packages/desktop-client/src/modals/modalsSlice.ts b/packages/desktop-client/src/modals/modalsSlice.tsindex 6ff15bb174..611b500287 100644--- a/packages/desktop-client/src/modals/modalsSlice.ts+++ b/packages/desktop-client/src/modals/modalsSlice.ts@@ -129,6 +129,12 @@ export type Modal =onSuccess: () => void;};}+ | {+ name: 'akahu-init';+ options: {+ onSuccess: () => void;+ };+ }| {name: 'enablebanking-init';options: {diff --git a/packages/loot-core/src/server/accounts/app.ts b/packages/loot-core/src/server/accounts/app.tsindex 8a59a382d8..4f08b59753 100644--- a/packages/loot-core/src/server/accounts/app.ts+++ b/packages/loot-core/src/server/accounts/app.ts@@ -29,6 +29,7 @@ import type {CategoryEntity,GoCardlessToken,ImportTransactionEntity,+ SyncServerAkahuAccount,SyncServerEnableBankingAccount,SyncServerGoCardlessAccount,SyncServerPluggyAiAccount,@@ -56,6 +57,7 @@ export type AccountHandlers = {'gocardless-accounts-link': typeof linkGoCardlessAccount;'simplefin-accounts-link': typeof linkSimpleFinAccount;'pluggyai-accounts-link': typeof linkPluggyAiAccount;+ 'akahu-accounts-link': typeof linkAkahuAccount;'enablebanking-accounts-link': typeof linkEnableBankingAccount;'account-create': typeof createAccount;'account-close': typeof closeAccount;@@ -68,6 +70,7 @@ export type AccountHandlers = {'gocardless-status': typeof goCardlessStatus;'simplefin-status': typeof simpleFinStatus;'pluggyai-status': typeof pluggyAiStatus;+ 'akahu-status': typeof akahuStatus;'enablebanking-status': typeof enableBankingStatus;'enablebanking-aspsps': typeof enableBankingAspsps;'enablebanking-start-auth': typeof enableBankingStartAuth;@@ -77,6 +80,7 @@ export type AccountHandlers = {'enablebanking-configure': typeof enableBankingConfigure;'simplefin-accounts': typeof simpleFinAccounts;'pluggyai-accounts': typeof pluggyAiAccounts;+ 'akahu-accounts': typeof akahuAccounts;'gocardless-get-banks': typeof getGoCardlessBanks;'gocardless-create-web-token': typeof createGoCardlessWebToken;'accounts-bank-sync': typeof accountsBankSync;@@ -380,6 +384,80 @@ async function linkPluggyAiAccount({return 'ok';}+async function linkAkahuAccount({+ externalAccount,+ upgradingId,+ offBudget = false,+ startingDate,+ startingBalance,+}: LinkAccountBaseParams & {+ externalAccount: SyncServerAkahuAccount;+}) {+ let id;++ const institution = {+ name: externalAccount.institution ?? null,+ };++ const bank = await link.findOrCreateBank(+ institution,+ externalAccount.orgDomain ?? externalAccount.orgId,+ );++ if (upgradingId) {+ const accRow = await db.first<db.DbAccount>(+ 'SELECT * FROM accounts WHERE id = ?',+ [upgradingId],+ );++ if (!accRow) {+ throw new Error(`Account with ID ${upgradingId} not found.`);+ }++ id = accRow.id;+ await db.update('accounts', {+ id,+ account_id: externalAccount.account_id,+ bank: bank.id,+ account_sync_source: 'akahu',+ });+ } else {+ id = uuidv4();+ await db.insertWithUUID('accounts', {+ id,+ account_id: externalAccount.account_id,+ name: externalAccount.name,+ official_name: externalAccount.name,+ bank: bank.id,+ offbudget: offBudget ? 1 : 0,+ account_sync_source: 'akahu',+ });+ await db.insertPayee({+ name: '',+ transfer_acct: id,+ });+ }++ const syncRes = await bankSync.syncAccount(+ undefined,+ undefined,+ id,+ externalAccount.account_id,+ bank.bank_id,+ startingDate,+ startingBalance,+ );++ await handleSyncResponse(syncRes, id);++ connection.send('sync-event', {+ type: 'success',+ tables: ['transactions'],+ });++ return 'ok';+}+async function linkEnableBankingAccount({externalAccount,upgradingId,@@ -833,6 +911,27 @@ async function pluggyAiStatus() {);}+async function akahuStatus() {+ const userToken = await asyncStorage.getItem('user-token');++ if (!userToken) {+ return { error: 'unauthorized' };+ }++ const serverConfig = getServer();+ if (!serverConfig) {+ throw new Error('Failed to get server config.');+ }++ return post(+ serverConfig.AKAHU_SERVER + '/status',+ {},+ {+ 'X-ACTUAL-TOKEN': userToken,+ },+ );+}+async function simpleFinAccounts() {const userToken = await asyncStorage.getItem('user-token');@@ -885,6 +984,32 @@ async function pluggyAiAccounts() {}}+async function akahuAccounts() {+ const userToken = await asyncStorage.getItem('user-token');++ if (!userToken) {+ return { error: 'unauthorized' };+ }++ const serverConfig = getServer();+ if (!serverConfig) {+ throw new Error('Failed to get server config.');+ }++ try {+ return await post(+ serverConfig.AKAHU_SERVER + '/accounts',+ {},+ {+ 'X-ACTUAL-TOKEN': userToken,+ },+ 60000,+ );+ } catch {+ return { error_code: 'TIMED_OUT' };+ }+}+async function enableBankingStatus() {const userToken = await asyncStorage.getItem('user-token');@@ -1594,6 +1719,7 @@ app.method('account-properties', getAccountProperties);app.method('gocardless-accounts-link', linkGoCardlessAccount);app.method('simplefin-accounts-link', linkSimpleFinAccount);app.method('pluggyai-accounts-link', linkPluggyAiAccount);+app.method('akahu-accounts-link', linkAkahuAccount);app.method('enablebanking-accounts-link', linkEnableBankingAccount);app.method('account-create', mutator(undoable(createAccount)));app.method('account-close', mutator(closeAccount));@@ -1606,6 +1732,7 @@ app.method('gocardless-poll-web-token-stop', stopGoCardlessWebTokenPolling);app.method('gocardless-status', goCardlessStatus);app.method('simplefin-status', simpleFinStatus);app.method('pluggyai-status', pluggyAiStatus);+app.method('akahu-status', akahuStatus);app.method('enablebanking-status', enableBankingStatus);app.method('enablebanking-aspsps', enableBankingAspsps);app.method('enablebanking-start-auth', enableBankingStartAuth);@@ -1615,6 +1742,7 @@ app.method('enablebanking-poll-auth-stop', stopEnableBankingPollAuth);app.method('enablebanking-configure', enableBankingConfigure);app.method('simplefin-accounts', simpleFinAccounts);app.method('pluggyai-accounts', pluggyAiAccounts);+app.method('akahu-accounts', akahuAccounts);app.method('gocardless-get-banks', getGoCardlessBanks);app.method('gocardless-create-web-token', createGoCardlessWebToken);app.method('accounts-bank-sync', mutator(accountsBankSync));diff --git a/packages/loot-core/src/server/accounts/sync.ts b/packages/loot-core/src/server/accounts/sync.tsindex 53a12b4d7d..62db86172b 100644--- a/packages/loot-core/src/server/accounts/sync.ts+++ b/packages/loot-core/src/server/accounts/sync.ts@@ -314,6 +314,45 @@ async function downloadPluggyAiTransactions(return retVal;}+async function downloadAkahuTransactions(+ acctId: AccountEntity['id'],+ since: string,+) {+ const userToken = await asyncStorage.getItem('user-token');+ if (!userToken) return;++ logger.log('Pulling transactions from Akahu');++ const res = await post(+ getServer().AKAHU_SERVER + '/transactions',+ {+ accountId: acctId,+ startDate: since,+ },+ {+ 'X-ACTUAL-TOKEN': userToken,+ },+ 60000,+ );++ if (res.error_code) {+ throw BankSyncError(res.error_type, res.error_code);+ } else if ('error' in res) {+ throw BankSyncError('Connection', res.error);+ }++ let retVal = {};+ const singleRes = res as BankSyncResponse;+ retVal = {+ transactions: singleRes.transactions.all,+ accountBalance: singleRes.balances,+ startingBalance: singleRes.startingBalance,+ };++ logger.log('Response:', retVal);+ return retVal;+}+async function downloadEnableBankingTransactions(acctId: string,since: string,@@ -1048,6 +1087,14 @@ async function processBankSyncDownload(return total - amountToInteger(trans.transactionAmount.amount);}, currentBalance);balanceToUse = previousBalance;+ } else if (acctRow.account_sync_source === 'akahu') {+ const currentBalance = download.startingBalance;+ const previousBalance = transactions.reduce(+ (total, trans) =>+ total - amountToInteger(trans.transactionAmount.amount),+ currentBalance,+ );+ balanceToUse = Math.round(previousBalance);}const oldestTransaction = transactions[transactions.length - 1];@@ -1136,6 +1183,8 @@ export async function syncAccount(download = await downloadSimpleFinTransactions(acctId, syncStartDate);} else if (acctRow.account_sync_source === 'pluggyai') {download = await downloadPluggyAiTransactions(acctId, syncStartDate);+ } else if (acctRow.account_sync_source === 'akahu') {+ download = await downloadAkahuTransactions(acctId, syncStartDate);} else if (acctRow.account_sync_source === 'goCardless') {download = await downloadGoCardlessTransactions(userId,diff --git a/packages/loot-core/src/server/server-config.ts b/packages/loot-core/src/server/server-config.tsindex 4a993bb0ea..b0c6e7e3d2 100644--- a/packages/loot-core/src/server/server-config.ts+++ b/packages/loot-core/src/server/server-config.ts@@ -8,6 +8,7 @@ type ServerConfig = {GOCARDLESS_SERVER: string;SIMPLEFIN_SERVER: string;PLUGGYAI_SERVER: string;+ AKAHU_SERVER: string;ENABLEBANKING_SERVER: string;};@@ -46,6 +47,7 @@ export function getServer(url?: string): ServerConfig | null {GOCARDLESS_SERVER: joinURL(url, '/gocardless'),SIMPLEFIN_SERVER: joinURL(url, '/simplefin'),PLUGGYAI_SERVER: joinURL(url, '/pluggyai'),+ AKAHU_SERVER: joinURL(url, '/akahu'),ENABLEBANKING_SERVER: joinURL(url, '/enablebanking'),};} catch (error) {diff --git a/packages/loot-core/src/types/models/akahu.ts b/packages/loot-core/src/types/models/akahu.tsnew file mode 100644index 0000000000..168bdf44a7--- /dev/null+++ b/packages/loot-core/src/types/models/akahu.ts@@ -0,0 +1,8 @@+export type SyncServerAkahuAccount = {+ balance: number;+ account_id: string;+ institution?: string;+ orgDomain?: string | null;+ orgId?: string;+ name: string;+};diff --git a/packages/loot-core/src/types/models/bank-sync.ts b/packages/loot-core/src/types/models/bank-sync.tsindex 42a7217b0c..22ae9e8d64 100644--- a/packages/loot-core/src/types/models/bank-sync.ts+++ b/packages/loot-core/src/types/models/bank-sync.ts@@ -25,6 +25,7 @@ export const SYNC_PROVIDERS = ['simpleFin','pluggyai','enableBanking',+ 'akahu',] as const;export type BankSyncProviders = (typeof SYNC_PROVIDERS)[number];diff --git a/packages/loot-core/src/types/models/index.ts b/packages/loot-core/src/types/models/index.tsindex c002f14b50..2516ef6694 100644--- a/packages/loot-core/src/types/models/index.ts+++ b/packages/loot-core/src/types/models/index.ts@@ -1,4 +1,5 @@export type * from './account';+export type * from './akahu';export type * from './bank';export type * from './bank-sync';export type * from './category';diff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.tsindex bc7a52da42..717094ce89 100644--- a/packages/loot-core/src/types/prefs.ts+++ b/packages/loot-core/src/types/prefs.ts@@ -10,7 +10,8 @@ export type FeatureFlag =| 'budgetAnalysisReport'| 'payeeLocations'| 'enableBanking'- | 'sankeyReport';+ | 'sankeyReport'+ | 'akahuBankSync';/*** Cross-device preferences. These sync across devices when they are changed.diff --git a/packages/sync-server/package.json b/packages/sync-server/package.jsonindex 0241026170..1da69158e7 100644--- a/packages/sync-server/package.json+++ b/packages/sync-server/package.json@@ -90,6 +90,7 @@"dependencies": {"@actual-app/crdt": "workspace:*","@actual-app/web": "workspace:*",+ "akahu": "^2.5.1","bcrypt": "^6.0.0","better-sqlite3": "^12.8.0","convict": "^6.2.5",diff --git a/packages/sync-server/src/app-akahu/app-akahu.ts b/packages/sync-server/src/app-akahu/app-akahu.tsnew file mode 100644index 0000000000..ecf662f4b8--- /dev/null+++ b/packages/sync-server/src/app-akahu/app-akahu.ts@@ -0,0 +1,341 @@+import { AkahuClient } from 'akahu';+import type {+ Account,+ CurrencyConversion,+ EnrichedTransaction,+ PendingTransaction,+ Transaction,+} from 'akahu';+// For some reason this is not provided in the provided index.d.ts file+import type { EnrichedPendingTransaction } from 'akahu/dist/models/transactions';+import { formatISO } from 'date-fns';+import express from 'express';++import { handleError } from '#app-gocardless/util/handle-error';+import { SecretName, secretsService } from '#services/secrets-service';+import {+ requestLoggerMiddleware,+ validateSessionMiddleware,+} from '#util/middlewares';++type AkahuTransaction = {+ booked: boolean;+ date: string;+ payeeName: string;+ notes: string;+ category?: string;+ transactionId?: string;+ sortOrder: number;+ transactionAmount: { amount: number; currency: string };+ merchant?: {+ name: string;+ website?: string;+ };+ meta?: {+ particulars?: string;+ code?: string;+ reference?: string;+ other_account?: string;+ conversion?: CurrencyConversion;+ logo?: string;+ card_suffix?: string;+ };+};++const app = express();+export { app as handlers };+app.use(express.json());+app.use(requestLoggerMiddleware);+app.use(validateSessionMiddleware);++app.post(+ '/status',+ handleError(async (req, res) => {+ const userToken = secretsService.get(SecretName.akahu_userToken);+ const appToken = secretsService.get(SecretName.akahu_appToken);++ const configured = userToken != null && appToken != null;++ res.send({+ status: 'ok',+ data: {+ configured,+ },+ });+ }),+);++app.post(+ '/accounts',+ handleError(async (req, res) => {+ const userToken = secretsService.get(SecretName.akahu_userToken);+ const appToken = secretsService.get(SecretName.akahu_appToken);++ if (!userToken || !appToken) {+ res.send({+ status: 'ok',+ data: {+ error: 'Missing user or app token',+ },+ });+ return;+ }++ try {+ const akahu = new AkahuClient({ appToken });+ const accounts = await akahu.accounts.list(userToken);++ res.send({+ status: 'ok',+ data: {+ accounts,+ },+ });+ } catch (error) {+ const errorMessage =+ error instanceof Error && error.message ? error.message : String(error);++ res.send({+ status: 'error',+ data: {+ error: errorMessage,+ },+ });+ }+ }),+);++app.post(+ '/transactions',+ handleError(async (req, res) => {+ const { accountId, startDate } = req.body || {};++ if (!accountId || !startDate) {+ return res.send({+ status: 'error',+ data: {+ error: 'accountId and startDate are required',+ },+ });+ }++ const userToken = secretsService.get(SecretName.akahu_userToken);+ const appToken = secretsService.get(SecretName.akahu_appToken);++ if (!userToken || !appToken) {+ res.send({+ status: 'ok',+ data: {+ error: 'Missing user or app token',+ },+ });+ return;+ }++ try {+ const akahu = new AkahuClient({ appToken });++ const account = await akahu.accounts.get(userToken, accountId);+ if (!account) {+ return res.send({+ status: 'error',+ data: {+ error: 'Account not found',+ },+ });+ }++ if (!account.balance) {+ return res.send({+ status: 'error',+ data: {+ error: 'Account balance unavailable',+ },+ });+ }++ const now = new Date();+ const endDate = new Date(+ now.getFullYear(),+ now.getMonth() + 1,+ 1,+ ).toISOString();++ // Fetch all transactions using pagination+ const transactions: Transaction[] = [];+ let cursor = undefined;+ do {+ const { items, cursor: nextCursor } =+ await akahu.accounts.listTransactions(userToken, accountId, {+ start: new Date(startDate).toISOString(),+ end: endDate,+ cursor,+ });++ transactions.push(...items);+ cursor = nextCursor && nextCursor.next ? nextCursor.next : undefined;+ } while (cursor);++ const pendingTransactions = await akahu.accounts.listPendingTransactions(+ userToken,+ accountId,+ );++ const date = getDate(+ account.refreshed?.balance+ ? new Date(account.refreshed.balance)+ : new Date(),+ );+ const currentBalance = convertToCents(account.balance.current);++ const balances = [+ {+ balanceAmount: {+ amount: currentBalance,+ currency: account.balance.currency,+ },+ balanceType: 'expected',+ referenceDate: date,+ },+ ];++ if (account.balance.available) {+ balances.push({+ balanceAmount: {+ amount: convertToCents(account.balance.available),+ currency: account.balance.currency,+ },+ balanceType: 'interimAvailable',+ referenceDate: date,+ });+ }++ const startDateObj = new Date(startDate);+ const all = [];+ const booked = [];+ const pending = [];++ // Process booked transactions+ for (const trans of transactions) {+ if (new Date(trans.date) >= startDateObj) {+ const processedTrans = processTransaction(trans, account);+ booked.push(processedTrans);+ all.push(processedTrans);+ }+ }++ // Process pending transactions+ for (const trans of pendingTransactions) {+ if (new Date(trans.date) >= startDateObj) {+ const processedTrans = processPendingTransaction(trans, account);+ pending.push(processedTrans);+ all.push(processedTrans);+ }+ }++ const sortFunction = (a: AkahuTransaction, b: AkahuTransaction) =>+ b.sortOrder - a.sortOrder;+ const bookedSorted = booked.sort(sortFunction);+ const pendingSorted = pending.sort(sortFunction);+ const allSorted = all.sort(sortFunction);++ res.send({+ status: 'ok',+ data: {+ balances,+ startingBalance: currentBalance,+ transactions: {+ all: allSorted,+ booked: bookedSorted,+ pending: pendingSorted,+ },+ },+ });+ } catch (error) {+ const errorMessage =+ error instanceof Error && error.message ? error.message : String(error);++ res.send({+ status: 'error',+ data: {+ error: 'Failed to fetch transactions: ' + errorMessage,+ },+ });+ }+ }),+);++function isEnriched(+ trans:+ | Transaction+ | EnrichedTransaction+ | PendingTransaction+ | EnrichedPendingTransaction,+): trans is EnrichedTransaction {+ return 'merchant' in trans || 'meta' in trans || 'category' in trans;+}++function getDate(date: Date): string {+ return formatISO(date).split('T')[0];+}++function convertToCents(amount: number): number {+ return Math.round(amount * 100);+}++function getPayeeName(+ trans:+ | Transaction+ | EnrichedTransaction+ | PendingTransaction+ | EnrichedPendingTransaction,+): string {+ if (isEnriched(trans)) {+ if (trans.merchant?.name) {+ return trans.merchant.name;+ }++ if (trans.meta?.other_account) {+ return trans.meta.other_account;+ }+ }++ return '';+}++function processPendingTransaction(+ trans: PendingTransaction | EnrichedPendingTransaction,+ account: Account,+): AkahuTransaction {+ const transactionDate = new Date(trans.date);++ return {+ ...trans,+ booked: false,+ date: getDate(transactionDate),+ payeeName: getPayeeName(trans),+ notes: trans.description,+ sortOrder: transactionDate.getTime(),+ transactionAmount: {+ amount: Math.round(trans.amount * 100) / 100,+ currency: account.balance?.currency ?? 'NZD',+ },+ };+}++function processTransaction(+ trans: Transaction | EnrichedTransaction,+ account: Account,+): AkahuTransaction {+ let category = undefined;+ if (isEnriched(trans)) {+ category = trans.category?.name;+ }++ return {+ ...processPendingTransaction(trans, account),+ category,+ booked: true,+ transactionId: trans._id,+ };+}diff --git a/packages/sync-server/src/app.ts b/packages/sync-server/src/app.tsindex e171d4d83c..276059e591 100644--- a/packages/sync-server/src/app.ts+++ b/packages/sync-server/src/app.ts@@ -9,6 +9,7 @@ import rateLimit from 'express-rate-limit';import { bootstrap } from './account-db';import * as accountApp from './app-account';import * as adminApp from './app-admin';+import * as akahuApp from './app-akahu/app-akahu.js';import * as corsApp from './app-cors-proxy';import * as enableBankingApp from './app-enablebanking/app-enablebanking';import * as goCardlessApp from './app-gocardless/app-gocardless';@@ -60,6 +61,7 @@ app.use('/account', accountApp.handlers);app.use('/gocardless', goCardlessApp.handlers);app.use('/simplefin', simpleFinApp.handlers);app.use('/pluggyai', pluggai.handlers);+app.use('/akahu', akahuApp.handlers);app.use('/enablebanking', enableBankingApp.handlers);app.use('/secret', secretApp.handlers);diff --git a/packages/sync-server/src/services/secrets-service.js b/packages/sync-server/src/services/secrets-service.jsindex f38c99f377..7ca7983fad 100644--- a/packages/sync-server/src/services/secrets-service.js+++ b/packages/sync-server/src/services/secrets-service.js@@ -15,6 +15,8 @@ export const SecretName = {pluggyai_clientId: 'pluggyai_clientId',pluggyai_clientSecret: 'pluggyai_clientSecret',pluggyai_itemIds: 'pluggyai_itemIds',+ akahu_userToken: 'akahu_userToken',+ akahu_appToken: 'akahu_appToken',enablebanking_applicationId: 'enablebanking_applicationId',enablebanking_secretKey: 'enablebanking_secretKey',};diff --git a/upcoming-release-notes/6041.md b/upcoming-release-notes/6041.mdnew file mode 100644index 0000000000..ad7c0c47b7--- /dev/null+++ b/upcoming-release-notes/6041.md@@ -0,0 +1,6 @@+---+category: Features+authors: [ItsThatDude]+---++Add New Zealand bank sync via Akahudiff --git a/yarn.lock b/yarn.lockindex dcfd203f1a..7a51fc8fc0 100644--- a/yarn.lock+++ b/yarn.lock@@ -186,6 +186,7 @@ __metadata:"@types/node": "npm:^22.19.17""@types/supertest": "npm:^7.2.0""@typescript/native-preview": "npm:beta"+ akahu: "npm:^2.5.1"bcrypt: "npm:^6.0.0"better-sqlite3: "npm:^12.8.0"convict: "npm:^6.2.5"@@ -11017,6 +11018,15 @@ __metadata:languageName: nodelinkType: hard+"agent-base@npm:6":+ version: 6.0.2+ resolution: "agent-base@npm:6.0.2"+ dependencies:+ debug: "npm:4"+ checksum: 10/21fb903e0917e5cb16591b4d0ef6a028a54b83ac30cd1fca58dece3d4e0990512a8723f9f83130d88a41e2af8b1f7be1386fda3ea2d181bb1a62155e75e95e23+ languageName: node+ linkType: hard+"agent-base@npm:^7.1.0, agent-base@npm:^7.1.2":version: 7.1.4resolution: "agent-base@npm:7.1.4"@@ -11092,6 +11102,16 @@ __metadata:languageName: nodelinkType: hard+"akahu@npm:^2.5.1":+ version: 2.5.1+ resolution: "akahu@npm:2.5.1"+ dependencies:+ axios: "npm:^1.13.5"+ uuid: "npm:^8.3.2"+ checksum: 10/46f428bde53497af8fe00578f8c78442f623d146e6ac6e223958659629091823edba8c73392fe665d5b78f3675c70c7f26dfb11d03d358d0d1a0361a33f1d2bb+ languageName: node+ linkType: hard+"algoliasearch-helper@npm:^3.26.0":version: 3.26.0resolution: "algoliasearch-helper@npm:3.26.0"@@ -11536,6 +11556,18 @@ __metadata:languageName: nodelinkType: hard+"axios@npm:^1.13.5":+ version: 1.16.1+ resolution: "axios@npm:1.16.1"+ dependencies:+ follow-redirects: "npm:^1.16.0"+ form-data: "npm:^4.0.5"+ https-proxy-agent: "npm:^5.0.1"+ proxy-from-env: "npm:^2.1.0"+ checksum: 10/9b6218cf96321cfbbf8f160658d695367114bcf4fb62492bdc1ccd647f184b5c71ae400e5ecaaf41079bc561de2ecbaf1fec63f398b3ec53389beff7694df64c+ languageName: node+ linkType: hard+"b4a@npm:^1.6.4":version: 1.7.3resolution: "b4a@npm:1.7.3"@@ -16540,7 +16572,7 @@ __metadata:languageName: nodelinkType: hard-"follow-redirects@npm:^1.0.0":+"follow-redirects@npm:^1.0.0, follow-redirects@npm:^1.16.0":version: 1.16.0resolution: "follow-redirects@npm:1.16.0"peerDependenciesMeta:@@ -17909,6 +17941,16 @@ __metadata:languageName: nodelinkType: hard+"https-proxy-agent@npm:^5.0.1":+ version: 5.0.1+ resolution: "https-proxy-agent@npm:5.0.1"+ dependencies:+ agent-base: "npm:6"+ debug: "npm:4"+ checksum: 10/f0dce7bdcac5e8eaa0be3c7368bb8836ed010fb5b6349ffb412b172a203efe8f807d9a6681319105ea1b6901e1972c7b5ea899672a7b9aad58309f766dcbe0df+ languageName: node+ linkType: hard+"https-proxy-agent@npm:^7.0.0, https-proxy-agent@npm:^7.0.1, https-proxy-agent@npm:^7.0.6":version: 7.0.6resolution: "https-proxy-agent@npm:7.0.6"@@ -23830,6 +23872,13 @@ __metadata:languageName: nodelinkType: hard+"proxy-from-env@npm:^2.1.0":+ version: 2.1.0+ resolution: "proxy-from-env@npm:2.1.0"+ checksum: 10/fbbaf4dab2a6231dc9e394903a5f66f20475e36b734335790b46feb9da07c37d6b32e2c02e3e2ea4d4b23774c53d8562e5b7cc73282cb43f4a597b7eacaee2ee+ languageName: node+ linkType: hard+"pstree.remy@npm:^1.1.8":version: 1.1.8resolution: "pstree.remy@npm:1.1.8"