A local-first personal finance app
[Redux Toolkit Migration] accountsSlice (#4012)
Joel Jeremy Marquez6573a5241102
diff --git a/packages/desktop-client/src/components/App.tsx b/packages/desktop-client/src/components/App.tsxindex f914d04f7c..fafac79331 100644--- a/packages/desktop-client/src/components/App.tsx+++ b/packages/desktop-client/src/components/App.tsx@@ -12,10 +12,12 @@ import { useTranslation } from 'react-i18next';import { BrowserRouter } from 'react-router-dom';import {+ addNotification,closeBudget,loadBudget,loadGlobalPrefs,setAppState,+ signOut,sync,} from 'loot-core/client/actions';import { SpreadsheetProvider } from 'loot-core/client/SpreadsheetProvider';@@ -25,7 +27,6 @@ import {send,} from 'loot-core/src/platform/client/fetch';-import { useActions } from '../hooks/useActions';import { useMetadataPref } from '../hooks/useMetadataPref';import { installPolyfills } from '../polyfills';import { useDispatch, useSelector } from '../redux';@@ -51,7 +52,6 @@ function AppInner() {const { showBoundary: showErrorBoundary } = useErrorBoundary();const dispatch = useDispatch();const userData = useSelector(state => state.user.data);- const { signOut, addNotification } = useActions();const maybeUpdate = async <T,>(cb?: () => T): Promise<T> => {if (global.Actual.isUpdateReadyForDownload()) {@@ -128,17 +128,19 @@ function AppInner() {useEffect(() => {if (userData?.tokenExpired) {- addNotification({- type: 'error',- id: 'login-expired',- title: t('Login expired'),- sticky: true,- message: t('Login expired, please log in again.'),- button: {- title: t('Go to login'),- action: signOut,- },- });+ dispatch(+ addNotification({+ type: 'error',+ id: 'login-expired',+ title: t('Login expired'),+ sticky: true,+ message: t('Login expired, please login again.'),+ button: {+ title: t('Go to login'),+ action: () => dispatch(signOut()),+ },+ }),+ );}}, [userData, userData?.tokenExpired]);diff --git a/packages/desktop-client/src/components/accounts/Account.tsx b/packages/desktop-client/src/components/accounts/Account.tsxindex 3b5819ac74..d11894911a 100644--- a/packages/desktop-client/src/components/accounts/Account.tsx+++ b/packages/desktop-client/src/components/accounts/Account.tsx@@ -13,6 +13,22 @@ import { debounce } from 'debounce';import { t } from 'i18next';import { v4 as uuidv4 } from 'uuid';+import { unlinkAccount } from 'loot-core/client/accounts/accountsSlice';+import {+ addNotification,+ createPayee,+ getPayees,+ initiallyLoadPayees,+ markAccountRead,+ openAccountCloseModal,+ pushModal,+ reopenAccount,+ replaceModal,+ syncAndDownload,+ updateAccount,+ updateNewTransactions,+} from 'loot-core/client/actions';+import { type AppDispatch } from 'loot-core/client/store';import { validForTransfer } from 'loot-core/client/transfer';import { type UndoState } from 'loot-core/server/undo';import { useFilters } from 'loot-core/src/client/data-hooks/filters';@@ -51,7 +67,6 @@ import {import { useAccountPreviewTransactions } from '../../hooks/useAccountPreviewTransactions';import { useAccounts } from '../../hooks/useAccounts';-import { useActions } from '../../hooks/useActions';import { useCategories } from '../../hooks/useCategories';import { useDateFormat } from '../../hooks/useDateFormat';import { useFailedAccounts } from '../../hooks/useFailedAccounts';@@ -67,7 +82,7 @@ import {} from '../../hooks/useSplitsExpanded';import { useSyncedPref } from '../../hooks/useSyncedPref';import { useTransactionBatchActions } from '../../hooks/useTransactionBatchActions';-import { useSelector } from '../../redux';+import { useSelector, useDispatch } from '../../redux';import { styles, theme } from '../../style';import { Button } from '../common/Button2';import { Text } from '../common/Text';@@ -262,8 +277,6 @@ type AccountInternalProps = {setShowExtraBalances: (newValue: boolean) => void;modalShowing?: boolean;accounts: AccountEntity[];- getPayees: () => Promise<PayeeEntity[]>;- updateAccount: (newAccount: AccountEntity) => void;newTransactions: Array<TransactionEntity['id']>;matchedTransactions: Array<TransactionEntity['id']>;splitsExpandedDispatch: ReturnType<typeof useSplitsExpanded>['dispatch'];@@ -288,7 +301,8 @@ type AccountInternalProps = {categoryGroups: ReturnType<typeof useCategories>['grouped'];hideFraction: boolean;accountsSyncing: string[];-} & ReturnType<typeof useActions>;+ dispatch: AppDispatch;+};type AccountInternalState = {search: string;filterConditions: ConditionEntity[];@@ -421,7 +435,7 @@ class AccountInternal extends PureComponent<// Important that any async work happens last so that the// listeners are set up synchronously- await this.props.initiallyLoadPayees();+ await this.props.dispatch(initiallyLoadPayees());await this.fetchTransactions(this.state.filterConditions);// If there is a pending undo, apply it immediately (this happens@@ -487,7 +501,7 @@ class AccountInternal extends PureComponent<else this.updateQuery(query);if (this.props.accountId) {- this.props.markAccountRead(this.props.accountId);+ this.props.dispatch(markAccountRead(this.props.accountId));}};@@ -609,13 +623,14 @@ class AccountInternal extends PureComponent<const accountId = this.props.accountId;const account = this.props.accounts.find(acct => acct.id === accountId);- await this.props.syncAndDownload(account ? account.id : undefined);+ await this.props.dispatch(+ syncAndDownload(account ? account.id : undefined),+ );};onImport = async () => {const accountId = this.props.accountId;const account = this.props.accounts.find(acct => acct.id === accountId);- const categories = await this.props.getCategories();if (account) {const res = await window.Actual?.openFileDialog({@@ -628,16 +643,19 @@ class AccountInternal extends PureComponent<});if (res) {- this.props.pushModal('import-transactions', {- accountId,- categories,- filename: res[0],- onImported: (didChange: boolean) => {- if (didChange) {- this.fetchTransactions();- }- },- });+ if (accountId && res?.length > 0) {+ this.props.dispatch(+ pushModal('import-transactions', {+ accountId,+ filename: res[0],+ onImported: (didChange: boolean) => {+ if (didChange) {+ this.fetchTransactions();+ }+ },+ }),+ );+ }}}};@@ -669,7 +687,7 @@ class AccountInternal extends PureComponent<}});- this.props.updateNewTransactions(updatedTransaction.id);+ this.props.dispatch(updateNewTransactions(updatedTransaction.id));};canCalculateBalance = () => {@@ -732,10 +750,12 @@ class AccountInternal extends PureComponent<this.fetchTransactions();} catch (error) {console.error('Error applying rules:', error);- this.props.addNotification({- type: 'error',- message: 'Failed to apply rules to transactions',- });+ this.props.dispatch(+ addNotification({+ type: 'error',+ message: 'Failed to apply rules to transactions',+ }),+ );} finally {this.setState({ workingHard: false });}@@ -761,7 +781,7 @@ class AccountInternal extends PureComponent<const account = this.props.accounts.find(account => account.id === this.props.accountId,);- this.props.updateAccount({ ...account, name } as AccountEntity);+ this.props.dispatch(updateAccount({ ...account, name } as AccountEntity));this.setState({ editingName: false, nameError: '' });}};@@ -789,23 +809,27 @@ class AccountInternal extends PureComponent<switch (item) {case 'link':- this.props.pushModal('add-account', {- upgradingAccountId: accountId,- });+ this.props.dispatch(+ pushModal('add-account', {+ upgradingAccountId: accountId,+ }),+ );break;case 'unlink':- this.props.pushModal('confirm-unlink-account', {- accountName: account.name,- onUnlink: () => {- this.props.unlinkAccount(accountId);- },- });+ this.props.dispatch(+ pushModal('confirm-unlink-account', {+ accountName: account.name,+ onUnlink: () => {+ this.props.dispatch(unlinkAccount({ id: accountId }));+ },+ }),+ );break;case 'close':- this.props.openAccountCloseModal(accountId);+ this.props.dispatch(openAccountCloseModal(accountId));break;case 'reopen':- this.props.reopenAccount(accountId);+ this.props.dispatch(reopenAccount(accountId));break;case 'export':const accountName = this.getAccountTitle(account, accountId);@@ -920,7 +944,7 @@ class AccountInternal extends PureComponent<onCreatePayee = (name: string) => {const trimmed = name.trim();if (trimmed !== '') {- return this.props.createPayee(name);+ return this.props.dispatch(createPayee(name));}return null;};@@ -1189,12 +1213,14 @@ class AccountInternal extends PureComponent<);const transactions = ungroupTransactions(data);if (transactions.length > 0) {- this.props.pushModal('confirm-transaction-edit', {- onConfirm: () => {- onConfirm(ids);- },- confirmReason,- });+ this.props.dispatch(+ pushModal('confirm-transaction-edit', {+ onConfirm: () => {+ onConfirm(ids);+ },+ confirmReason,+ }),+ );} else {onConfirm(ids);}@@ -1289,14 +1315,14 @@ class AccountInternal extends PureComponent<],} satisfies NewRuleEntity;- this.props.pushModal('edit-rule', { rule });+ this.props.dispatch(pushModal('edit-rule', { rule }));};onSetTransfer = async (ids: string[]) => {const onConfirmTransfer = async (ids: string[]) => {this.setState({ workingHard: true });- const payees = await this.props.getPayees();+ const payees: PayeeEntity[] = await this.props.dispatch(getPayees());const { data: transactions } = await runQuery(q('transactions').filter({ id: { $oneof: ids } })@@ -1663,10 +1689,8 @@ class AccountInternal extends PureComponent<payees,dateFormat,hideFraction,- addNotification,accountsSyncing,failedAccounts,- replaceModal,showExtraBalances,accountId,categoryId,@@ -1818,10 +1842,13 @@ class AccountInternal extends PureComponent<isFiltered={transactionsFiltered}dateFormat={dateFormat}hideFraction={hideFraction}- addNotification={addNotification}renderEmpty={() =>showEmptyMessage ? (- <EmptyMessage onAdd={() => replaceModal('add-account')} />+ <EmptyMessage+ onAdd={() =>+ this.props.dispatch(replaceModal('add-account'))+ }+ />) : !loading ? (<Viewstyle={{@@ -1866,6 +1893,7 @@ class AccountInternal extends PureComponent<type AccountHackProps = Omit<AccountInternalProps,+ | 'dispatch'| 'splitsExpandedDispatch'| 'onBatchEdit'| 'onBatchDuplicate'@@ -1876,6 +1904,7 @@ type AccountHackProps = Omit<function AccountHack(props: AccountHackProps) {const { dispatch: splitsExpandedDispatch } = useSplitsExpanded();+ const dispatch = useDispatch();const {onBatchEdit,onBatchDuplicate,@@ -1886,6 +1915,7 @@ function AccountHack(props: AccountHackProps) {return (<AccountInternal+ dispatch={dispatch}splitsExpandedDispatch={splitsExpandedDispatch}onBatchEdit={onBatchEdit}onBatchDuplicate={onBatchDuplicate}@@ -1929,7 +1959,6 @@ export function Account() {const filterConditions = location?.state?.filterConditions || [];const savedFiters = useFilters();- const actionCreators = useActions();const schedulesQuery = useMemo(() => accountSchedulesQuery(params.id),@@ -1966,7 +1995,6 @@ export function Account() {accountsSyncing={accountsSyncing}filterConditions={filterConditions}categoryGroups={categoryGroups}- {...actionCreators}accountId={params.id}categoryId={location?.state?.categoryId}location={location}diff --git a/packages/desktop-client/src/components/accounts/AccountSyncCheck.tsx b/packages/desktop-client/src/components/accounts/AccountSyncCheck.tsxindex f7ec29db71..f91425bbae 100644--- a/packages/desktop-client/src/components/accounts/AccountSyncCheck.tsx+++ b/packages/desktop-client/src/components/accounts/AccountSyncCheck.tsx@@ -2,7 +2,7 @@ import React, { useCallback, useRef, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';import { useParams } from 'react-router-dom';-import { unlinkAccount } from 'loot-core/client/actions';+import { unlinkAccount } from 'loot-core/client/accounts/accountsSlice';import { type AccountEntity } from 'loot-core/types/models';import { authorizeBank } from '../../gocardless';@@ -104,7 +104,7 @@ export function AccountSyncCheck() {const unlink = useCallback((acc: AccountEntity) => {if (acc.id) {- dispatch(unlinkAccount(acc.id));+ dispatch(unlinkAccount({ id: acc.id }));}setOpen(false);diff --git a/packages/desktop-client/src/components/admin/UserAccess/UserAccessRow.tsx b/packages/desktop-client/src/components/admin/UserAccess/UserAccessRow.tsxindex 7473156df6..ae9d5915c4 100644--- a/packages/desktop-client/src/components/admin/UserAccess/UserAccessRow.tsx+++ b/packages/desktop-client/src/components/admin/UserAccess/UserAccessRow.tsx@@ -2,12 +2,13 @@import React, { memo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { addNotification, signOut } from 'loot-core/client/actions';import { send } from 'loot-core/platform/client/fetch';import { getUserAccessErrors } from 'loot-core/shared/errors';import { type UserAvailable } from 'loot-core/types/models';-import { useActions } from '../../../hooks/useActions';import { useMetadataPref } from '../../../hooks/useMetadataPref';+import { useDispatch } from '../../../redux';import { theme } from '../../../style';import { View } from '../../common/View';import { Checkbox } from '../../forms';@@ -22,13 +23,13 @@ type UserAccessProps = {export const UserAccessRow = memo(({ access, hovered, onHover }: UserAccessProps) => {const { t } = useTranslation();+ const dispatch = useDispatch();const backgroundFocus = hovered;const [marked, setMarked] = useState(access.owner === 1 || access.haveAccess === 1,);const [cloudFileId] = useMetadataPref('cloudFileId');- const actions = useActions();const handleAccessToggle = async () => {const newValue = !marked;@@ -48,14 +49,16 @@ export const UserAccessRow = memo(});if (someDeletionsFailed) {- actions.addNotification({- type: 'error',- title: t('Access Revocation Incomplete'),- message: t(- 'Some access permissions were not revoked successfully.',- ),- sticky: true,- });+ dispatch(+ addNotification({+ type: 'error',+ title: t('Access Revocation Incomplete'),+ message: t(+ 'Some access permissions were not revoked successfully.',+ ),+ sticky: true,+ }),+ );}}setMarked(newValue);@@ -63,26 +66,30 @@ export const UserAccessRow = memo(const handleError = (error: string) => {if (error === 'token-expired') {- actions.addNotification({- type: 'error',- id: 'login-expired',- title: t('Login expired'),- sticky: true,- message: getUserAccessErrors(error),- button: {- title: t('Go to login'),- action: () => {- actions.signOut();+ dispatch(+ addNotification({+ type: 'error',+ id: 'login-expired',+ title: t('Login expired'),+ sticky: true,+ message: getUserAccessErrors(error),+ button: {+ title: t('Go to login'),+ action: () => {+ dispatch(signOut());+ },},- },- });+ }),+ );} else {- actions.addNotification({- type: 'error',- title: t('Something happened while editing access'),- sticky: true,- message: getUserAccessErrors(error),- });+ dispatch(+ addNotification({+ type: 'error',+ title: t('Something happened while editing access'),+ sticky: true,+ message: getUserAccessErrors(error),+ }),+ );}};diff --git a/packages/desktop-client/src/components/admin/UserDirectory/UserDirectory.tsx b/packages/desktop-client/src/components/admin/UserDirectory/UserDirectory.tsxindex f1464abe25..2d57fc13de 100644--- a/packages/desktop-client/src/components/admin/UserDirectory/UserDirectory.tsx+++ b/packages/desktop-client/src/components/admin/UserDirectory/UserDirectory.tsx@@ -10,6 +10,7 @@ import {} from 'react';import { Trans, useTranslation } from 'react-i18next';+import { addNotification, signOut } from 'loot-core/client/actions';import { pushModal } from 'loot-core/src/client/actions/modals';import { send } from 'loot-core/src/platform/client/fetch';import * as undo from 'loot-core/src/platform/client/undo';@@ -18,7 +19,6 @@ import {type UserEntity,} from 'loot-core/types/models/user';-import { useActions } from '../../../hooks/useActions';import { SelectedProvider, useSelected } from '../../../hooks/useSelected';import { useDispatch } from '../../../redux';import { theme } from '../../../style';@@ -86,7 +86,6 @@ function UserDirectoryContent({const [page, setPage] = useState(0);const [filter, setFilter] = useState('');const dispatch = useDispatch();- const actions = useActions();const { getUserDirectoryErrors } = useGetUserDirectoryErrors();@@ -146,31 +145,42 @@ function UserDirectoryContent({if (error) {if (error === 'token-expired') {- actions.addNotification({- type: 'error',- id: 'login-expired',- title: t('Login expired'),- sticky: true,- message: getUserDirectoryErrors(error),- button: {- title: t('Go to login'),- action: () => actions.signOut(),- },- });+ dispatch(+ addNotification({+ type: 'error',+ id: 'login-expired',+ title: t('Login expired'),+ sticky: true,+ message: getUserDirectoryErrors(error),+ button: {+ title: t('Go to login'),+ action: () => dispatch(signOut()),+ },+ }),+ );} else {- actions.addNotification({- type: 'error',- title: t('Something happened while deleting users'),- sticky: true,- message: getUserDirectoryErrors(error),- });+ dispatch(+ addNotification({+ type: 'error',+ title: t('Something happened while deleting users'),+ sticky: true,+ message: getUserDirectoryErrors(error),+ }),+ );}}await loadUsers();selectedInst.dispatch({ type: 'select-none' });setLoading(false);- }, [actions, loadUsers, selectedInst, setLoading, getUserDirectoryErrors, t]);+ }, [+ setLoading,+ selectedInst,+ loadUsers,+ dispatch,+ t,+ getUserDirectoryErrors,+ ]);const onEditUser = useCallback(user => {diff --git a/packages/desktop-client/src/components/modals/EditAccess.tsx b/packages/desktop-client/src/components/modals/EditAccess.tsxindex 93dacc800c..aaef96cfb3 100644--- a/packages/desktop-client/src/components/modals/EditAccess.tsx+++ b/packages/desktop-client/src/components/modals/EditAccess.tsx@@ -1,12 +1,13 @@import { useEffect, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';+import { addNotification, popModal, signOut } from 'loot-core/client/actions';import { send } from 'loot-core/platform/client/fetch';import { getUserAccessErrors } from 'loot-core/shared/errors';import { type Handlers } from 'loot-core/types/handlers';import { type UserAccessEntity } from 'loot-core/types/models/userAccess';-import { useActions } from '../../hooks/useActions';+import { useDispatch } from '../../redux';import { styles, theme } from '../../style';import { Button } from '../common/Button2';import { Modal, ModalCloseButton, ModalHeader } from '../common/Modal';@@ -26,8 +27,8 @@ export function EditUserAccess({onSave: originalOnSave,}: EditUserAccessProps) {const { t } = useTranslation();+ const dispatch = useDispatch();- const actions = useActions();const [userId, setUserId] = useState(defaultUserAccess.userId ?? '');const [error, setSetError] = useState('');const [availableUsers, setAvailableUsers] = useState<[string, string][]>([]);@@ -49,7 +50,7 @@ export function EditUserAccess({}},);- }, [defaultUserAccess.fileId, actions]);+ }, [defaultUserAccess.fileId]);async function onSave(close: () => void) {const userAccess = {@@ -63,19 +64,21 @@ export function EditUserAccess({close();} else {if (error === 'token-expired') {- actions.addNotification({- type: 'error',- id: 'login-expired',- title: t('Login expired'),- sticky: true,- message: getUserAccessErrors(error),- button: {- title: t('Go to login'),- action: () => {- actions.signOut();+ dispatch(+ addNotification({+ type: 'error',+ id: 'login-expired',+ title: t('Login expired'),+ sticky: true,+ message: getUserAccessErrors(error),+ button: {+ title: t('Go to login'),+ action: () => {+ dispatch(signOut());+ },},- },- });+ }),+ );} else {setSetError(getUserAccessErrors(error));}@@ -135,7 +138,7 @@ export function EditUserAccess({<Buttonvariant="bare"style={{ marginRight: 10 }}- onPress={actions.popModal}+ onPress={() => dispatch(popModal())}>Cancel</Button>diff --git a/packages/desktop-client/src/components/modals/EditUser.tsx b/packages/desktop-client/src/components/modals/EditUser.tsxindex f71961ea03..0e59ada14a 100644--- a/packages/desktop-client/src/components/modals/EditUser.tsx+++ b/packages/desktop-client/src/components/modals/EditUser.tsx@@ -1,13 +1,14 @@import { useState } from 'react';import { Trans, useTranslation } from 'react-i18next';+import { addNotification, popModal, signOut } from 'loot-core/client/actions';import { send } from 'loot-core/platform/client/fetch';import {PossibleRoles,type UserEntity,} from 'loot-core/src/types/models/user';-import { type BoundActions, useActions } from '../../hooks/useActions';+import { useDispatch } from '../../redux';import { styles, theme } from '../../style';import { Button } from '../common/Button2';import { Input } from '../common/Input';@@ -26,7 +27,6 @@ type EditUserProps = {method: 'user-add' | 'user-update',user: User,setError: (error: string) => void,- actions: BoundActions,) => Promise<void>;};@@ -75,13 +75,13 @@ function useGetUserDirectoryErrors() {function useSaveUser() {const { t } = useTranslation();+ const dispatch = useDispatch();const { getUserDirectoryErrors } = useGetUserDirectoryErrors();async function saveUser(method: 'user-add' | 'user-update',user: User,setError: (error: string) => void,- actions: BoundActions,): Promise<boolean> {const { error, id: newId } = (await send(method, user)) || {};if (!error) {@@ -91,19 +91,21 @@ function useSaveUser() {} else {setError(getUserDirectoryErrors(error));if (error === 'token-expired') {- actions.addNotification({- type: 'error',- id: 'login-expired',- title: t('Login expired'),- sticky: true,- message: getUserDirectoryErrors(error),- button: {- title: t('Go to login'),- action: () => {- actions.signOut();+ dispatch(+ addNotification({+ type: 'error',+ id: 'login-expired',+ title: t('Login expired'),+ sticky: true,+ message: getUserDirectoryErrors(error),+ button: {+ title: t('Go to login'),+ action: () => {+ dispatch(signOut());+ },},- },- });+ }),+ );}return false;@@ -138,8 +140,8 @@ export function EditUserFinanceApp({/><EditUserdefaultUser={defaultUser}- onSave={async (method, user, setError, actions) => {- if (await saveUser(method, user, setError, actions)) {+ onSave={async (method, user, setError) => {+ if (await saveUser(method, user, setError)) {originalOnSave(user);close();}@@ -153,8 +155,8 @@ export function EditUserFinanceApp({function EditUser({ defaultUser, onSave: originalOnSave }: EditUserProps) {const { t } = useTranslation();+ const dispatch = useDispatch();- const actions = useActions();const [userName, setUserName] = useState<string>(defaultUser.userName ?? '');const [displayName, setDisplayName] = useState<string>(defaultUser.displayName ?? '',@@ -181,7 +183,7 @@ function EditUser({ defaultUser, onSave: originalOnSave }: EditUserProps) {};const method = user.id ? 'user-update' : 'user-add';- await originalOnSave(method, user, setError, actions);+ await originalOnSave(method, user, setError);}return (@@ -306,7 +308,7 @@ function EditUser({ defaultUser, onSave: originalOnSave }: EditUserProps) {<Buttonvariant="bare"style={{ marginRight: 10 }}- onPress={actions.popModal}+ onPress={() => dispatch(popModal())}><Trans>Cancel</Trans></Button>diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsxindex 9c1092ef96..9765dc6633 100644--- a/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx@@ -11,6 +11,7 @@ import {} from 'loot-core/client/actions';import { amountToInteger } from 'loot-core/src/shared/util';+import { useCategories } from '../../../hooks/useCategories';import { useDateFormat } from '../../../hooks/useDateFormat';import { useSyncedPrefs } from '../../../hooks/useSyncedPrefs';import { useDispatch } from '../../../redux';@@ -145,6 +146,7 @@ export function ImportTransactionsModal({ options }) {const dateFormat = useDateFormat() || 'MM/dd/yyyy';const [prefs, savePrefs] = useSyncedPrefs();const dispatch = useDispatch();+ const categories = useCategories();const [multiplierAmount, setMultiplierAmount] = useState('');const [loadingState, setLoadingState] = useState('parsing');@@ -157,7 +159,7 @@ export function ImportTransactionsModal({ options }) {const [flipAmount, setFlipAmount] = useState(false);const [multiplierEnabled, setMultiplierEnabled] = useState(false);const [reconcile, setReconcile] = useState(true);- const { accountId, categories, onImported } = options;+ const { accountId, onImported } = options;// This cannot be set after parsing the file, because changing it// requires re-parsing the file. This is different from the otherdiff --git a/packages/desktop-client/src/components/modals/OpenIDEnableModal.tsx b/packages/desktop-client/src/components/modals/OpenIDEnableModal.tsxindex deef6d1282..18dbd7b6ca 100644--- a/packages/desktop-client/src/components/modals/OpenIDEnableModal.tsx+++ b/packages/desktop-client/src/components/modals/OpenIDEnableModal.tsx@@ -1,12 +1,13 @@import { useState } from 'react';import { Trans, useTranslation } from 'react-i18next';+import { closeBudget, popModal } from 'loot-core/client/actions';import { send } from 'loot-core/platform/client/fetch';import * as asyncStorage from 'loot-core/platform/server/asyncStorage';import { getOpenIdErrors } from 'loot-core/shared/errors';import { type OpenIdConfig } from 'loot-core/types/models/openid';-import { useActions } from '../../hooks/useActions';+import { useDispatch } from '../../redux';import { theme, styles } from '../../style';import { Error } from '../alerts';import { Button } from '../common/Button2';@@ -24,10 +25,9 @@ export function OpenIDEnableModal({onSave: originalOnSave,}: OpenIDEnableModalProps) {const { t } = useTranslation();+ const dispatch = useDispatch();const [error, setError] = useState('');- const actions = useActions();- const { closeBudget } = useActions();const refreshLoginMethods = useRefreshLoginMethods();async function onSave(config: OpenIdConfig) {@@ -38,7 +38,7 @@ export function OpenIDEnableModal({try {await refreshLoginMethods();await asyncStorage.removeItem('user-token');- await closeBudget();+ await dispatch(closeBudget());} catch (e) {console.error('Failed to cleanup after OpenID enable:', e);setError(@@ -73,7 +73,7 @@ export function OpenIDEnableModal({key="cancel"variant="bare"style={{ marginRight: 10 }}- onPress={actions.popModal}+ onPress={() => dispatch(popModal())}><Trans>Cancel</Trans></Button>,diff --git a/packages/desktop-client/src/components/modals/PasswordEnableModal.tsx b/packages/desktop-client/src/components/modals/PasswordEnableModal.tsxindex 09edbe2ab3..704ceff816 100644--- a/packages/desktop-client/src/components/modals/PasswordEnableModal.tsx+++ b/packages/desktop-client/src/components/modals/PasswordEnableModal.tsx@@ -1,10 +1,11 @@import { useState } from 'react';import { Trans, useTranslation } from 'react-i18next';+import { closeBudget, popModal } from 'loot-core/client/actions';import { send } from 'loot-core/platform/client/fetch';import * as asyncStorage from 'loot-core/src/platform/server/asyncStorage';-import { useActions } from '../../hooks/useActions';+import { useDispatch } from '../../redux';import { theme, styles } from '../../style';import { Error as ErrorAlert } from '../alerts';import { Button } from '../common/Button2';@@ -30,9 +31,9 @@ export function PasswordEnableModal({onSave: originalOnSave,}: PasswordEnableModalProps) {const { t } = useTranslation();+ const dispatch = useDispatch();const [error, setError] = useState<string | null>(null);- const { closeBudget, popModal } = useActions();const multiuserEnabled = useMultiuserEnabled();const availableLoginMethods = useAvailableLoginMethods();const refreshLoginMethods = useRefreshLoginMethods();@@ -59,7 +60,7 @@ export function PasswordEnableModal({originalOnSave?.();await refreshLoginMethods();await asyncStorage.removeItem('user-token');- await closeBudget();+ await dispatch(closeBudget());} else {setError(getErrorMessage(error));}@@ -84,7 +85,7 @@ export function PasswordEnableModal({<Buttonvariant="bare"style={{ fontSize: 15, marginRight: 10 }}- onPress={() => popModal()}+ onPress={() => dispatch(popModal())}><Trans>Cancel</Trans></Button>@@ -101,7 +102,7 @@ export function PasswordEnableModal({<Buttonvariant="bare"style={{ fontSize: 15, marginRight: 10 }}- onPress={() => popModal()}+ onPress={() => dispatch(popModal())}><Trans>Cancel</Trans></Button>diff --git a/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.jsx b/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.jsxindex d72bd8e8cf..10c3fd8777 100644--- a/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.jsx+++ b/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.jsx@@ -2,11 +2,11 @@ import React, { useState } from 'react';import { useTranslation, Trans } from 'react-i18next';import {- closeModal,linkAccount,linkAccountSimpleFin,unlinkAccount,-} from 'loot-core/client/actions';+} from 'loot-core/client/accounts/accountsSlice';+import { closeModal } from 'loot-core/client/actions';import { useAccounts } from '../../hooks/useAccounts';import { useDispatch } from '../../redux';@@ -61,7 +61,7 @@ export function SelectLinkedAccountsModal({localAccounts.filter(acc => acc.account_id).filter(acc => !chosenLocalAccountIds.includes(acc.id))- .forEach(acc => dispatch(unlinkAccount(acc.id)));+ .forEach(acc => dispatch(unlinkAccount({ id: acc.id })));// Link new accountsObject.entries(chosenAccounts).forEach(@@ -80,26 +80,28 @@ export function SelectLinkedAccountsModal({// Finally link the matched accountif (syncSource === 'simpleFin') {dispatch(- linkAccountSimpleFin(+ linkAccountSimpleFin({externalAccount,- chosenLocalAccountId !== addOnBudgetAccountOption.id &&+ upgradingId:+ chosenLocalAccountId !== addOnBudgetAccountOption.id &&chosenLocalAccountId !== addOffBudgetAccountOption.id- ? chosenLocalAccountId- : undefined,+ ? chosenLocalAccountId+ : undefined,offBudget,- ),+ }),);} else {dispatch(- linkAccount(+ linkAccount({requisitionId,- externalAccount,- chosenLocalAccountId !== addOnBudgetAccountOption.id &&+ account: externalAccount,+ upgradingId:+ chosenLocalAccountId !== addOnBudgetAccountOption.id &&chosenLocalAccountId !== addOffBudgetAccountOption.id- ? chosenLocalAccountId- : undefined,+ ? chosenLocalAccountId+ : undefined,offBudget,- ),+ }),);}},diff --git a/packages/desktop-client/src/components/modals/TransferOwnership.tsx b/packages/desktop-client/src/components/modals/TransferOwnership.tsxindex d1619964ff..72c886ba45 100644--- a/packages/desktop-client/src/components/modals/TransferOwnership.tsx+++ b/packages/desktop-client/src/components/modals/TransferOwnership.tsx@@ -1,14 +1,17 @@import { useEffect, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';-import { addNotification, closeAndLoadBudget } from 'loot-core/client/actions';+import {+ addNotification,+ closeAndLoadBudget,+ popModal,+} from 'loot-core/client/actions';import { send } from 'loot-core/platform/client/fetch';import { getUserAccessErrors } from 'loot-core/shared/errors';import { type Budget } from 'loot-core/types/budget';import { type RemoteFile, type SyncedLocalFile } from 'loot-core/types/file';import { type Handlers } from 'loot-core/types/handlers';-import { useActions } from '../../hooks/useActions';import { useMetadataPref } from '../../hooks/useMetadataPref';import { useDispatch, useSelector } from '../../redux';import { styles, theme } from '../../style';@@ -30,7 +33,6 @@ export function TransferOwnership({const { t } = useTranslation();const userData = useSelector(state => state.user.data);- const actions = useActions();const [userId, setUserId] = useState('');const [error, setError] = useState<string | null>(null);const [availableUsers, setAvailableUsers] = useState<[string, string][]>([]);@@ -49,14 +51,16 @@ export function TransferOwnership({if (!data) {setAvailableUsers([]);} else if ('error' in data) {- addNotification({- type: 'error',- title: t('Error getting users'),- message: t(- 'Failed to complete ownership transfer. Please try again.',- ),- sticky: true,- });+ dispatch(+ addNotification({+ type: 'error',+ title: t('Error getting users'),+ message: t(+ 'Failed to complete ownership transfer. Please try again.',+ ),+ sticky: true,+ }),+ );} else {setAvailableUsers(data@@ -71,7 +75,7 @@ export function TransferOwnership({}},);- }, [userData?.userId, currentFile?.owner, t]);+ }, [userData?.userId, currentFile?.owner, t, dispatch]);async function onSave() {if (cloudFileId) {@@ -165,7 +169,10 @@ export function TransferOwnership({style={{ marginTop: 20 }}>{error && <Text style={{ color: theme.errorText }}>{error}</Text>}- <Button style={{ marginRight: 10 }} onPress={actions.popModal}>+ <Button+ style={{ marginRight: 10 }}+ onPress={() => dispatch(popModal())}+ ><Trans>Cancel</Trans></Button>@@ -183,14 +190,16 @@ export function TransferOwnership({);close();} catch (error) {- addNotification({- type: 'error',- title: t('Failed to transfer ownership'),- message: t(- 'Failed to complete ownership transfer. Please try again.',- ),- sticky: true,- });+ dispatch(+ addNotification({+ type: 'error',+ title: t('Failed to transfer ownership'),+ message: t(+ 'Failed to complete ownership transfer. Please try again.',+ ),+ sticky: true,+ }),+ );setIsTransferring(false);}}}diff --git a/packages/desktop-client/src/components/reports/reports/Calendar.tsx b/packages/desktop-client/src/components/reports/reports/Calendar.tsxindex d4a723f671..77412a36c9 100644--- a/packages/desktop-client/src/components/reports/reports/Calendar.tsx+++ b/packages/desktop-client/src/components/reports/reports/Calendar.tsx@@ -605,7 +605,6 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {isFiltered={() => true}dateFormat={dateFormat}hideFraction={false}- addNotification={addNotification}renderEmpty={() => (<Viewstyle={{diff --git a/packages/desktop-client/src/components/sidebar/Accounts.tsx b/packages/desktop-client/src/components/sidebar/Accounts.tsxindex b260c15555..fb8eadfaea 100644--- a/packages/desktop-client/src/components/sidebar/Accounts.tsx+++ b/packages/desktop-client/src/components/sidebar/Accounts.tsx@@ -1,8 +1,8 @@import React, { useState } from 'react';import { useTranslation } from 'react-i18next';-import { moveAccount } from 'loot-core/src/client/actions';-import * as queries from 'loot-core/src/client/queries';+import { moveAccount } from 'loot-core/client/accounts/accountsSlice';+import * as queries from 'loot-core/client/queries';import { type AccountEntity } from 'loot-core/types/models';import { useAccounts } from '../../hooks/useAccounts';@@ -64,7 +64,7 @@ export function Accounts() {targetIdToMove = idx < accounts.length ? accounts[idx].id : null;}- dispatch(moveAccount(id, targetIdToMove));+ dispatch(moveAccount({ id, targetId: targetIdToMove as string }));}const onToggleClosedAccounts = () => {diff --git a/packages/desktop-client/src/components/transactions/TransactionList.jsx b/packages/desktop-client/src/components/transactions/TransactionList.jsxindex 89b6706875..7e39f76272 100644--- a/packages/desktop-client/src/components/transactions/TransactionList.jsx+++ b/packages/desktop-client/src/components/transactions/TransactionList.jsx@@ -78,7 +78,6 @@ export function TransactionList({isFiltered,dateFormat,hideFraction,- addNotification,renderEmpty,onSort,sortField,@@ -228,7 +227,6 @@ export function TransactionList({isFiltered={isFiltered}dateFormat={dateFormat}hideFraction={hideFraction}- addNotification={addNotification}headerContent={headerContent}renderEmpty={renderEmpty}onSave={onSave}diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.jsx b/packages/desktop-client/src/components/transactions/TransactionsTable.jsxindex 2a4949a8b1..5b7f134668 100644--- a/packages/desktop-client/src/components/transactions/TransactionsTable.jsx+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.jsx@@ -20,7 +20,7 @@ import {isValid as isDateValid,} from 'date-fns';-import { pushModal } from 'loot-core/client/actions';+import { addNotification, pushModal } from 'loot-core/client/actions';import { useCachedSchedules } from 'loot-core/src/client/data-hooks/schedules';import {getAccountsById,@@ -2103,6 +2103,7 @@ function TransactionTableInner({}export const TransactionTable = forwardRef((props, ref) => {+ const dispatch = useDispatch();const [newTransactions, setNewTransactions] = useState(null);const [prevIsAdding, setPrevIsAdding] = useState(false);const splitsExpanded = useSplitsExpanded();@@ -2235,10 +2236,12 @@ export const TransactionTable = forwardRef((props, ref) => {useEffect(() => {if (shouldAdd.current) {if (newTransactions[0].account == null) {- props.addNotification({- type: 'error',- message: 'Account is a required field',- });+ dispatch(+ addNotification({+ type: 'error',+ message: 'Account is a required field',+ }),+ );newNavigator.onEdit('temp', 'account');} else {const transactions = latestState.current.newTransactions;diff --git a/packages/desktop-client/src/global-events.ts b/packages/desktop-client/src/global-events.tsindex 97f3dcd211..d21d037ae7 100644--- a/packages/desktop-client/src/global-events.ts+++ b/packages/desktop-client/src/global-events.ts@@ -1,28 +1,40 @@// @ts-strict-ignore-import { type Store } from 'redux';-+import {+ addGenericErrorNotification,+ addNotification,+ closeBudgetUI,+ closeModal,+ getAccounts,+ getCategories,+ getPayees,+ loadPrefs,+ pushModal,+ reloadApp,+ replaceModal,+ setAppState,+} from 'loot-core/client/actions';+import { type AppStore } from 'loot-core/client/store';import * as sharedListeners from 'loot-core/src/client/shared-listeners';-import type { State } from 'loot-core/src/client/state-types';import { listen } from 'loot-core/src/platform/client/fetch';import * as undo from 'loot-core/src/platform/client/undo';-import { type BoundActions } from './hooks/useActions';--export function handleGlobalEvents(actions: BoundActions, store: Store<State>) {+export function handleGlobalEvents(store: AppStore) {listen('server-error', () => {- actions.addGenericErrorNotification();+ store.dispatch(addGenericErrorNotification());});listen('orphaned-payees', ({ orphanedIds, updatedPayeeIds }) => {// Right now, it prompts to merge into the first payee- actions.pushModal('merge-unused-payees', {- payeeIds: orphanedIds,- targetPayeeId: updatedPayeeIds[0],- });+ store.dispatch(+ pushModal('merge-unused-payees', {+ payeeIds: orphanedIds,+ targetPayeeId: updatedPayeeIds[0],+ }),+ );});listen('schedules-offline', () => {- actions.pushModal('schedule-posts-offline-notification');+ store.dispatch(pushModal('schedule-posts-offline-notification'));});// This is experimental: we sync data locally automatically when@@ -36,7 +48,7 @@ export function handleGlobalEvents(actions: BoundActions, store: Store<State>) {if (event.type === 'applied') {const tables = event.tables;if (tables.includes('payees') || tables.includes('payee_mapping')) {- actions.getPayees();+ store.dispatch(getPayees());}}}@@ -45,16 +57,18 @@ export function handleGlobalEvents(actions: BoundActions, store: Store<State>) {// TODO: Should this run on mobile too?listen('sync-event', async ({ type }) => {if (type === 'unauthorized') {- actions.addNotification({- type: 'warning',- message: 'Unable to authenticate with server',- sticky: true,- id: 'auth-issue',- });+ store.dispatch(+ addNotification({+ type: 'warning',+ message: 'Unable to authenticate with server',+ sticky: true,+ id: 'auth-issue',+ }),+ );}});- sharedListeners.listenForSyncEvent(actions, store);+ sharedListeners.listenForSyncEvent(store);listen('undo-event', undoState => {const { tables, undoTag } = undoState;@@ -65,11 +79,11 @@ export function handleGlobalEvents(actions: BoundActions, store: Store<State>) {tables.includes('category_groups') ||tables.includes('category_mapping')) {- promises.push(actions.getCategories());+ promises.push(store.dispatch(getCategories()));}if (tables.includes('accounts')) {- promises.push(actions.getAccounts());+ promises.push(store.dispatch(getAccounts()));}const tagged = undo.getTaggedState(undoTag);@@ -86,10 +100,10 @@ export function handleGlobalEvents(actions: BoundActions, store: Store<State>) {modalStack.length === 0 ||modalStack[modalStack.length - 1].name !== tagged.openModal) {- actions.replaceModal(tagged.openModal);+ store.dispatch(replaceModal(tagged.openModal));}} else {- actions.closeModal();+ store.dispatch(closeModal());if (window.location.href.replace(window.location.origin, '') !==@@ -107,44 +121,46 @@ export function handleGlobalEvents(actions: BoundActions, store: Store<State>) {});listen('fallback-write-error', () => {- actions.addNotification({- type: 'error',- title: 'Unable to save changes',- sticky: true,- message:- 'This browser only supports using the app in one tab at a time, ' +- 'and another tab has opened the app. No changes will be saved ' +- 'from this tab; please close it and continue working in the other one.',- });+ store.dispatch(+ addNotification({+ type: 'error',+ title: 'Unable to save changes',+ sticky: true,+ message:+ 'This browser only supports using the app in one tab at a time, ' ++ 'and another tab has opened the app. No changes will be saved ' ++ 'from this tab; please close it and continue working in the other one.',+ }),+ );});listen('start-load', () => {- actions.closeBudgetUI();- actions.setAppState({ loadingText: '' });+ store.dispatch(closeBudgetUI());+ store.dispatch(setAppState({ loadingText: '' }));});listen('finish-load', () => {- actions.closeModal();- actions.setAppState({ loadingText: null });- actions.loadPrefs();+ store.dispatch(closeModal());+ store.dispatch(setAppState({ loadingText: null }));+ store.dispatch(loadPrefs());});listen('start-import', () => {- actions.closeBudgetUI();+ store.dispatch(closeBudgetUI());});listen('finish-import', () => {- actions.closeModal();- actions.setAppState({ loadingText: null });- actions.loadPrefs();+ store.dispatch(closeModal());+ store.dispatch(setAppState({ loadingText: null }));+ store.dispatch(loadPrefs());});listen('show-budgets', () => {- actions.closeBudgetUI();- actions.setAppState({ loadingText: null });+ store.dispatch(closeBudgetUI());+ store.dispatch(setAppState({ loadingText: null }));});listen('api-fetch-redirected', () => {- actions.reloadApp();+ store.dispatch(reloadApp());});}diff --git a/packages/desktop-client/src/hooks/useActions.ts b/packages/desktop-client/src/hooks/useActions.tsdeleted file mode 100644index f1ed715c7e..0000000000--- a/packages/desktop-client/src/hooks/useActions.ts+++ /dev/null@@ -1,33 +0,0 @@-import { useMemo } from 'react';--import { bindActionCreators } from 'redux';-import { type ThunkAction } from 'redux-thunk';--import * as actions from 'loot-core/src/client/actions';-import type { Action, State } from 'loot-core/src/client/state-types';--import { useDispatch } from '../redux';--type ActionReturnType<T extends (...args: unknown[]) => unknown> =- ReturnType<T> extends ThunkAction<infer ReturnType, State, never, Action>- ? ReturnType- : ReturnType<T>;--export type BoundActions = {- [Key in keyof typeof actions]: (- ...args: Parameters<(typeof actions)[Key]>- ) => // @ts-expect-error temporarily disabling this TS error; eventually the `useActions` hook should be removed- ActionReturnType<(typeof actions)[Key]>;-};--// https://react-redux.js.org/api/hooks#recipe-useactions-/**- * @deprecated please use actions directly with `useAppDispatch`- * @see https://github.com/reduxjs/react-redux/issues/1252#issuecomment-488160930- **/-export function useActions() {- const dispatch = useDispatch();- return useMemo(() => {- return bindActionCreators(actions, dispatch);- }, [dispatch]) as unknown as BoundActions;-}diff --git a/packages/desktop-client/src/index.tsx b/packages/desktop-client/src/index.tsxindex 9612414cc7..22d27b7b50 100644--- a/packages/desktop-client/src/index.tsx+++ b/packages/desktop-client/src/index.tsx@@ -13,6 +13,7 @@ import { Provider } from 'react-redux';import { bindActionCreators } from '@reduxjs/toolkit';import { createRoot } from 'react-dom/client';+import * as accountsSlice from 'loot-core/src/client/accounts/accountsSlice';import * as actions from 'loot-core/src/client/actions';import { runQuery } from 'loot-core/src/client/query-helpers';import { store } from 'loot-core/src/client/store';@@ -23,24 +24,28 @@ import { AuthProvider } from './auth/AuthProvider';import { App } from './components/App';import { ServerProvider } from './components/ServerContext';import { handleGlobalEvents } from './global-events';-import { type BoundActions } from './hooks/useActions';// See https://github.com/WICG/focus-visible. Only makes the blue// focus outline appear from keyboard events.import 'focus-visible';const boundActions = bindActionCreators(- actions,+ {+ ...actions,+ ...accountsSlice.actions,+ },store.dispatch,-) as unknown as BoundActions;+);// Listen for global events from the server or main process-handleGlobalEvents(boundActions, store);+handleGlobalEvents(store);declare global {// eslint-disable-next-line @typescript-eslint/consistent-type-definitionsinterface Window {- __actionsForMenu: BoundActions & { inputFocused: typeof inputFocused };+ __actionsForMenu: typeof boundActions & {+ inputFocused: typeof inputFocused;+ };$send: typeof send;$query: typeof runQuery;diff --git a/packages/loot-core/src/client/accounts/accountsSlice.ts b/packages/loot-core/src/client/accounts/accountsSlice.tsnew file mode 100644index 0000000000..6fd078bf41--- /dev/null+++ b/packages/loot-core/src/client/accounts/accountsSlice.ts@@ -0,0 +1,322 @@+import { createSlice, type PayloadAction } from '@reduxjs/toolkit';++import { send } from '../../platform/client/fetch';+import { type AccountEntity, type TransactionEntity } from '../../types/models';+import { addNotification, getAccounts, getPayees } from '../actions';+import * as constants from '../constants';+import { createAppAsyncThunk } from '../redux';+import { type AppDispatch } from '../store';++const sliceName = 'account';++const initialState: AccountState = {+ failedAccounts: {},+ accountsSyncing: [],+};++type SetAccountsSyncingPayload = {+ ids: Array<AccountEntity['id']>;+};++type MarkAccountFailedPayload = {+ id: AccountEntity['id'];+ errorType: string;+ errorCode: string;+};++type MarkAccountSuccessPayload = {+ id: AccountEntity['id'];+};++type AccountState = {+ failedAccounts: {+ [key: AccountEntity['id']]: { type: string; code: string };+ };+ accountsSyncing: Array<AccountEntity['id']>;+};++const accountsSlice = createSlice({+ name: sliceName,+ initialState,+ reducers: {+ setAccountsSyncing(+ state,+ action: PayloadAction<SetAccountsSyncingPayload>,+ ) {+ state.accountsSyncing = action.payload.ids;+ },+ markAccountFailed(state, action: PayloadAction<MarkAccountFailedPayload>) {+ state.failedAccounts[action.payload.id] = {+ type: action.payload.errorType,+ code: action.payload.errorCode,+ };+ },+ markAccountSuccess(+ state,+ action: PayloadAction<MarkAccountSuccessPayload>,+ ) {+ delete state.failedAccounts[action.payload.id];+ },+ },+});++type UnlinkAccountPayload = {+ id: AccountEntity['id'];+};++export const unlinkAccount = createAppAsyncThunk(+ 'accounts/unlinkAccount',+ async ({ id }: UnlinkAccountPayload, { dispatch }) => {+ const { markAccountSuccess } = accountsSlice.actions;++ await send('account-unlink', { id });+ dispatch(markAccountSuccess({ id }));+ await dispatch(getAccounts());+ },+);++type LinkAccountPayload = {+ requisitionId: string;+ account: unknown;+ upgradingId?: AccountEntity['id'];+ offBudget?: boolean;+};++export const linkAccount = createAppAsyncThunk(+ `${sliceName}/linkAccount`,+ async (+ { requisitionId, account, upgradingId, offBudget }: LinkAccountPayload,+ { dispatch },+ ) => {+ await send('gocardless-accounts-link', {+ requisitionId,+ account,+ upgradingId,+ offBudget,+ });+ await dispatch(getPayees());+ await dispatch(getAccounts());+ },+);++type LinkAccountSimpleFinPayload = {+ externalAccount: unknown;+ upgradingId?: AccountEntity['id'];+ offBudget?: boolean;+};++export const linkAccountSimpleFin = createAppAsyncThunk(+ `${sliceName}/linkAccountSimpleFin`,+ async (+ { externalAccount, upgradingId, offBudget }: LinkAccountSimpleFinPayload,+ { dispatch },+ ) => {+ await send('simplefin-accounts-link', {+ externalAccount,+ upgradingId,+ offBudget,+ });+ await dispatch(getPayees());+ await dispatch(getAccounts());+ },+);++type SyncResponse = {+ errors: Array<{+ type: string;+ category: string;+ code: string;+ message: string;+ internal?: string;+ }>;+ newTransactions: Array<TransactionEntity['id']>;+ matchedTransactions: Array<TransactionEntity['id']>;+ updatedAccounts: Array<AccountEntity['id']>;+};++function handleSyncResponse(+ accountId: AccountEntity['id'],+ res: SyncResponse,+ dispatch: AppDispatch,+ resNewTransactions: Array<TransactionEntity['id']>,+ resMatchedTransactions: Array<TransactionEntity['id']>,+ resUpdatedAccounts: Array<AccountEntity['id']>,+) {+ const { errors, newTransactions, matchedTransactions, updatedAccounts } = res;+ const { markAccountFailed, markAccountSuccess } = accountsSlice.actions;++ // Mark the account as failed or succeeded (depending on sync output)+ const [error] = errors;+ if (error) {+ // We only want to mark the account as having problem if it+ // was a real syncing error.+ if (error.type === 'SyncError') {+ dispatch(+ markAccountFailed({+ id: accountId,+ errorType: error.category,+ errorCode: error.code,+ }),+ );+ }+ } else {+ dispatch(markAccountSuccess({ id: accountId }));+ }++ // Dispatch errors (if any)+ errors.forEach(error => {+ if (error.type === 'SyncError') {+ dispatch(+ addNotification({+ type: 'error',+ message: error.message,+ }),+ );+ } else {+ dispatch(+ addNotification({+ type: 'error',+ message: error.message,+ internal: error.internal,+ }),+ );+ }+ });++ resNewTransactions.push(...newTransactions);+ resMatchedTransactions.push(...matchedTransactions);+ resUpdatedAccounts.push(...updatedAccounts);++ return newTransactions.length > 0 || matchedTransactions.length > 0;+}++type SyncAccountsPayload = {+ id?: AccountEntity['id'];+};++export const syncAccounts = createAppAsyncThunk(+ `${sliceName}/syncAccounts`,+ async ({ id }: SyncAccountsPayload, { dispatch, getState }) => {+ // Disallow two parallel sync operations+ const accountsState = getState().account;+ if (accountsState.accountsSyncing.length > 0) {+ return false;+ }++ const batchSync = !id;++ // Build an array of IDs for accounts to sync.. if no `id` provided+ // then we assume that all accounts should be synced+ const queriesState = getState().queries;+ let accountIdsToSync = !batchSync+ ? [id]+ : queriesState.accounts+ .filter(+ ({ bank, closed, tombstone }) => !!bank && !closed && !tombstone,+ )+ .sort((a, b) =>+ a.offbudget === b.offbudget+ ? a.sort_order - b.sort_order+ : a.offbudget - b.offbudget,+ )+ .map(({ id }) => id);++ const { setAccountsSyncing } = accountsSlice.actions;+ dispatch(setAccountsSyncing({ ids: accountIdsToSync }));++ const accountsData: AccountEntity[] = await send('accounts-get');+ const simpleFinAccounts = accountsData.filter(+ a => a.account_sync_source === 'simpleFin',+ );++ let isSyncSuccess = false;+ const newTransactions: Array<TransactionEntity['id']> = [];+ const matchedTransactions: Array<TransactionEntity['id']> = [];+ const updatedAccounts: Array<AccountEntity['id']> = [];++ if (batchSync && simpleFinAccounts.length > 0) {+ console.log('Using SimpleFin batch sync');++ const res = await send('simplefin-batch-sync', {+ ids: simpleFinAccounts.map(a => a.id),+ });++ for (const account of res) {+ const success = handleSyncResponse(+ account.accountId,+ account.res,+ dispatch,+ newTransactions,+ matchedTransactions,+ updatedAccounts,+ );+ if (success) isSyncSuccess = true;+ }++ accountIdsToSync = accountIdsToSync.filter(+ id => !simpleFinAccounts.find(sfa => sfa.id === id),+ );+ }++ // Loop through the accounts and perform sync operation.. one by one+ for (let idx = 0; idx < accountIdsToSync.length; idx++) {+ const accountId = accountIdsToSync[idx];++ // Perform sync operation+ const res = await send('accounts-bank-sync', {+ ids: [accountId],+ });++ const success = handleSyncResponse(+ accountId,+ res,+ dispatch,+ newTransactions,+ matchedTransactions,+ updatedAccounts,+ );++ if (success) isSyncSuccess = true;++ // Dispatch the ids for the accounts that are yet to be synced+ dispatch(setAccountsSyncing({ ids: accountIdsToSync.slice(idx + 1) }));+ }++ // Set new transactions+ dispatch({+ type: constants.SET_NEW_TRANSACTIONS,+ newTransactions,+ matchedTransactions,+ updatedAccounts,+ });++ // Reset the sync state back to empty (fallback in case something breaks+ // in the logic above)+ dispatch(setAccountsSyncing({ ids: [] }));+ return isSyncSuccess;+ },+);++type MoveAccountPayload = {+ id: AccountEntity['id'];+ targetId: AccountEntity['id'];+};++export const moveAccount = createAppAsyncThunk(+ `${sliceName}/moveAccount`,+ async ({ id, targetId }: MoveAccountPayload, { dispatch }) => {+ await send('account-move', { id, targetId });+ await dispatch(getAccounts());+ await dispatch(getPayees());+ },+);++export const { name, reducer, getInitialState } = accountsSlice;+export const actions = {+ ...accountsSlice.actions,+ linkAccount,+ linkAccountSimpleFin,+ moveAccount,+ unlinkAccount,+ syncAccounts,+};diff --git a/packages/loot-core/src/client/actions/account.ts b/packages/loot-core/src/client/actions/account.tsdeleted file mode 100644index e7dd9b6991..0000000000--- a/packages/loot-core/src/client/actions/account.ts+++ /dev/null@@ -1,341 +0,0 @@-// @ts-strict-ignore-import { send } from '../../platform/client/fetch';-import * as constants from '../constants';-import type {- AccountSyncStatusAction,- SetAccountsSyncingAction,-} from '../state-types/account';-import type {- MarkAccountReadAction,- SetLastTransactionAction,- UpdateNewTransactionsAction,-} from '../state-types/queries';-import { type AppDispatch, type GetRootState } from '../store';--import { addNotification } from './notifications';-import { getPayees, getAccounts } from './queries';--export function setAccountsSyncing(- ids: SetAccountsSyncingAction['ids'],-): SetAccountsSyncingAction {- return {- type: constants.SET_ACCOUNTS_SYNCING,- ids,- };-}--export function markAccountFailed(- id: AccountSyncStatusAction['id'],- errorType?: string,- errorCode?: string,-): AccountSyncStatusAction {- return {- type: 'ACCOUNT_SYNC_STATUS',- id,- failed: true,- errorType,- errorCode,- };-}-export function markAccountSuccess(- id: AccountSyncStatusAction['id'],-): AccountSyncStatusAction {- return {- type: 'ACCOUNT_SYNC_STATUS',- id,- failed: false,- };-}--export function unlinkAccount(id: string) {- return async (dispatch: AppDispatch) => {- await send('account-unlink', { id });- dispatch(markAccountSuccess(id));- dispatch(getAccounts());- };-}--export function linkAccount(- requisitionId: string,- account: unknown,- upgradingId?: string,- offBudget?: boolean,-) {- return async (dispatch: AppDispatch) => {- await send('gocardless-accounts-link', {- requisitionId,- account,- upgradingId,- offBudget,- });- await dispatch(getPayees());- await dispatch(getAccounts());- };-}--export function linkAccountSimpleFin(- externalAccount: unknown,- upgradingId?: string,- offBudget?: boolean,-) {- return async (dispatch: AppDispatch) => {- await send('simplefin-accounts-link', {- externalAccount,- upgradingId,- offBudget,- });- await dispatch(getPayees());- await dispatch(getAccounts());- };-}--function handleSyncResponse(- accountId,- res,- dispatch,- resNewTransactions,- resMatchedTransactions,- resUpdatedAccounts,-) {- const { errors, newTransactions, matchedTransactions, updatedAccounts } = res;-- // Mark the account as failed or succeeded (depending on sync output)- const [error] = errors;- if (error) {- // We only want to mark the account as having problem if it- // was a real syncing error.- if (error.type === 'SyncError') {- dispatch(markAccountFailed(accountId, error.category, error.code));- }- } else {- dispatch(markAccountSuccess(accountId));- }-- // Dispatch errors (if any)- errors.forEach(error => {- if (error.type === 'SyncError') {- dispatch(- addNotification({- type: 'error',- message: error.message,- }),- );- } else {- dispatch(- addNotification({- type: 'error',- message: error.message,- internal: error.internal,- }),- );- }- });-- resNewTransactions.push(...newTransactions);- resMatchedTransactions.push(...matchedTransactions);- resUpdatedAccounts.push(...updatedAccounts);-- return newTransactions.length > 0 || matchedTransactions.length > 0;-}--export function syncAccounts(id?: string) {- return async (dispatch: AppDispatch, getState: GetRootState) => {- // Disallow two parallel sync operations- if (getState().account.accountsSyncing.length > 0) {- return false;- }-- const batchSync = !id;-- // Build an array of IDs for accounts to sync.. if no `id` provided- // then we assume that all accounts should be synced- let accountIdsToSync = !batchSync- ? [id]- : getState()- .queries.accounts.filter(- ({ bank, closed, tombstone }) => !!bank && !closed && !tombstone,- )- .sort((a, b) =>- a.offbudget === b.offbudget- ? a.sort_order - b.sort_order- : a.offbudget - b.offbudget,- )- .map(({ id }) => id);-- dispatch(setAccountsSyncing(accountIdsToSync));-- const accountsData = await send('accounts-get');- const simpleFinAccounts = accountsData.filter(- a => a.account_sync_source === 'simpleFin',- );-- let isSyncSuccess = false;- const newTransactions = [];- const matchedTransactions = [];- const updatedAccounts = [];-- if (batchSync && simpleFinAccounts.length > 0) {- console.log('Using SimpleFin batch sync');-- const res = await send('simplefin-batch-sync', {- ids: simpleFinAccounts.map(a => a.id),- });-- for (const account of res) {- const success = handleSyncResponse(- account.accountId,- account.res,- dispatch,- newTransactions,- matchedTransactions,- updatedAccounts,- );- if (success) isSyncSuccess = true;- }-- accountIdsToSync = accountIdsToSync.filter(- id => !simpleFinAccounts.find(sfa => sfa.id === id),- );- }-- // Loop through the accounts and perform sync operation.. one by one- for (let idx = 0; idx < accountIdsToSync.length; idx++) {- const accountId = accountIdsToSync[idx];-- // Perform sync operation- const res = await send('accounts-bank-sync', {- ids: [accountId],- });-- const success = handleSyncResponse(- accountId,- res,- dispatch,- newTransactions,- matchedTransactions,- updatedAccounts,- );-- if (success) isSyncSuccess = true;-- // Dispatch the ids for the accounts that are yet to be synced- dispatch(setAccountsSyncing(accountIdsToSync.slice(idx + 1)));- }-- // Set new transactions- dispatch({- type: constants.SET_NEW_TRANSACTIONS,- newTransactions,- matchedTransactions,- updatedAccounts,- });-- // Reset the sync state back to empty (fallback in case something breaks- // in the logic above)- dispatch(setAccountsSyncing([]));- return isSyncSuccess;- };-}--// Remember the last transaction manually added to the system-export function setLastTransaction(- transaction: SetLastTransactionAction['transaction'],-): SetLastTransactionAction {- return {- type: constants.SET_LAST_TRANSACTION,- transaction,- };-}--export function parseTransactions(filepath, options) {- return async () => {- return await send('transactions-parse-file', {- filepath,- options,- });- };-}--export function importPreviewTransactions(id: string, transactions) {- return async (dispatch: AppDispatch): Promise<boolean> => {- const { errors = [], updatedPreview } = await send('transactions-import', {- accountId: id,- transactions,- isPreview: true,- });-- errors.forEach(error => {- dispatch(- addNotification({- type: 'error',- message: error.message,- }),- );- });-- return updatedPreview;- };-}--export function importTransactions(id: string, transactions, reconcile = true) {- return async (dispatch: AppDispatch): Promise<boolean> => {- if (!reconcile) {- await send('api/transactions-add', {- accountId: id,- transactions,- });-- return true;- }-- const {- errors = [],- added,- updated,- } = await send('transactions-import', {- accountId: id,- transactions,- isPreview: false,- });-- errors.forEach(error => {- dispatch(- addNotification({- type: 'error',- message: error.message,- }),- );- });-- dispatch({- type: constants.SET_NEW_TRANSACTIONS,- newTransactions: added,- matchedTransactions: updated,- updatedAccounts: added.length > 0 ? [id] : [],- });-- return added.length > 0 || updated.length > 0;- };-}--export function updateNewTransactions(changedId): UpdateNewTransactionsAction {- return {- type: constants.UPDATE_NEW_TRANSACTIONS,- changedId,- };-}--export function markAccountRead(accountId): MarkAccountReadAction {- return {- type: constants.MARK_ACCOUNT_READ,- accountId,- };-}--export function moveAccount(id, targetId) {- return async (dispatch: AppDispatch) => {- await send('account-move', { id, targetId });- dispatch(getAccounts());- dispatch(getPayees());- };-}diff --git a/packages/loot-core/src/client/actions/budgets.ts b/packages/loot-core/src/client/actions/budgets.tsindex 4a36f1f49f..cac82a0f76 100644--- a/packages/loot-core/src/client/actions/budgets.ts+++ b/packages/loot-core/src/client/actions/budgets.ts@@ -231,7 +231,7 @@ export function importBudget(};}-export function uploadBudget(id: string) {+export function uploadBudget(id?: string) {return async (dispatch: AppDispatch) => {const { error } = await send('upload-budget', { id });if (error) {diff --git a/packages/loot-core/src/client/actions/index.ts b/packages/loot-core/src/client/actions/index.tsindex ec9bda79e1..ef2b435b02 100644--- a/packages/loot-core/src/client/actions/index.ts+++ b/packages/loot-core/src/client/actions/index.ts@@ -1,5 +1,4 @@export * from './queries';-export * from './account';export * from './modals';export * from './notifications';export * from './prefs';diff --git a/packages/loot-core/src/client/actions/queries.ts b/packages/loot-core/src/client/actions/queries.tsindex caa316b824..3d972584c5 100644--- a/packages/loot-core/src/client/actions/queries.ts+++ b/packages/loot-core/src/client/actions/queries.ts@@ -5,6 +5,11 @@ import throttle from 'throttleit';import { send } from '../../platform/client/fetch';import { type AccountEntity } from '../../types/models';import * as constants from '../constants';+import {+ type MarkAccountReadAction,+ type SetLastTransactionAction,+ type UpdateNewTransactionsAction,+} from '../state-types/queries';import { type AppDispatch, type GetRootState } from '../store';import { pushModal } from './modals';@@ -368,6 +373,101 @@ export function forceCloseAccount(accountId) {return closeAccount(accountId, null, null, true);}+// Remember the last transaction manually added to the system+export function setLastTransaction(+ transaction: SetLastTransactionAction['transaction'],+): SetLastTransactionAction {+ return {+ type: constants.SET_LAST_TRANSACTION,+ transaction,+ };+}++export function parseTransactions(filepath, options) {+ return async () => {+ return await send('transactions-parse-file', {+ filepath,+ options,+ });+ };+}++export function importPreviewTransactions(id: string, transactions) {+ return async (dispatch: AppDispatch): Promise<boolean> => {+ const { errors = [], updatedPreview } = await send('transactions-import', {+ accountId: id,+ transactions,+ isPreview: true,+ });++ errors.forEach(error => {+ dispatch(+ addNotification({+ type: 'error',+ message: error.message,+ }),+ );+ });++ return updatedPreview;+ };+}++export function importTransactions(id: string, transactions, reconcile = true) {+ return async (dispatch: AppDispatch): Promise<boolean> => {+ if (!reconcile) {+ await send('api/transactions-add', {+ accountId: id,+ transactions,+ });++ return true;+ }++ const {+ errors = [],+ added,+ updated,+ } = await send('transactions-import', {+ accountId: id,+ transactions,+ isPreview: false,+ });++ errors.forEach(error => {+ dispatch(+ addNotification({+ type: 'error',+ message: error.message,+ }),+ );+ });++ dispatch({+ type: constants.SET_NEW_TRANSACTIONS,+ newTransactions: added,+ matchedTransactions: updated,+ updatedAccounts: added.length > 0 ? [id] : [],+ });++ return added.length > 0 || updated.length > 0;+ };+}++export function updateNewTransactions(changedId): UpdateNewTransactionsAction {+ return {+ type: constants.UPDATE_NEW_TRANSACTIONS,+ changedId,+ };+}++export function markAccountRead(accountId): MarkAccountReadAction {+ return {+ type: constants.MARK_ACCOUNT_READ,+ accountId,+ };+}+const _undo = throttle(() => send('undo'), 100);const _redo = throttle(() => send('redo'), 100);diff --git a/packages/loot-core/src/client/actions/sync.ts b/packages/loot-core/src/client/actions/sync.tsindex ca7c341aeb..f421b98575 100644--- a/packages/loot-core/src/client/actions/sync.ts+++ b/packages/loot-core/src/client/actions/sync.ts@@ -1,8 +1,8 @@import { send } from '../../platform/client/fetch';import { getUploadError } from '../../shared/errors';+import { syncAccounts } from '../accounts/accountsSlice';import { type AppDispatch, type GetRootState } from '../store';-import { syncAccounts } from './account';import { pushModal } from './modals';import { loadPrefs } from './prefs';@@ -64,7 +64,7 @@ export function syncAndDownload(accountId?: string) {return { error: syncState.error };}- const hasDownloaded = await dispatch(syncAccounts(accountId));+ const hasDownloaded = await dispatch(syncAccounts({ id: accountId }));if (hasDownloaded) {// Sync again afterwards if new transactions were createddiff --git a/packages/loot-core/src/client/reducers/account.ts b/packages/loot-core/src/client/reducers/account.tsdeleted file mode 100644index ef9e74121c..0000000000--- a/packages/loot-core/src/client/reducers/account.ts+++ /dev/null@@ -1,33 +0,0 @@-import * as constants from '../constants';-import type { Action } from '../state-types';-import type { AccountState } from '../state-types/account';--export const initialState: AccountState = {- failedAccounts: {},- accountsSyncing: [],-};--export function update(state = initialState, action: Action): AccountState {- switch (action.type) {- case constants.SET_ACCOUNTS_SYNCING:- return {- ...state,- accountsSyncing: action.ids,- };- case constants.ACCOUNT_SYNC_STATUS: {- const failedAccounts = { ...state.failedAccounts };- if (action.failed) {- failedAccounts[action.id] = {- type: action.errorType,- code: action.errorCode,- };- } else {- delete failedAccounts[action.id];- }-- return { ...state, failedAccounts };- }- default:- }- return state;-}diff --git a/packages/loot-core/src/client/reducers/index.ts b/packages/loot-core/src/client/reducers/index.tsindex 98f44d189d..1622ff4645 100644--- a/packages/loot-core/src/client/reducers/index.ts+++ b/packages/loot-core/src/client/reducers/index.ts@@ -1,4 +1,3 @@-import { update as account } from './account';import { update as app } from './app';import { update as budgets } from './budgets';import { update as modals } from './modals';@@ -10,7 +9,6 @@ import { update as user } from './user';export const reducers = {app,queries,- account,prefs,modals,notifications,diff --git a/packages/loot-core/src/client/redux/index.ts b/packages/loot-core/src/client/redux/index.tsnew file mode 100644index 0000000000..53941584c1--- /dev/null+++ b/packages/loot-core/src/client/redux/index.ts@@ -0,0 +1,8 @@+import { createAsyncThunk } from '@reduxjs/toolkit';++import { type AppDispatch, type RootState } from '../store';++export const createAppAsyncThunk = createAsyncThunk.withTypes<{+ state: RootState;+ dispatch: AppDispatch;+}>();diff --git a/packages/loot-core/src/client/shared-listeners.ts b/packages/loot-core/src/client/shared-listeners.tsindex 1311cf5c87..043754c024 100644--- a/packages/loot-core/src/client/shared-listeners.ts+++ b/packages/loot-core/src/client/shared-listeners.ts@@ -3,9 +3,23 @@ import { t } from 'i18next';import { listen, send } from '../platform/client/fetch';+import {+ addNotification,+ closeAndDownloadBudget,+ getAccounts,+ getCategories,+ getPayees,+ loadPrefs,+ pushModal,+ resetSync,+ signOut,+ sync,+ uploadBudget,+} from './actions';import type { Notification } from './state-types/notifications';+import { type AppStore } from './store';-export function listenForSyncEvent(actions, store) {+export function listenForSyncEvent(store: AppStore) {let attemptedSyncRepair = false;listen('sync-event', event => {@@ -19,17 +33,19 @@ export function listenForSyncEvent(actions, store) {if (attemptedSyncRepair) {attemptedSyncRepair = false;- actions.addNotification({- title: t('Syncing has been fixed!'),- message: t('Happy budgeting!'),- type: 'message',- });+ store.dispatch(+ addNotification({+ title: t('Syncing has been fixed!'),+ message: t('Happy budgeting!'),+ type: 'message',+ }),+ );}const tables = event.tables;if (tables.includes('prefs')) {- actions.loadPrefs();+ store.dispatch(loadPrefs());}if (@@ -37,15 +53,15 @@ export function listenForSyncEvent(actions, store) {tables.includes('category_groups') ||tables.includes('category_mapping')) {- actions.getCategories();+ store.dispatch(getCategories());}if (tables.includes('payees') || tables.includes('payee_mapping')) {- actions.getPayees();+ store.dispatch(getPayees());}if (tables.includes('accounts')) {- actions.getAccounts();+ store.dispatch(getAccounts());}} else if (event.type === 'error') {let notif: Notification | null = null;@@ -68,7 +84,7 @@ export function listenForSyncEvent(actions, store) {id: 'reset-sync',button: {title: t('Reset sync'),- action: actions.resetSync,+ action: () => store.dispatch(resetSync()),},};} else {@@ -90,7 +106,7 @@ export function listenForSyncEvent(actions, store) {action: async () => {attemptedSyncRepair = true;await send('sync-repair');- actions.sync();+ store.dispatch(sync());},},};@@ -111,13 +127,13 @@ export function listenForSyncEvent(actions, store) {'Old encryption keys are not migrated. If using encryption, [reset encryption here](#makeKey).',),messageActions: {- makeKey: () => actions.pushModal('create-encryption-key'),+ makeKey: () => store.dispatch(pushModal('create-encryption-key')),},sticky: true,id: 'old-file',button: {title: t('Reset sync'),- action: actions.resetSync,+ action: () => store.dispatch(resetSync()),},};break;@@ -136,7 +152,9 @@ export function listenForSyncEvent(actions, store) {id: 'invalid-key-state',button: {title: t('Reset key'),- action: () => actions.pushModal('create-encryption-key'),+ action: () => {+ store.dispatch(pushModal('create-encryption-key'));+ },},};@@ -159,9 +177,9 @@ export function listenForSyncEvent(actions, store) {button: {title: t('Register'),action: async () => {- await actions.uploadBudget();- actions.sync();- actions.loadPrefs();+ await store.dispatch(uploadBudget());+ store.dispatch(sync());+ store.dispatch(loadPrefs());},},};@@ -181,7 +199,7 @@ export function listenForSyncEvent(actions, store) {id: 'upload-file',button: {title: t('Upload'),- action: actions.resetSync,+ action: () => store.dispatch(resetSync()),},};break;@@ -204,12 +222,12 @@ export function listenForSyncEvent(actions, store) {) +' ' +learnMore,- messageActions: { upload: actions.resetSync },+ messageActions: { upload: () => store.dispatch(resetSync()) },sticky: true,id: 'needs-revert',button: {title: t('Revert'),- action: () => actions.closeAndDownloadBudget(cloudFileId),+ action: () => store.dispatch(closeAndDownloadBudget(cloudFileId)),},};break;@@ -226,10 +244,13 @@ export function listenForSyncEvent(actions, store) {id: 'encrypt-failure-missing',button: {title: t('Create key'),- action: () =>- actions.pushModal('fix-encryption-key', {- onSuccess: () => actions.sync(),- }),+ action: () => {+ store.dispatch(+ pushModal('fix-encryption-key', {+ onSuccess: () => store.dispatch(sync()),+ }),+ );+ },},};} else {@@ -243,10 +264,9 @@ export function listenForSyncEvent(actions, store) {id: 'encrypt-failure',button: {title: t('Reset key'),- action: () =>- actions.pushModal('create-encryption-key', {- onSuccess: () => actions.sync(),- }),+ action: () => {+ store.dispatch(pushModal('create-encryption-key'));+ },},};}@@ -282,7 +302,7 @@ export function listenForSyncEvent(actions, store) {id: 'login-expired',button: {title: 'Go to login',- action: () => actions.signOut(),+ action: () => store.dispatch(signOut()),},};break;@@ -297,7 +317,7 @@ export function listenForSyncEvent(actions, store) {}if (notif) {- actions.addNotification({ type: 'error', ...notif });+ store.dispatch(addNotification({ type: 'error', ...notif }));}}});diff --git a/packages/loot-core/src/client/state-types/account.d.ts b/packages/loot-core/src/client/state-types/account.d.tsdeleted file mode 100644index 87b16a8698..0000000000--- a/packages/loot-core/src/client/state-types/account.d.ts+++ /dev/null@@ -1,27 +0,0 @@-import type * as constants from '../constants';--export type AccountState = {- failedAccounts: { [key: string]: { type: string; code: string } };- accountsSyncing: string[];-};--export type SetAccountsSyncingAction = {- type: typeof constants.SET_ACCOUNTS_SYNCING;- ids: string[];-};--export type AccountSyncStatusAction = {- type: typeof constants.ACCOUNT_SYNC_STATUS;- id: string;-} & (- | {- failed: false;- }- | {- failed: true;- errorType: string;- errorCode: string;- }-);--export type AccountActions = SetAccountsSyncingAction | AccountSyncStatusAction;diff --git a/packages/loot-core/src/client/state-types/index.d.ts b/packages/loot-core/src/client/state-types/index.d.tsindex ffc435f33a..5e14bdbb58 100644--- a/packages/loot-core/src/client/state-types/index.d.ts+++ b/packages/loot-core/src/client/state-types/index.d.ts@@ -1,6 +1,5 @@import type * as constants from '../constants';-import type { AccountActions, AccountState } from './account';import type { AppActions, AppState } from './app';import type { BudgetsActions, BudgetsState } from './budgets';import type { ModalsActions, ModalsState } from './modals';@@ -14,7 +13,6 @@ export type CloseBudgetAction = {};export type Action =- | AccountActions| AppActions| BudgetsActions| ModalsActions@@ -25,7 +23,6 @@ export type Action =| CloseBudgetAction;export type State = {- account: AccountState;app: AppState;budgets: BudgetsState;modals: ModalsState;diff --git a/packages/loot-core/src/client/store/index.ts b/packages/loot-core/src/client/store/index.tsindex 12f1f2e4d3..807ac7853c 100644--- a/packages/loot-core/src/client/store/index.ts+++ b/packages/loot-core/src/client/store/index.ts@@ -1,8 +1,12 @@import { combineReducers, configureStore } from '@reduxjs/toolkit';+import {+ name as accountsSliceName,+ reducer as accountsSliceReducer,+ getInitialState as getInitialAccountsState,+} from '../accounts/accountsSlice';import * as constants from '../constants';import { reducers } from '../reducers';-import { initialState as initialAccountState } from '../reducers/account';import { initialState as initialAppState } from '../reducers/app';import { initialState as initialBudgetsState } from '../reducers/budgets';import { initialState as initialModalsState } from '../reducers/modals';@@ -11,13 +15,16 @@ import { initialState as initialPrefsState } from '../reducers/prefs';import { initialState as initialQueriesState } from '../reducers/queries';import { initialState as initialUserState } from '../reducers/user';-const appReducer = combineReducers(reducers);+const appReducer = combineReducers({+ ...reducers,+ [accountsSliceName]: accountsSliceReducer,+});const rootReducer: typeof appReducer = (state, action) => {if (action.type === constants.CLOSE_BUDGET) {// Reset the state and only keep around things intentionally. This// blows away everything elsestate = {- account: initialAccountState,+ account: getInitialAccountsState(),modals: initialModalsState,notifications: initialNotificationsState,queries: initialQueriesState,@@ -48,6 +55,7 @@ export const store = configureStore({}),});+export type AppStore = typeof store;export type RootState = ReturnType<typeof store.getState>;export type AppDispatch = typeof store.dispatch;export type GetRootState = typeof store.getState;diff --git a/packages/loot-core/src/client/store/mock.ts b/packages/loot-core/src/client/store/mock.tsindex a232a9c566..2101cfda24 100644--- a/packages/loot-core/src/client/store/mock.ts+++ b/packages/loot-core/src/client/store/mock.ts@@ -1,10 +1,17 @@import { configureStore, combineReducers } from '@reduxjs/toolkit';+import {+ name as accountsSliceName,+ reducer as accountsSliceReducer,+} from '../accounts/accountsSlice';import { reducers } from '../reducers';import { type store as realStore } from './index';-const appReducer = combineReducers(reducers);+const appReducer = combineReducers({+ ...reducers,+ [accountsSliceName]: accountsSliceReducer,+});export let mockStore: typeof realStore = configureStore({reducer: appReducer,diff --git a/upcoming-release-notes/4012.md b/upcoming-release-notes/4012.mdnew file mode 100644index 0000000000..8f7431e335--- /dev/null+++ b/upcoming-release-notes/4012.md@@ -0,0 +1,6 @@+---+category: Maintenance+authors: [joel-jeremy]+---++Phase 2 - Redux Toolkit Migration - accounts slice