Skip to content

A local-first personal finance app

[Redux Toolkit Migration] budgetsSlice (#4114)

Joel Jeremy Marquezfcf110749d93
diff --git a/packages/desktop-client/src/components/App.tsx b/packages/desktop-client/src/components/App.tsx
index 98a0426d98..b40d362505 100644
--- a/packages/desktop-client/src/components/App.tsx
+++ b/packages/desktop-client/src/components/App.tsx
@@ -16,12 +16,11 @@ import { View } from '@actual-app/components/view';
import {
addNotification,
- closeBudget,
- loadBudget,
loadGlobalPrefs,
signOut,
} from 'loot-core/client/actions';
import { setAppState, sync } from 'loot-core/client/app/appSlice';
+import { closeBudget, loadBudget } from 'loot-core/client/budgets/budgetsSlice';
import * as Platform from 'loot-core/client/platform';
import { SpreadsheetProvider } from 'loot-core/client/SpreadsheetProvider';
import { init as initConnection, send } from 'loot-core/platform/client/fetch';
@@ -100,7 +99,7 @@ function AppInner() {
);
const budgetId = await send('get-last-opened-backup');
if (budgetId) {
- await dispatch(loadBudget(budgetId));
+ await dispatch(loadBudget({ id: budgetId }));
// Check to see if this file has been remotely deleted (but
// don't block on this in case they are offline or something)
diff --git a/packages/desktop-client/src/components/LoggedInUser.tsx b/packages/desktop-client/src/components/LoggedInUser.tsx
index b8b849ab61..77ec9442b2 100644
--- a/packages/desktop-client/src/components/LoggedInUser.tsx
+++ b/packages/desktop-client/src/components/LoggedInUser.tsx
@@ -9,7 +9,8 @@ import { styles } from '@actual-app/components/styles';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import { closeBudget, getUserData, signOut } from 'loot-core/client/actions';
+import { getUserData, signOut } from 'loot-core/client/actions';
+import { closeBudget } from 'loot-core/client/budgets/budgetsSlice';
import { listen } from 'loot-core/platform/client/fetch';
import { type RemoteFile, type SyncedLocalFile } from 'loot-core/types/file';
import { type TransObjectLiteral } from 'loot-core/types/util';
diff --git a/packages/desktop-client/src/components/manager/BudgetList.tsx b/packages/desktop-client/src/components/manager/BudgetList.tsx
index 0925434582..754658fc85 100644
--- a/packages/desktop-client/src/components/manager/BudgetList.tsx
+++ b/packages/desktop-client/src/components/manager/BudgetList.tsx
@@ -15,16 +15,15 @@ import { Text } from '@actual-app/components/text';
import { Tooltip } from '@actual-app/components/tooltip';
import { View } from '@actual-app/components/view';
+import { getUserData, pushModal } from 'loot-core/client/actions';
import {
closeAndDownloadBudget,
closeAndLoadBudget,
createBudget,
downloadBudget,
- getUserData,
loadAllFiles,
loadBudget,
- pushModal,
-} from 'loot-core/client/actions';
+} from 'loot-core/client/budgets/budgetsSlice';
import {
isElectron,
isNonProductionEnvironment,
@@ -561,14 +560,14 @@ export function BudgetList({ showHeader = true, quickSwitchMode = false }) {
if (!id) {
if (isRemoteFile) {
- await dispatch(downloadBudget(file.cloudFileId));
+ await dispatch(downloadBudget({ cloudFileId: file.cloudFileId }));
} else {
- await dispatch(loadBudget(file.id));
+ await dispatch(loadBudget({ id: file.id }));
}
} else if (!isRemoteFile && file.id !== id) {
- await dispatch(closeAndLoadBudget(file.id));
+ await dispatch(closeAndLoadBudget({ fileId: file.id }));
} else if (isRemoteFile) {
- await dispatch(closeAndDownloadBudget(file.cloudFileId));
+ await dispatch(closeAndDownloadBudget({ cloudFileId: file.cloudFileId }));
}
};
diff --git a/packages/desktop-client/src/components/manager/ConfigServer.tsx b/packages/desktop-client/src/components/manager/ConfigServer.tsx
index 3508aa10d4..b7a7045cb5 100644
--- a/packages/desktop-client/src/components/manager/ConfigServer.tsx
+++ b/packages/desktop-client/src/components/manager/ConfigServer.tsx
@@ -6,7 +6,8 @@ import { Button, ButtonWithLoading } from '@actual-app/components/button';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import { createBudget, loggedIn, signOut } from 'loot-core/client/actions';
+import { loggedIn, signOut } from 'loot-core/client/actions';
+import { createBudget } from 'loot-core/client/budgets/budgetsSlice';
import {
isNonProductionEnvironment,
isElectron,
diff --git a/packages/desktop-client/src/components/manager/WelcomeScreen.tsx b/packages/desktop-client/src/components/manager/WelcomeScreen.tsx
index a8ff0fb698..a493e6cbda 100644
--- a/packages/desktop-client/src/components/manager/WelcomeScreen.tsx
+++ b/packages/desktop-client/src/components/manager/WelcomeScreen.tsx
@@ -7,7 +7,8 @@ import { styles } from '@actual-app/components/styles';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import { createBudget, pushModal } from 'loot-core/client/actions';
+import { pushModal } from 'loot-core/client/actions';
+import { createBudget } from 'loot-core/client/budgets/budgetsSlice';
import { useDispatch } from '../../redux';
import { theme } from '../../style';
@@ -97,7 +98,7 @@ export function WelcomeScreen() {
<Button
variant="primary"
autoFocus
- onPress={() => dispatch(createBudget())}
+ onPress={() => dispatch(createBudget({}))}
>
{t('Start fresh')}
</Button>
diff --git a/packages/desktop-client/src/components/manager/subscribe/Bootstrap.tsx b/packages/desktop-client/src/components/manager/subscribe/Bootstrap.tsx
index 6687977c1c..52844cc62d 100644
--- a/packages/desktop-client/src/components/manager/subscribe/Bootstrap.tsx
+++ b/packages/desktop-client/src/components/manager/subscribe/Bootstrap.tsx
@@ -7,7 +7,7 @@ import { Paragraph } from '@actual-app/components/paragraph';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import { createBudget } from 'loot-core/client/actions/budgets';
+import { createBudget } from 'loot-core/client/budgets/budgetsSlice';
import { send } from 'loot-core/platform/client/fetch';
import { useNavigate } from '../../../hooks/useNavigate';
diff --git a/packages/desktop-client/src/components/modals/CreateEncryptionKeyModal.tsx b/packages/desktop-client/src/components/modals/CreateEncryptionKeyModal.tsx
index a2733b37a6..8f58ba70a0 100644
--- a/packages/desktop-client/src/components/modals/CreateEncryptionKeyModal.tsx
+++ b/packages/desktop-client/src/components/modals/CreateEncryptionKeyModal.tsx
@@ -11,8 +11,9 @@ import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
-import { loadAllFiles, loadGlobalPrefs } from 'loot-core/client/actions';
+import { loadGlobalPrefs } from 'loot-core/client/actions';
import { sync } from 'loot-core/client/app/appSlice';
+import { loadAllFiles } from 'loot-core/client/budgets/budgetsSlice';
import { send } from 'loot-core/platform/client/fetch';
import { getCreateKeyError } from 'loot-core/shared/errors';
diff --git a/packages/desktop-client/src/components/modals/LoadBackupModal.tsx b/packages/desktop-client/src/components/modals/LoadBackupModal.tsx
index 8df643e4e9..0d2af13245 100644
--- a/packages/desktop-client/src/components/modals/LoadBackupModal.tsx
+++ b/packages/desktop-client/src/components/modals/LoadBackupModal.tsx
@@ -7,7 +7,7 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { loadBackup, makeBackup } from 'loot-core/client/actions';
+import { loadBackup, makeBackup } from 'loot-core/client/budgets/budgetsSlice';
import { send, listen, unlisten } from 'loot-core/platform/client/fetch';
import { type Backup } from 'loot-core/server/backups';
@@ -107,7 +107,12 @@ export function LoadBackupModal({
<Button
variant="primary"
onPress={() =>
- dispatch(loadBackup(budgetIdToLoad, latestBackup.id))
+ dispatch(
+ loadBackup({
+ budgetId: budgetIdToLoad,
+ backupId: latestBackup.id,
+ }),
+ )
}
>
{t('Revert to original version')}
@@ -142,7 +147,11 @@ export function LoadBackupModal({
) : (
<BackupTable
backups={previousBackups}
- onSelect={id => dispatch(loadBackup(budgetIdToLoad, id))}
+ onSelect={id =>
+ dispatch(
+ loadBackup({ budgetId: budgetIdToLoad, backupId: id }),
+ )
+ }
/>
)}
</View>
diff --git a/packages/desktop-client/src/components/modals/OpenIDEnableModal.tsx b/packages/desktop-client/src/components/modals/OpenIDEnableModal.tsx
index de4729edd9..77b6edd266 100644
--- a/packages/desktop-client/src/components/modals/OpenIDEnableModal.tsx
+++ b/packages/desktop-client/src/components/modals/OpenIDEnableModal.tsx
@@ -6,7 +6,8 @@ import { Label } from '@actual-app/components/label';
import { styles } from '@actual-app/components/styles';
import { View } from '@actual-app/components/view';
-import { closeBudget, popModal } from 'loot-core/client/actions';
+import { popModal } from 'loot-core/client/actions';
+import { closeBudget } from 'loot-core/client/budgets/budgetsSlice';
import { send } from 'loot-core/platform/client/fetch';
import * as asyncStorage from 'loot-core/platform/server/asyncStorage';
import { getOpenIdErrors } from 'loot-core/shared/errors';
diff --git a/packages/desktop-client/src/components/modals/OutOfSyncMigrationsModal.tsx b/packages/desktop-client/src/components/modals/OutOfSyncMigrationsModal.tsx
index a8aa2c0989..6af8c2042b 100644
--- a/packages/desktop-client/src/components/modals/OutOfSyncMigrationsModal.tsx
+++ b/packages/desktop-client/src/components/modals/OutOfSyncMigrationsModal.tsx
@@ -6,7 +6,7 @@ import { Paragraph } from '@actual-app/components/paragraph';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import { closeBudget } from 'loot-core/client/actions';
+import { closeBudget } from 'loot-core/client/budgets/budgetsSlice';
import { useDispatch } from '../../redux';
import { Link } from '../common/Link';
diff --git a/packages/desktop-client/src/components/modals/PasswordEnableModal.tsx b/packages/desktop-client/src/components/modals/PasswordEnableModal.tsx
index 1567a775fa..959bf22c52 100644
--- a/packages/desktop-client/src/components/modals/PasswordEnableModal.tsx
+++ b/packages/desktop-client/src/components/modals/PasswordEnableModal.tsx
@@ -6,7 +6,8 @@ import { Label } from '@actual-app/components/label';
import { styles } from '@actual-app/components/styles';
import { View } from '@actual-app/components/view';
-import { closeBudget, popModal } from 'loot-core/client/actions';
+import { popModal } from 'loot-core/client/actions';
+import { closeBudget } from 'loot-core/client/budgets/budgetsSlice';
import { send } from 'loot-core/platform/client/fetch';
import * as asyncStorage from 'loot-core/platform/server/asyncStorage';
diff --git a/packages/desktop-client/src/components/modals/TransferOwnership.tsx b/packages/desktop-client/src/components/modals/TransferOwnership.tsx
index b03f87c13b..dc7ed9ea36 100644
--- a/packages/desktop-client/src/components/modals/TransferOwnership.tsx
+++ b/packages/desktop-client/src/components/modals/TransferOwnership.tsx
@@ -7,11 +7,8 @@ import { styles } from '@actual-app/components/styles';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import {
- addNotification,
- closeAndLoadBudget,
- popModal,
-} from 'loot-core/client/actions';
+import { addNotification, popModal } from 'loot-core/client/actions';
+import { closeAndLoadBudget } from 'loot-core/client/budgets/budgetsSlice';
import { send } from 'loot-core/platform/client/fetch';
import { getUserAccessErrors } from 'loot-core/shared/errors';
import { type Budget } from 'loot-core/types/budget';
@@ -188,7 +185,7 @@ export function TransferOwnership({
try {
await onSave();
await dispatch(
- closeAndLoadBudget((currentFile as Budget).id),
+ closeAndLoadBudget({ fileId: (currentFile as Budget).id }),
);
close();
} catch (error) {
diff --git a/packages/desktop-client/src/components/modals/manager/DeleteFileModal.tsx b/packages/desktop-client/src/components/modals/manager/DeleteFileModal.tsx
index 2f927f7b2a..5390bf5b6f 100644
--- a/packages/desktop-client/src/components/modals/manager/DeleteFileModal.tsx
+++ b/packages/desktop-client/src/components/modals/manager/DeleteFileModal.tsx
@@ -5,7 +5,7 @@ import { ButtonWithLoading } from '@actual-app/components/button';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import { deleteBudget } from 'loot-core/client/actions';
+import { deleteBudget } from 'loot-core/client/budgets/budgetsSlice';
import { type File } from 'loot-core/types/file';
import { useDispatch } from '../../../redux';
@@ -71,10 +71,10 @@ export function DeleteFileModal({ file }: DeleteFileProps) {
onPress={async () => {
setLoadingState('cloud');
await dispatch(
- deleteBudget(
- 'id' in file ? file.id : undefined,
- file.cloudFileId,
- ),
+ deleteBudget({
+ id: 'id' in file ? file.id : undefined,
+ cloudFileId: file.cloudFileId,
+ }),
);
setLoadingState(null);
@@ -137,7 +137,7 @@ export function DeleteFileModal({ file }: DeleteFileProps) {
}}
onPress={async () => {
setLoadingState('local');
- await dispatch(deleteBudget(file.id));
+ await dispatch(deleteBudget({ id: file.id }));
setLoadingState(null);
close();
diff --git a/packages/desktop-client/src/components/modals/manager/DuplicateFileModal.tsx b/packages/desktop-client/src/components/modals/manager/DuplicateFileModal.tsx
index 4e03016323..f1d1644e5a 100644
--- a/packages/desktop-client/src/components/modals/manager/DuplicateFileModal.tsx
+++ b/packages/desktop-client/src/components/modals/manager/DuplicateFileModal.tsx
@@ -8,12 +8,9 @@ import { InlineField } from '@actual-app/components/inline-field';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import {
- addNotification,
- duplicateBudget,
- uniqueBudgetName,
- validateBudgetName,
-} from 'loot-core/client/actions';
+import { addNotification } from 'loot-core/client/actions';
+import { duplicateBudget } from 'loot-core/client/budgets/budgetsSlice';
+import { send } from 'loot-core/platform/client/fetch';
import { type File } from 'loot-core/types/file';
import { useDispatch } from '../../../redux';
@@ -242,3 +239,14 @@ export function DuplicateFileModal({
</Modal>
);
}
+
+async function validateBudgetName(name: string): Promise<{
+ valid: boolean;
+ message?: string;
+}> {
+ return send('validate-budget-name', { name });
+}
+
+async function uniqueBudgetName(name: string): Promise<string> {
+ return send('unique-budget-name', { name });
+}
diff --git a/packages/desktop-client/src/components/modals/manager/FilesSettingsModal.tsx b/packages/desktop-client/src/components/modals/manager/FilesSettingsModal.tsx
index 10cd1e939a..24f27121e3 100644
--- a/packages/desktop-client/src/components/modals/manager/FilesSettingsModal.tsx
+++ b/packages/desktop-client/src/components/modals/manager/FilesSettingsModal.tsx
@@ -6,7 +6,8 @@ import { styles } from '@actual-app/components/styles';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import { loadAllFiles, pushModal } from 'loot-core/client/actions';
+import { pushModal } from 'loot-core/client/actions';
+import { loadAllFiles } from 'loot-core/client/budgets/budgetsSlice';
import { useGlobalPref } from '../../../hooks/useGlobalPref';
import { SvgPencil1 } from '../../../icons/v2';
diff --git a/packages/desktop-client/src/components/modals/manager/ImportActualModal.tsx b/packages/desktop-client/src/components/modals/manager/ImportActualModal.tsx
index 83469d57a7..7488a99c09 100644
--- a/packages/desktop-client/src/components/modals/manager/ImportActualModal.tsx
+++ b/packages/desktop-client/src/components/modals/manager/ImportActualModal.tsx
@@ -9,7 +9,7 @@ import { styles } from '@actual-app/components/styles';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { importBudget } from 'loot-core/client/actions/budgets';
+import { importBudget } from 'loot-core/client/budgets/budgetsSlice';
import { useNavigate } from '../../../hooks/useNavigate';
import { useDispatch } from '../../../redux';
@@ -48,7 +48,7 @@ export function ImportActualModal() {
setImporting(true);
setError(null);
try {
- await dispatch(importBudget(res[0], 'actual'));
+ await dispatch(importBudget({ filepath: res[0], type: 'actual' }));
navigate('/budget');
} catch (err) {
setError(err.message);
diff --git a/packages/desktop-client/src/components/modals/manager/ImportYNAB4Modal.tsx b/packages/desktop-client/src/components/modals/manager/ImportYNAB4Modal.tsx
index 8e0a76db5e..15c4e33f39 100644
--- a/packages/desktop-client/src/components/modals/manager/ImportYNAB4Modal.tsx
+++ b/packages/desktop-client/src/components/modals/manager/ImportYNAB4Modal.tsx
@@ -9,7 +9,7 @@ import { styles } from '@actual-app/components/styles';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { importBudget } from 'loot-core/client/actions/budgets';
+import { importBudget } from 'loot-core/client/budgets/budgetsSlice';
import { useNavigate } from '../../../hooks/useNavigate';
import { useDispatch } from '../../../redux';
@@ -40,7 +40,7 @@ export function ImportYNAB4Modal() {
setImporting(true);
setError(null);
try {
- await dispatch(importBudget(res[0], 'ynab4'));
+ await dispatch(importBudget({ filepath: res[0], type: 'ynab4' }));
navigate('/budget');
} catch (err) {
setError(err.message);
diff --git a/packages/desktop-client/src/components/modals/manager/ImportYNAB5Modal.tsx b/packages/desktop-client/src/components/modals/manager/ImportYNAB5Modal.tsx
index e55e072f87..4fe7a52d8c 100644
--- a/packages/desktop-client/src/components/modals/manager/ImportYNAB5Modal.tsx
+++ b/packages/desktop-client/src/components/modals/manager/ImportYNAB5Modal.tsx
@@ -9,7 +9,7 @@ import { styles } from '@actual-app/components/styles';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { importBudget } from 'loot-core/client/actions/budgets';
+import { importBudget } from 'loot-core/client/budgets/budgetsSlice';
import { useNavigate } from '../../../hooks/useNavigate';
import { useDispatch } from '../../../redux';
@@ -43,7 +43,7 @@ export function ImportYNAB5Modal() {
setImporting(true);
setError(null);
try {
- await dispatch(importBudget(res[0], 'ynab5'));
+ await dispatch(importBudget({ filepath: res[0], type: 'ynab5' }));
navigate('/budget');
} catch (err) {
setError(err.message);
diff --git a/packages/desktop-client/src/components/settings/index.tsx b/packages/desktop-client/src/components/settings/index.tsx
index aea6fac6c1..5163439078 100644
--- a/packages/desktop-client/src/components/settings/index.tsx
+++ b/packages/desktop-client/src/components/settings/index.tsx
@@ -6,7 +6,8 @@ import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
-import { closeBudget, loadPrefs } from 'loot-core/client/actions';
+import { loadPrefs } from 'loot-core/client/actions';
+import { closeBudget } from 'loot-core/client/budgets/budgetsSlice';
import { listen } from 'loot-core/platform/client/fetch';
import { isElectron } from 'loot-core/shared/environment';
diff --git a/packages/desktop-client/src/components/sidebar/BudgetName.tsx b/packages/desktop-client/src/components/sidebar/BudgetName.tsx
index 30db766eda..e8948278a2 100644
--- a/packages/desktop-client/src/components/sidebar/BudgetName.tsx
+++ b/packages/desktop-client/src/components/sidebar/BudgetName.tsx
@@ -8,7 +8,7 @@ import { Popover } from '@actual-app/components/popover';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import { closeBudget } from 'loot-core/client/actions';
+import { closeBudget } from 'loot-core/client/budgets/budgetsSlice';
import * as Platform from 'loot-core/client/platform';
import { useContextMenu } from '../../hooks/useContextMenu';
diff --git a/packages/desktop-client/src/global-events.ts b/packages/desktop-client/src/global-events.ts
index 814f2e12a9..63938eadcb 100644
--- a/packages/desktop-client/src/global-events.ts
+++ b/packages/desktop-client/src/global-events.ts
@@ -2,13 +2,13 @@
import {
addGenericErrorNotification,
addNotification,
- closeBudgetUI,
closeModal,
loadPrefs,
pushModal,
replaceModal,
} from 'loot-core/client/actions';
import { setAppState } from 'loot-core/client/app/appSlice';
+import { closeBudgetUI } from 'loot-core/client/budgets/budgetsSlice';
import {
getAccounts,
getCategories,
diff --git a/packages/desktop-client/src/index.tsx b/packages/desktop-client/src/index.tsx
index 903d6a74e3..a23d7fb1e3 100644
--- a/packages/desktop-client/src/index.tsx
+++ b/packages/desktop-client/src/index.tsx
@@ -16,6 +16,7 @@ import { createRoot } from 'react-dom/client';
import * as accountsSlice from 'loot-core/client/accounts/accountsSlice';
import * as actions from 'loot-core/client/actions';
import * as appSlice from 'loot-core/client/app/appSlice';
+import * as budgetsSlice from 'loot-core/client/budgets/budgetsSlice';
import * as queriesSlice from 'loot-core/client/queries/queriesSlice';
import { runQuery } from 'loot-core/client/query-helpers';
import { store } from 'loot-core/client/store';
@@ -36,6 +37,7 @@ const boundActions = bindActionCreators(
...actions,
...accountsSlice.actions,
...appSlice.actions,
+ ...budgetsSlice.actions,
...queriesSlice.actions,
},
store.dispatch,
diff --git a/packages/loot-core/src/client/actions/backups.ts b/packages/loot-core/src/client/actions/backups.ts
deleted file mode 100644
index 51e5100a7b..0000000000
--- a/packages/loot-core/src/client/actions/backups.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-// @ts-strict-ignore
-import { send } from '../../platform/client/fetch';
-import { type AppDispatch, type GetRootState } from '../store';
-
-import { closeBudget, loadBudget } from './budgets';
-
-// Take in the budget id so that backups can be loaded when a budget
-// isn't opened
-export function loadBackup(budgetId, backupId) {
- return async (dispatch: AppDispatch, getState: GetRootState) => {
- const prefs = getState().prefs.local;
- if (prefs && prefs.id) {
- await dispatch(closeBudget());
- }
-
- await send('backup-load', { id: budgetId, backupId });
- await dispatch(loadBudget(budgetId));
- };
-}
-
-export function makeBackup() {
- return async (dispatch: AppDispatch, getState: GetRootState) => {
- const prefs = getState().prefs.local;
- if (prefs && prefs.id) {
- await send('backup-make', { id: prefs.id });
- }
- };
-}
diff --git a/packages/loot-core/src/client/actions/budgets.ts b/packages/loot-core/src/client/actions/budgets.ts
deleted file mode 100644
index e07febef25..0000000000
--- a/packages/loot-core/src/client/actions/budgets.ts
+++ /dev/null
@@ -1,315 +0,0 @@
-// @ts-strict-ignore
-import { t } from 'i18next';
-
-import { send } from '../../platform/client/fetch';
-import { getDownloadError, getSyncError } from '../../shared/errors';
-import type { Handlers } from '../../types/handlers';
-import { setAppState } from '../app/appSlice';
-import * as constants from '../constants';
-import { type AppDispatch, type GetRootState } from '../store';
-
-import { closeModal, pushModal } from './modals';
-import { loadPrefs, loadGlobalPrefs } from './prefs';
-
-export function loadBudgets() {
- return async (dispatch: AppDispatch) => {
- const budgets = await send('get-budgets');
-
- dispatch({
- type: constants.SET_BUDGETS,
- budgets,
- });
- };
-}
-
-export function loadRemoteFiles() {
- return async (dispatch: AppDispatch) => {
- const files = await send('get-remote-files');
-
- dispatch({
- type: constants.SET_REMOTE_FILES,
- files,
- });
- };
-}
-
-export function loadAllFiles() {
- return async (dispatch: AppDispatch, getState: GetRootState) => {
- const budgets = await send('get-budgets');
- const files = await send('get-remote-files');
-
- dispatch({
- type: constants.SET_ALL_FILES,
- budgets,
- remoteFiles: files,
- });
-
- return getState().budgets.allFiles;
- };
-}
-
-export function loadBudget(id: string, options = {}) {
- return async (dispatch: AppDispatch) => {
- dispatch(setAppState({ loadingText: t('Loading...') }));
-
- // Loading a budget may fail
- const { error } = await send('load-budget', { id, ...options });
-
- if (error) {
- const message = getSyncError(error, id);
- if (error === 'out-of-sync-migrations') {
- dispatch(pushModal('out-of-sync-migrations'));
- } else if (error === 'out-of-sync-data') {
- // confirm is not available on iOS
- if (typeof window.confirm !== 'undefined') {
- const showBackups = window.confirm(
- message +
- ' ' +
- t(
- 'Make sure the app is up-to-date. Do you want to load a backup?',
- ),
- );
-
- if (showBackups) {
- dispatch(pushModal('load-backup', { budgetId: id }));
- }
- } else {
- alert(message + ' ' + t('Make sure the app is up-to-date.'));
- }
- } else {
- alert(message);
- }
- } else {
- dispatch(closeModal());
-
- await dispatch(loadPrefs());
- }
-
- dispatch(setAppState({ loadingText: null }));
- };
-}
-
-export function closeBudget() {
- return async (dispatch: AppDispatch, getState: GetRootState) => {
- const prefs = getState().prefs.local;
- if (prefs && prefs.id) {
- // This clears out all the app state so the user starts fresh
- dispatch({ type: constants.CLOSE_BUDGET });
-
- dispatch(setAppState({ loadingText: t('Closing...') }));
- await send('close-budget');
- dispatch(setAppState({ loadingText: null }));
- if (localStorage.getItem('SharedArrayBufferOverride')) {
- window.location.reload();
- }
- }
- };
-}
-
-export function closeBudgetUI() {
- return async (dispatch: AppDispatch, getState: GetRootState) => {
- const prefs = getState().prefs.local;
- if (prefs && prefs.id) {
- dispatch({ type: constants.CLOSE_BUDGET });
- }
- };
-}
-
-export function deleteBudget(id?: string, cloudFileId?: string) {
- return async (dispatch: AppDispatch) => {
- await send('delete-budget', { id, cloudFileId });
- await dispatch(loadAllFiles());
- };
-}
-
-export function createBudget({ testMode = false, demoMode = false } = {}) {
- return async (dispatch: AppDispatch) => {
- dispatch(
- setAppState({
- loadingText:
- testMode || demoMode ? t('Making demo...') : t('Creating budget...'),
- }),
- );
-
- if (demoMode) {
- await send('create-demo-budget');
- } else {
- await send('create-budget', { testMode });
- }
-
- dispatch(closeModal());
-
- await dispatch(loadAllFiles());
- await dispatch(loadPrefs());
-
- // Set the loadingText to null after we've loaded the budget prefs
- // so that the existing manager page doesn't flash
- dispatch(setAppState({ loadingText: null }));
- };
-}
-
-export async function validateBudgetName(name: string): Promise<{
- valid: boolean;
- message?: string;
-}> {
- return send('validate-budget-name', { name });
-}
-
-export async function uniqueBudgetName(name: string): Promise<string> {
- return send('unique-budget-name', { name });
-}
-
-export function duplicateBudget({
- id,
- cloudId,
- oldName,
- newName,
- managePage,
- loadBudget = 'none',
- cloudSync,
-}: {
- id?: string | undefined;
- cloudId?: string | undefined;
- oldName: string;
- newName: string;
- managePage?: boolean;
- loadBudget: 'none' | 'original' | 'copy';
- /**
- * cloudSync is used to determine if the duplicate budget
- * should be synced to the server
- */
- cloudSync: boolean;
-}) {
- return async (dispatch: AppDispatch) => {
- try {
- dispatch(
- setAppState({
- loadingText: t('Duplicating: {{oldName}} to: {{newName}}', {
- oldName,
- newName,
- }),
- }),
- );
-
- await send('duplicate-budget', {
- id,
- cloudId,
- newName,
- cloudSync,
- open: loadBudget,
- });
-
- dispatch(closeModal());
-
- if (managePage) {
- await dispatch(loadAllFiles());
- }
- } catch (error) {
- console.error('Error duplicating budget:', error);
- throw error instanceof Error
- ? error
- : new Error('Error duplicating budget: ' + String(error));
- } finally {
- dispatch(setAppState({ loadingText: null }));
- }
- };
-}
-
-export function importBudget(
- filepath: string,
- type: Parameters<Handlers['import-budget']>[0]['type'],
-) {
- return async (dispatch: AppDispatch) => {
- const { error } = await send('import-budget', { filepath, type });
- if (error) {
- throw new Error(error);
- }
-
- dispatch(closeModal());
-
- await dispatch(loadPrefs());
- };
-}
-
-export function uploadBudget(id?: string) {
- return async (dispatch: AppDispatch) => {
- const { error } = await send('upload-budget', { id });
- if (error) {
- return { error };
- }
-
- await dispatch(loadAllFiles());
- return {};
- };
-}
-
-export function closeAndLoadBudget(fileId: string) {
- return async (dispatch: AppDispatch) => {
- await dispatch(closeBudget());
- await dispatch(loadBudget(fileId));
- };
-}
-
-export function closeAndDownloadBudget(cloudFileId: string) {
- return async (dispatch: AppDispatch) => {
- await dispatch(closeBudget());
- dispatch(downloadBudget(cloudFileId, { replace: true }));
- };
-}
-
-export function downloadBudget(cloudFileId: string, { replace = false } = {}) {
- return async (dispatch: AppDispatch) => {
- dispatch(
- setAppState({
- loadingText: t('Downloading...'),
- }),
- );
-
- const { id, error } = await send('download-budget', {
- fileId: cloudFileId,
- replace,
- });
-
- if (error) {
- if (error.reason === 'decrypt-failure') {
- const opts = {
- hasExistingKey: error.meta && error.meta.isMissingKey,
- cloudFileId,
- onSuccess: () => {
- dispatch(downloadBudget(cloudFileId, { replace }));
- },
- };
-
- dispatch(pushModal('fix-encryption-key', opts));
- dispatch(setAppState({ loadingText: null }));
- } else if (error.reason === 'file-exists') {
- alert(
- t(
- 'A file with id “{{id}}” already exists with the name “{{name}}”. ' +
- 'This file will be replaced. This probably happened because files were manually ' +
- 'moved around outside of Actual.',
- {
- id: error.meta.id,
- name: error.meta.name,
- },
- ),
- );
-
- return dispatch(downloadBudget(cloudFileId, { replace: true }));
- } else {
- dispatch(setAppState({ loadingText: null }));
- alert(getDownloadError(error));
- }
- return null;
- } else {
- await Promise.all([
- dispatch(loadGlobalPrefs()),
- dispatch(loadAllFiles()),
- dispatch(loadBudget(id)),
- ]);
- dispatch(setAppState({ loadingText: null }));
- }
-
- return id;
- };
-}
diff --git a/packages/loot-core/src/client/actions/index.ts b/packages/loot-core/src/client/actions/index.ts
index 9d758dfb9d..1fbc47c94a 100644
--- a/packages/loot-core/src/client/actions/index.ts
+++ b/packages/loot-core/src/client/actions/index.ts
@@ -1,6 +1,4 @@
export * from './modals';
export * from './notifications';
export * from './prefs';
-export * from './budgets';
-export * from './backups';
export * from './user';
diff --git a/packages/loot-core/src/client/actions/user.ts b/packages/loot-core/src/client/actions/user.ts
index 5136f6cf6a..e368a145b5 100644
--- a/packages/loot-core/src/client/actions/user.ts
+++ b/packages/loot-core/src/client/actions/user.ts
@@ -1,8 +1,8 @@
import { send } from '../../platform/client/fetch';
+import { closeBudget, loadAllFiles } from '../budgets/budgetsSlice';
import * as constants from '../constants';
import { type AppDispatch } from '../store';
-import { loadAllFiles, closeBudget } from './budgets';
import { loadGlobalPrefs } from './prefs';
export function getUserData() {
diff --git a/packages/loot-core/src/client/budgets/budgetsSlice.ts b/packages/loot-core/src/client/budgets/budgetsSlice.ts
new file mode 100644
index 0000000000..2ab08a9b5e
--- /dev/null
+++ b/packages/loot-core/src/client/budgets/budgetsSlice.ts
@@ -0,0 +1,589 @@
+import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
+import { t } from 'i18next';
+
+import { send } from '../../platform/client/fetch';
+import { type RemoteFile } from '../../server/cloud-storage';
+import { getDownloadError, getSyncError } from '../../shared/errors';
+import { type Budget } from '../../types/budget';
+import { type File } from '../../types/file';
+import { type Handlers } from '../../types/handlers';
+import { closeModal, loadGlobalPrefs, loadPrefs, pushModal } from '../actions';
+import { setAppState } from '../app/appSlice';
+import * as constants from '../constants';
+import { createAppAsyncThunk } from '../redux';
+
+const sliceName = 'budgets';
+
+export const loadBudgets = createAppAsyncThunk(
+ `${sliceName}/loadBudgets`,
+ async (_, { dispatch }) => {
+ const budgets = await send('get-budgets');
+
+ await dispatch(setBudgets({ budgets }));
+ },
+);
+
+export const loadRemoteFiles = createAppAsyncThunk(
+ `${sliceName}/loadRemoteFiles`,
+ async (_, { dispatch }) => {
+ const files = await send('get-remote-files');
+
+ await dispatch(setRemoteFiles({ remoteFiles: files }));
+ },
+);
+
+export const loadAllFiles = createAppAsyncThunk(
+ `${sliceName}/loadAllFiles`,
+ async (_, { dispatch, getState }) => {
+ const budgets = await send('get-budgets');
+ const files = await send('get-remote-files');
+
+ await dispatch(setAllFiles({ budgets, remoteFiles: files }));
+
+ return getState().budgets.allFiles;
+ },
+);
+
+type LoadBudgetPayload = {
+ id: string;
+ // TODO: Is this still needed?
+ options?: Record<string, unknown>;
+};
+
+export const loadBudget = createAppAsyncThunk(
+ `${sliceName}/loadBudget`,
+ async ({ id, options = {} }: LoadBudgetPayload, { dispatch }) => {
+ await dispatch(setAppState({ loadingText: t('Loading...') }));
+
+ // Loading a budget may fail
+ const { error } = await send('load-budget', { id, ...options });
+
+ if (error) {
+ const message = getSyncError(error, id);
+ if (error === 'out-of-sync-migrations') {
+ await dispatch(pushModal('out-of-sync-migrations'));
+ } else if (error === 'out-of-sync-data') {
+ // confirm is not available on iOS
+ if (typeof window.confirm !== 'undefined') {
+ const showBackups = window.confirm(
+ message +
+ ' ' +
+ t(
+ 'Make sure the app is up-to-date. Do you want to load a backup?',
+ ),
+ );
+
+ if (showBackups) {
+ await dispatch(pushModal('load-backup', { budgetId: id }));
+ }
+ } else {
+ alert(message + ' ' + t('Make sure the app is up-to-date.'));
+ }
+ } else {
+ alert(message);
+ }
+ } else {
+ await dispatch(closeModal());
+ await dispatch(loadPrefs());
+ }
+
+ await dispatch(setAppState({ loadingText: null }));
+ },
+);
+
+export const closeBudget = createAppAsyncThunk(
+ `${sliceName}/closeBudget`,
+ async (_, { dispatch, getState }) => {
+ const prefs = getState().prefs.local;
+ if (prefs && prefs.id) {
+ // This clears out all the app state so the user starts fresh
+ // TODO: Change to use an action once CLOSE_BUDGET is migrated to redux toolkit.
+ await dispatch({ type: constants.CLOSE_BUDGET });
+
+ await dispatch(setAppState({ loadingText: t('Closing...') }));
+ await send('close-budget');
+ await dispatch(setAppState({ loadingText: null }));
+ if (localStorage.getItem('SharedArrayBufferOverride')) {
+ window.location.reload();
+ }
+ }
+ },
+);
+
+export const closeBudgetUI = createAppAsyncThunk(
+ `${sliceName}/closeBudgetUI`,
+ async (_, { dispatch, getState }) => {
+ const prefs = getState().prefs.local;
+ if (prefs && prefs.id) {
+ // TODO: Change to use an action once CLOSE_BUDGET is migrated to redux toolkit.
+ await dispatch({ type: constants.CLOSE_BUDGET });
+ }
+ },
+);
+
+type DeleteBudgetPayload = {
+ id?: string;
+ cloudFileId?: string;
+};
+
+export const deleteBudget = createAppAsyncThunk(
+ `${sliceName}/deleteBudget`,
+ async ({ id, cloudFileId }: DeleteBudgetPayload, { dispatch }) => {
+ await send('delete-budget', { id, cloudFileId });
+ await dispatch(loadAllFiles());
+ },
+);
+
+type CreateBudgetPayload = {
+ testMode?: boolean;
+ demoMode?: boolean;
+};
+
+export const createBudget = createAppAsyncThunk(
+ `${sliceName}/createBudget`,
+ async (
+ { testMode = false, demoMode = false }: CreateBudgetPayload,
+ { dispatch },
+ ) => {
+ await dispatch(
+ setAppState({
+ loadingText:
+ testMode || demoMode ? t('Making demo...') : t('Creating budget...'),
+ }),
+ );
+
+ if (demoMode) {
+ await send('create-demo-budget');
+ } else {
+ await send('create-budget', { testMode });
+ }
+
+ await dispatch(closeModal());
+
+ await dispatch(loadAllFiles());
+ await dispatch(loadPrefs());
+
+ // Set the loadingText to null after we've loaded the budget prefs
+ // so that the existing manager page doesn't flash
+ await dispatch(setAppState({ loadingText: null }));
+ },
+);
+
+type DuplicateBudgetPayload = {
+ id?: string | undefined;
+ cloudId?: string | undefined;
+ oldName: string;
+ newName: string;
+ managePage?: boolean;
+ loadBudget: 'none' | 'original' | 'copy';
+ /**
+ * cloudSync is used to determine if the duplicate budget
+ * should be synced to the server
+ */
+ cloudSync: boolean;
+};
+
+export const duplicateBudget = createAppAsyncThunk(
+ `${sliceName}/duplicateBudget`,
+ async (
+ {
+ id,
+ cloudId,
+ oldName,
+ newName,
+ managePage,
+ loadBudget = 'none',
+ cloudSync,
+ }: DuplicateBudgetPayload,
+ { dispatch },
+ ) => {
+ try {
+ await dispatch(
+ setAppState({
+ loadingText: t('Duplicating: {{oldName}} to: {{newName}}', {
+ oldName,
+ newName,
+ }),
+ }),
+ );
+
+ await send('duplicate-budget', {
+ id,
+ cloudId,
+ newName,
+ cloudSync,
+ open: loadBudget,
+ });
+
+ await dispatch(closeModal());
+
+ if (managePage) {
+ await dispatch(loadAllFiles());
+ }
+ } catch (error) {
+ console.error('Error duplicating budget:', error);
+ throw error instanceof Error
+ ? error
+ : new Error('Error duplicating budget: ' + String(error));
+ } finally {
+ await dispatch(setAppState({ loadingText: null }));
+ }
+ },
+);
+
+type ImportBudgetPayload = {
+ filepath: string;
+ type: Parameters<Handlers['import-budget']>[0]['type'];
+};
+
+export const importBudget = createAppAsyncThunk(
+ `${sliceName}/importBudget`,
+ async ({ filepath, type }: ImportBudgetPayload, { dispatch }) => {
+ const { error } = await send('import-budget', { filepath, type });
+ if (error) {
+ throw new Error(error);
+ }
+
+ await dispatch(closeModal());
+ await dispatch(loadPrefs());
+ },
+);
+
+type UploadBudgetPayload = {
+ id?: string;
+};
+
+export const uploadBudget = createAppAsyncThunk(
+ `${sliceName}/uploadBudget`,
+ async ({ id }: UploadBudgetPayload, { dispatch }) => {
+ const { error } = await send('upload-budget', { id });
+ if (error) {
+ return { error };
+ }
+
+ await dispatch(loadAllFiles());
+ return {};
+ },
+);
+
+export const closeAndLoadBudget = createAppAsyncThunk(
+ `${sliceName}/closeAndLoadBudget`,
+ async ({ fileId }: { fileId: string }, { dispatch }) => {
+ await dispatch(closeBudget());
+ await dispatch(loadBudget({ id: fileId }));
+ },
+);
+
+type CloseAndDownloadBudgetPayload = {
+ cloudFileId: string;
+};
+
+export const closeAndDownloadBudget = createAppAsyncThunk(
+ `${sliceName}/closeAndDownloadBudget`,
+ async ({ cloudFileId }: CloseAndDownloadBudgetPayload, { dispatch }) => {
+ await dispatch(closeBudget());
+ await dispatch(downloadBudget({ cloudFileId, replace: true }));
+ },
+);
+
+type DownloadBudgetPayload = {
+ cloudFileId: string;
+ replace?: boolean;
+};
+
+export const downloadBudget = createAppAsyncThunk(
+ `${sliceName}/downloadBudget`,
+ async (
+ { cloudFileId, replace = false }: DownloadBudgetPayload,
+ { dispatch },
+ ): Promise<string | null> => {
+ await dispatch(
+ setAppState({
+ loadingText: t('Downloading...'),
+ }),
+ );
+
+ const { id, error } = await send('download-budget', {
+ fileId: cloudFileId,
+ replace,
+ });
+
+ if (error) {
+ if (error.reason === 'decrypt-failure') {
+ const opts = {
+ hasExistingKey: error.meta && error.meta.isMissingKey,
+ cloudFileId,
+ onSuccess: () => {
+ dispatch(downloadBudget({ cloudFileId, replace }));
+ },
+ };
+
+ await dispatch(pushModal('fix-encryption-key', opts));
+ await dispatch(setAppState({ loadingText: null }));
+ } else if (error.reason === 'file-exists') {
+ alert(
+ t(
+ 'A file with id “{{id}}” already exists with the name “{{name}}”. ' +
+ 'This file will be replaced. This probably happened because files were manually ' +
+ 'moved around outside of Actual.',
+ {
+ id: error.meta.id,
+ name: error.meta.name,
+ },
+ ),
+ );
+
+ return await dispatch(
+ downloadBudget({ cloudFileId, replace: true }),
+ ).unwrap();
+ } else {
+ await dispatch(setAppState({ loadingText: null }));
+ alert(getDownloadError(error));
+ }
+ return null;
+ } else {
+ await Promise.all([
+ dispatch(loadGlobalPrefs()),
+ dispatch(loadAllFiles()),
+ dispatch(loadBudget({ id })),
+ ]);
+ await dispatch(setAppState({ loadingText: null }));
+ }
+
+ return id;
+ },
+);
+
+type LoadBackupPayload = {
+ budgetId: string;
+ backupId: string;
+};
+
+// Take in the budget id so that backups can be loaded when a budget isn't opened
+export const loadBackup = createAppAsyncThunk(
+ `${sliceName}/loadBackup`,
+ async ({ budgetId, backupId }: LoadBackupPayload, { dispatch, getState }) => {
+ const prefs = getState().prefs.local;
+ if (prefs && prefs.id) {
+ await dispatch(closeBudget());
+ }
+
+ await send('backup-load', { id: budgetId, backupId });
+ await dispatch(loadBudget({ id: budgetId }));
+ },
+);
+
+export const makeBackup = createAppAsyncThunk(
+ `${sliceName}/makeBackup`,
+ async (_, { getState }) => {
+ const prefs = getState().prefs.local;
+ if (prefs && prefs.id) {
+ await send('backup-make', { id: prefs.id });
+ }
+ },
+);
+
+type BudgetsState = {
+ budgets: Budget[];
+ remoteFiles: RemoteFile[] | null;
+ allFiles: File[] | null;
+};
+
+const initialState: BudgetsState = {
+ budgets: [],
+ remoteFiles: null,
+ allFiles: null,
+};
+
+type SetBudgetsPayload = {
+ budgets: Budget[];
+};
+
+type SetRemoteFilesPayload = {
+ remoteFiles: RemoteFile[];
+};
+
+type SetAllFilesPayload = {
+ budgets: Budget[];
+ remoteFiles: RemoteFile[];
+};
+
+const budgetsSlice = createSlice({
+ name: 'budgets',
+ initialState,
+ reducers: {
+ setBudgets(state, action: PayloadAction<SetBudgetsPayload>) {
+ state.budgets = action.payload.budgets;
+ state.allFiles = reconcileFiles(
+ action.payload.budgets,
+ state.remoteFiles,
+ );
+ },
+ setRemoteFiles(state, action: PayloadAction<SetRemoteFilesPayload>) {
+ state.remoteFiles = action.payload.remoteFiles;
+ state.allFiles = reconcileFiles(
+ state.budgets,
+ action.payload.remoteFiles,
+ );
+ },
+ setAllFiles(state, action: PayloadAction<SetAllFilesPayload>) {
+ state.budgets = action.payload.budgets;
+ state.remoteFiles = action.payload.remoteFiles;
+ state.allFiles = reconcileFiles(
+ action.payload.budgets,
+ action.payload.remoteFiles,
+ );
+ },
+ signOut(state) {
+ state.allFiles = null;
+ },
+ },
+});
+
+export const { name, reducer, getInitialState } = budgetsSlice;
+
+export const actions = {
+ ...budgetsSlice.actions,
+ loadBudgets,
+ loadRemoteFiles,
+ loadAllFiles,
+ loadBudget,
+ closeBudget,
+ closeBudgetUI,
+ deleteBudget,
+ createBudget,
+ duplicateBudget,
+ importBudget,
+ uploadBudget,
+ closeAndLoadBudget,
+ closeAndDownloadBudget,
+ downloadBudget,
+ loadBackup,
+ makeBackup,
+};
+
+export const { setBudgets, setRemoteFiles, setAllFiles, signOut } = actions;
+
+function sortFiles(arr: File[]) {
+ arr.sort((x, y) => {
+ const name1 = x.name.toLowerCase();
+ const name2 = y.name.toLowerCase();
+ let i = name1 < name2 ? -1 : name1 > name2 ? 1 : 0;
+ if (i === 0) {
+ const xId = x.state === 'remote' ? x.cloudFileId : x.id;
+ const yId = x.state === 'remote' ? x.cloudFileId : x.id;
+ i = xId < yId ? -1 : xId > yId ? 1 : 0;
+ }
+ return i;
+ });
+ return arr;
+}
+
+// States of a file:
+// 1. local - Only local (not uploaded/synced)
+// 2. remote - Unavailable locally, available to download
+// 3. synced - Downloaded & synced
+// 4. detached - Downloaded but broken group id (reset sync state)
+// 5. broken - user shouldn't have access to this file
+// 6. unknown - user is offline so can't determine the status
+function reconcileFiles(
+ localFiles: Budget[],
+ remoteFiles: RemoteFile[] | null,
+): File[] {
+ const reconciled = new Set();
+
+ const files = localFiles.map((localFile): File & { deleted: boolean } => {
+ const { cloudFileId, groupId } = localFile;
+ if (cloudFileId && groupId) {
+ // This is the case where for some reason getting the files from
+ // the server failed. We don't want to scare the user, just show
+ // an unknown state and tell them it'll be OK once they come
+ // back online
+ if (remoteFiles == null) {
+ return {
+ ...localFile,
+ cloudFileId,
+ groupId,
+ deleted: false,
+ state: 'unknown',
+ hasKey: true,
+ owner: '',
+ };
+ }
+
+ const remote = remoteFiles.find(f => localFile.cloudFileId === f.fileId);
+ if (remote) {
+ // Mark reconciled
+ reconciled.add(remote.fileId);
+
+ if (remote.groupId === localFile.groupId) {
+ return {
+ ...localFile,
+ cloudFileId,
+ groupId,
+ name: remote.name,
+ deleted: remote.deleted,
+ encryptKeyId: remote.encryptKeyId,
+ hasKey: remote.hasKey,
+ state: 'synced',
+ owner: remote.owner,
+ usersWithAccess: remote.usersWithAccess,
+ };
+ } else {
+ return {
+ ...localFile,
+ cloudFileId,
+ groupId,
+ name: remote.name,
+ deleted: remote.deleted,
+ encryptKeyId: remote.encryptKeyId,
+ hasKey: remote.hasKey,
+ state: 'detached',
+ owner: remote.owner,
+ usersWithAccess: remote.usersWithAccess,
+ };
+ }
+ } else {
+ return {
+ ...localFile,
+ cloudFileId,
+ groupId,
+ deleted: false,
+ state: 'broken',
+ hasKey: true,
+ owner: '',
+ };
+ }
+ } else {
+ return { ...localFile, deleted: false, state: 'local', hasKey: true };
+ }
+ });
+
+ const sorted = sortFiles(
+ files
+ .concat(
+ (remoteFiles || [])
+ .filter(f => !reconciled.has(f.fileId))
+ .map(f => {
+ return {
+ cloudFileId: f.fileId,
+ groupId: f.groupId,
+ name: f.name,
+ deleted: f.deleted,
+ encryptKeyId: f.encryptKeyId,
+ hasKey: f.hasKey,
+ state: 'remote',
+ owner: f.owner,
+ usersWithAccess: f.usersWithAccess,
+ };
+ }),
+ )
+ .filter(f => !f.deleted),
+ );
+
+ // One last pass to list all the broken (unauthorized) files at the
+ // bottom
+ return sorted
+ .filter(f => f.state !== 'broken')
+ .concat(sorted.filter(f => f.state === 'broken'));
+}
diff --git a/packages/loot-core/src/client/reducers/budgets.ts b/packages/loot-core/src/client/reducers/budgets.ts
deleted file mode 100644
index fad8eb9e19..0000000000
--- a/packages/loot-core/src/client/reducers/budgets.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import type { RemoteFile } from '../../server/cloud-storage';
-import type { Budget } from '../../types/budget';
-import { type File } from '../../types/file';
-import * as constants from '../constants';
-import type { Action } from '../state-types';
-import type { BudgetsState } from '../state-types/budgets';
-
-function sortFiles(arr: File[]) {
- arr.sort((x, y) => {
- const name1 = x.name.toLowerCase();
- const name2 = y.name.toLowerCase();
- let i = name1 < name2 ? -1 : name1 > name2 ? 1 : 0;
- if (i === 0) {
- const xId = x.state === 'remote' ? x.cloudFileId : x.id;
- const yId = x.state === 'remote' ? x.cloudFileId : x.id;
- i = xId < yId ? -1 : xId > yId ? 1 : 0;
- }
- return i;
- });
- return arr;
-}
-
-// States of a file:
-// 1. local - Only local (not uploaded/synced)
-// 2. remote - Unavailable locally, available to download
-// 3. synced - Downloaded & synced
-// 4. detached - Downloaded but broken group id (reset sync state)
-// 5. broken - user shouldn't have access to this file
-// 6. unknown - user is offline so can't determine the status
-function reconcileFiles(
- localFiles: Budget[],
- remoteFiles: RemoteFile[] | null,
-): File[] {
- const reconciled = new Set();
-
- const files = localFiles.map((localFile): File & { deleted: boolean } => {
- const { cloudFileId, groupId } = localFile;
- if (cloudFileId && groupId) {
- // This is the case where for some reason getting the files from
- // the server failed. We don't want to scare the user, just show
- // an unknown state and tell them it'll be OK once they come
- // back online
- if (remoteFiles == null) {
- return {
- ...localFile,
- cloudFileId,
- groupId,
- deleted: false,
- state: 'unknown',
- hasKey: true,
- owner: '',
- };
- }
-
- const remote = remoteFiles.find(f => localFile.cloudFileId === f.fileId);
- if (remote) {
- // Mark reconciled
- reconciled.add(remote.fileId);
-
- if (remote.groupId === localFile.groupId) {
- return {
- ...localFile,
- cloudFileId,
- groupId,
- name: remote.name,
- deleted: remote.deleted,
- encryptKeyId: remote.encryptKeyId,
- hasKey: remote.hasKey,
- state: 'synced',
- owner: remote.owner,
- usersWithAccess: remote.usersWithAccess,
- };
- } else {
- return {
- ...localFile,
- cloudFileId,
- groupId,
- name: remote.name,
- deleted: remote.deleted,
- encryptKeyId: remote.encryptKeyId,
- hasKey: remote.hasKey,
- state: 'detached',
- owner: remote.owner,
- usersWithAccess: remote.usersWithAccess,
- };
- }
- } else {
- return {
- ...localFile,
- cloudFileId,
- groupId,
- deleted: false,
- state: 'broken',
- hasKey: true,
- owner: '',
- };
- }
- } else {
- return { ...localFile, deleted: false, state: 'local', hasKey: true };
- }
- });
-
- const sorted = sortFiles(
- files
- .concat(
- (remoteFiles || [])
- .filter(f => !reconciled.has(f.fileId))
- .map(f => {
- return {
- cloudFileId: f.fileId,
- groupId: f.groupId,
- name: f.name,
- deleted: f.deleted,
- encryptKeyId: f.encryptKeyId,
- hasKey: f.hasKey,
- state: 'remote',
- owner: f.owner,
- usersWithAccess: f.usersWithAccess,
- };
- }),
- )
- .filter(f => !f.deleted),
- );
-
- // One last pass to list all the broken (unauthorized) files at the
- // bottom
- return sorted
- .filter(f => f.state !== 'broken')
- .concat(sorted.filter(f => f.state === 'broken'));
-}
-
-export const initialState: BudgetsState = {
- budgets: [],
- remoteFiles: null,
- allFiles: null,
-};
-
-export function update(state = initialState, action: Action): BudgetsState {
- switch (action.type) {
- case constants.SET_BUDGETS:
- return {
- ...state,
- budgets: action.budgets,
- allFiles: reconcileFiles(action.budgets, state.remoteFiles),
- };
- case constants.SET_REMOTE_FILES:
- return {
- ...state,
- remoteFiles: action.files,
- allFiles: reconcileFiles(state.budgets, action.files),
- };
- case constants.SET_ALL_FILES:
- return {
- ...state,
- budgets: action.budgets,
- remoteFiles: action.remoteFiles,
- allFiles: reconcileFiles(action.budgets, action.remoteFiles),
- };
- case constants.SIGN_OUT:
- // If the user logs out, make sure to reset all the files
- return { ...state, allFiles: null };
- default:
- }
- return state;
-}
diff --git a/packages/loot-core/src/client/reducers/index.ts b/packages/loot-core/src/client/reducers/index.ts
index 3cdfc84499..aaf67868ce 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 budgets } from './budgets';
import { update as modals } from './modals';
import { update as notifications } from './notifications';
import { update as prefs } from './prefs';
@@ -8,6 +7,5 @@ export const reducers = {
prefs,
modals,
notifications,
- budgets,
user,
};
diff --git a/packages/loot-core/src/client/reducers/modals.ts b/packages/loot-core/src/client/reducers/modals.ts
index bcf1db0e04..6f0dac1ec0 100644
--- a/packages/loot-core/src/client/reducers/modals.ts
+++ b/packages/loot-core/src/client/reducers/modals.ts
@@ -9,10 +9,14 @@ export const initialState: ModalsState = {
type ModalsAction =
| Action
- // Temporary until we migrate to redux toolkit.
+ // TODO. Temporary until we migrate to redux toolkit.
| {
type: 'app/setAppState';
payload: { loadingText: string | null };
+ }
+ // TODO: Temporary until we migrate to redux toolkit.
+ | {
+ type: 'budgets/signOut';
};
export function update(
@@ -55,7 +59,7 @@ export function update(
...state,
modalStack: idx < 0 ? state.modalStack : state.modalStack.slice(0, idx),
};
- // Temporary until we migrate to redux toolkit.
+ // TODO: Temporary until we migrate to redux toolkit.
case 'app/setAppState':
if (action.payload.loadingText) {
return {
@@ -64,7 +68,8 @@ export function update(
};
}
break;
- case constants.SIGN_OUT:
+ // TODO: Temporary until we migrate to redux toolkit.
+ case 'budgets/signOut':
return initialState;
default:
}
diff --git a/packages/loot-core/src/client/shared-listeners.ts b/packages/loot-core/src/client/shared-listeners.ts
index bad952eb56..e2c5a841a4 100644
--- a/packages/loot-core/src/client/shared-listeners.ts
+++ b/packages/loot-core/src/client/shared-listeners.ts
@@ -3,15 +3,9 @@ import { t } from 'i18next';
import { listen, send } from '../platform/client/fetch';
-import {
- addNotification,
- closeAndDownloadBudget,
- loadPrefs,
- pushModal,
- signOut,
- uploadBudget,
-} from './actions';
+import { addNotification, loadPrefs, pushModal, signOut } from './actions';
import { resetSync, sync } from './app/appSlice';
+import { closeAndDownloadBudget, uploadBudget } from './budgets/budgetsSlice';
import { getAccounts, getCategories, getPayees } from './queries/queriesSlice';
import type { Notification } from './state-types/notifications';
import { type AppStore } from './store';
@@ -197,7 +191,7 @@ export function listenForSyncEvent(store: AppStore) {
button: {
title: t('Register'),
action: async () => {
- await store.dispatch(uploadBudget());
+ await store.dispatch(uploadBudget({}));
store.dispatch(sync());
store.dispatch(loadPrefs());
},
@@ -249,7 +243,9 @@ export function listenForSyncEvent(store: AppStore) {
id: 'needs-revert',
button: {
title: t('Revert'),
- action: () => store.dispatch(closeAndDownloadBudget(cloudFileId)),
+ action: () => {
+ store.dispatch(closeAndDownloadBudget({ cloudFileId }));
+ },
},
};
break;
diff --git a/packages/loot-core/src/client/state-types/budgets.d.ts b/packages/loot-core/src/client/state-types/budgets.d.ts
deleted file mode 100644
index caa53f81de..0000000000
--- a/packages/loot-core/src/client/state-types/budgets.d.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import type { RemoteFile } from '../../server/cloud-storage';
-import type { Budget } from '../../types/budget';
-import type { File } from '../../types/file';
-import type * as constants from '../constants';
-
-export type BudgetsState = {
- budgets: Budget[];
- remoteFiles: RemoteFile[] | null;
- allFiles: File[] | null;
-};
-
-export type SetBudgetsAction = {
- type: typeof constants.SET_BUDGETS;
- budgets: Budget[];
-};
-
-export type SetRemoteFilesAction = {
- type: typeof constants.SET_REMOTE_FILES;
- files: RemoteFile[];
-};
-
-export type SetAllFilesAction = {
- type: typeof constants.SET_ALL_FILES;
- budgets: Budget[];
- remoteFiles: RemoteFile[];
-};
-
-export type SignOutAction = {
- type: typeof constants.SIGN_OUT;
-};
-
-export type BudgetsActions =
- | SetBudgetsAction
- | SetRemoteFilesAction
- | SetAllFilesAction
- | SignOutAction;
diff --git a/packages/loot-core/src/client/state-types/index.d.ts b/packages/loot-core/src/client/state-types/index.d.ts
index a7665c59a8..6cb70748c0 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 { BudgetsActions, BudgetsState } from './budgets';
import type { ModalsActions, ModalsState } from './modals';
import type { NotificationsActions, NotificationsState } from './notifications';
import type { PrefsActions, PrefsState } from './prefs';
@@ -11,7 +10,6 @@ export type CloseBudgetAction = {
};
export type Action =
- | BudgetsActions
| ModalsActions
| NotificationsActions
| PrefsActions
@@ -19,7 +17,6 @@ export type Action =
| CloseBudgetAction;
export type State = {
- budgets: BudgetsState;
modals: ModalsState;
notifications: NotificationsState;
prefs: PrefsState;
diff --git a/packages/loot-core/src/client/store/index.ts b/packages/loot-core/src/client/store/index.ts
index 8ad3d8f466..95523b362b 100644
--- a/packages/loot-core/src/client/store/index.ts
+++ b/packages/loot-core/src/client/store/index.ts
@@ -16,6 +16,11 @@ import {
reducer as appSliceReducer,
getInitialState as getInitialAppState,
} from '../app/appSlice';
+import {
+ name as budgetsSliceName,
+ reducer as budgetsSliceReducer,
+ getInitialState as getInitialBudgetsState,
+} from '../budgets/budgetsSlice';
import * as constants from '../constants';
import {
name as queriesSliceName,
@@ -23,7 +28,6 @@ import {
getInitialState as getInitialQueriesState,
} from '../queries/queriesSlice';
import { reducers } from '../reducers';
-import { initialState as initialBudgetsState } from '../reducers/budgets';
import { initialState as initialModalsState } from '../reducers/modals';
import { initialState as initialNotificationsState } from '../reducers/notifications';
import { initialState as initialPrefsState } from '../reducers/prefs';
@@ -33,6 +37,7 @@ const appReducer = combineReducers({
...reducers,
[accountsSliceName]: accountsSliceReducer,
[appSliceName]: appSliceReducer,
+ [budgetsSliceName]: budgetsSliceReducer,
[queriesSliceName]: queriesSliceReducer,
});
const rootReducer: typeof appReducer = (state, action) => {
@@ -44,7 +49,7 @@ const rootReducer: typeof appReducer = (state, action) => {
modals: initialModalsState,
notifications: initialNotificationsState,
queries: getInitialQueriesState(),
- budgets: state?.budgets || initialBudgetsState,
+ budgets: state?.budgets || getInitialBudgetsState(),
user: state?.user || initialUserState,
prefs: {
local: initialPrefsState.local,
diff --git a/packages/loot-core/src/client/store/mock.ts b/packages/loot-core/src/client/store/mock.ts
index c2342bea30..318ee26637 100644
--- a/packages/loot-core/src/client/store/mock.ts
+++ b/packages/loot-core/src/client/store/mock.ts
@@ -8,6 +8,10 @@ import {
name as appSliceName,
reducer as appSliceReducer,
} from '../app/appSlice';
+import {
+ name as budgetsSliceName,
+ reducer as budgetsSliceReducer,
+} from '../budgets/budgetsSlice';
import {
name as queriesSliceName,
reducer as queriesSliceReducer,
@@ -20,6 +24,7 @@ const appReducer = combineReducers({
...reducers,
[accountsSliceName]: accountsSliceReducer,
[appSliceName]: appSliceReducer,
+ [budgetsSliceName]: budgetsSliceReducer,
[queriesSliceName]: queriesSliceReducer,
});
diff --git a/upcoming-release-notes/4114.md b/upcoming-release-notes/4114.md
new file mode 100644
index 0000000000..9e9fb6eaac
--- /dev/null
+++ b/upcoming-release-notes/4114.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [joel-jeremy]
+---
+
+Phase 2 - Redux Toolkit Migration - budgets slice