Skip to content

A local-first personal finance app

Add typings to most of the Redux logic (#1269)

Jed Fox2860837741d8
diff --git a/.eslintrc.js b/.eslintrc.js
index b340b3d86b..fe925974b4 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -185,9 +185,10 @@ module.exports = {
},
{
files: [
- '**/icons/**/*.js',
- '**/mocks/**/*.{js,ts,tsx}',
- '**/{mocks,__mocks__}/*.{js,ts,tsx}',
+ 'packages/loot-core/src/types/**/*',
+ 'packages/loot-core/src/client/state-types/**/*',
+ '**/icons/**/*',
+ '**/{mocks,__mocks__}/**/*',
// can't correctly resolve usages
'**/*.{testing,electron,browser,web,api}.ts',
],
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.json
index b13a596c9d..855dedb088 100644
--- a/packages/desktop-client/package.json
+++ b/packages/desktop-client/package.json
@@ -20,6 +20,7 @@
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.1",
"@types/react-modal": "^3.16.0",
+ "@types/react-redux": "^7.1.25",
"@types/react-router-dom": "^5.3.3",
"@types/uuid": "^9.0.2",
"@types/webpack-bundle-analyzer": "^4.6.0",
diff --git a/packages/desktop-client/src/components/Modals.js b/packages/desktop-client/src/components/Modals.js
index 1f80cfdb71..502201f25b 100644
--- a/packages/desktop-client/src/components/Modals.js
+++ b/packages/desktop-client/src/components/Modals.js
@@ -11,7 +11,6 @@ import useSyncServerStatus from '../hooks/useSyncServerStatus';
import BudgetSummary from './modals/BudgetSummary';
import CloseAccount from './modals/CloseAccount';
-import ConfigureLinkedAccounts from './modals/ConfigureLinkedAccounts';
import ConfirmCategoryDelete from './modals/ConfirmCategoryDelete';
import CreateAccount from './modals/CreateAccount';
import CreateEncryptionKey from './modals/CreateEncryptionKey';
@@ -97,18 +96,6 @@ function Modals({
/>
);
- case 'configure-linked-accounts':
- return (
- <ConfigureLinkedAccounts
- modalProps={modalProps}
- institution={options.institution}
- publicToken={options.publicToken}
- accounts={options.accounts}
- upgradingId={options.upgradingId}
- actions={actions}
- />
- );
-
case 'confirm-category-delete':
return (
<ConfirmCategoryDelete
diff --git a/packages/desktop-client/src/components/Notifications.js b/packages/desktop-client/src/components/Notifications.tsx
similarity index 88%
rename from packages/desktop-client/src/components/Notifications.js
rename to packages/desktop-client/src/components/Notifications.tsx
index d584609155..67287e2ec1 100644
--- a/packages/desktop-client/src/components/Notifications.js
+++ b/packages/desktop-client/src/components/Notifications.tsx
@@ -1,9 +1,15 @@
-import React, { useState, useEffect, useMemo } from 'react';
-import { connect } from 'react-redux';
+import React, {
+ useState,
+ useEffect,
+ useMemo,
+ type SetStateAction,
+} from 'react';
+import { connect, useSelector } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from 'loot-core/src/client/actions';
+import type { NotificationWithId } from 'loot-core/src/client/state-types/notifications';
import Loading from '../icons/AnimatedLoading';
import Delete from '../icons/v0/Delete';
@@ -19,7 +25,12 @@ import {
LinkButton,
} from './common';
-function compileMessage(message, actions, setLoading, onRemove) {
+function compileMessage(
+ message: string,
+ actions: Record<string, () => void>,
+ setLoading: (arg: SetStateAction<boolean>) => void,
+ onRemove?: () => void,
+) {
return (
<Stack spacing={2}>
{message.split(/\n\n/).map((paragraph, idx) => {
@@ -65,7 +76,13 @@ function compileMessage(message, actions, setLoading, onRemove) {
);
}
-function Notification({ notification, onRemove }) {
+function Notification({
+ notification,
+ onRemove,
+}: {
+ notification: NotificationWithId;
+ onRemove: () => void;
+}) {
let { type, title, message, pre, messageActions, sticky, internal, button } =
notification;
@@ -203,7 +220,8 @@ function Notification({ notification, onRemove }) {
);
}
-function Notifications({ notifications, removeNotification, style }) {
+function Notifications({ removeNotification, style }) {
+ let notifications = useSelector(state => state.notifications.notifications);
return (
<View
style={[
@@ -232,7 +250,6 @@ function Notifications({ notifications, removeNotification, style }) {
);
}
-export default connect(
- state => ({ notifications: state.notifications.notifications }),
- dispatch => bindActionCreators(actions, dispatch),
-)(Notifications);
+export default connect(null, dispatch => bindActionCreators(actions, dispatch))(
+ Notifications,
+);
diff --git a/packages/desktop-client/src/components/manager/ImportActual.js b/packages/desktop-client/src/components/manager/ImportActual.js
index 4579fd2e28..ba2d460bd2 100644
--- a/packages/desktop-client/src/components/manager/ImportActual.js
+++ b/packages/desktop-client/src/components/manager/ImportActual.js
@@ -23,7 +23,7 @@ function getErrorMessage(error) {
}
}
-function Import({ modalProps, availableImports }) {
+function Import({ modalProps }) {
const dispatch = useDispatch();
const [error, setError] = useState(false);
const [importing, setImporting] = useState(false);
diff --git a/packages/desktop-client/src/components/manager/ImportYNAB4.js b/packages/desktop-client/src/components/manager/ImportYNAB4.js
index 218e84452d..7c2d9cd7ae 100644
--- a/packages/desktop-client/src/components/manager/ImportYNAB4.js
+++ b/packages/desktop-client/src/components/manager/ImportYNAB4.js
@@ -15,7 +15,7 @@ function getErrorMessage(error) {
}
}
-function Import({ modalProps, availableImports }) {
+function Import({ modalProps }) {
const dispatch = useDispatch();
const [error, setError] = useState(false);
const [importing, setImporting] = useState(false);
diff --git a/packages/desktop-client/src/components/manager/ImportYNAB5.js b/packages/desktop-client/src/components/manager/ImportYNAB5.js
index 393038f2f7..302db9cae0 100644
--- a/packages/desktop-client/src/components/manager/ImportYNAB5.js
+++ b/packages/desktop-client/src/components/manager/ImportYNAB5.js
@@ -24,7 +24,7 @@ function getErrorMessage(error) {
}
}
-function Import({ modalProps, availableImports }) {
+function Import({ modalProps }) {
const dispatch = useDispatch();
const [error, setError] = useState(false);
const [importing, setImporting] = useState(false);
diff --git a/packages/desktop-client/src/components/manager/Modals.js b/packages/desktop-client/src/components/manager/Modals.js
index d945e73690..a77e6356d8 100644
--- a/packages/desktop-client/src/components/manager/Modals.js
+++ b/packages/desktop-client/src/components/manager/Modals.js
@@ -16,7 +16,7 @@ import ImportActual from './ImportActual';
import ImportYNAB4 from './ImportYNAB4';
import ImportYNAB5 from './ImportYNAB5';
-function Modals({ modalStack, isHidden, availableImports, actions }) {
+function Modals({ modalStack, isHidden, actions }) {
let stack = modalStack.map(({ name, options }, idx) => {
const modalProps = {
onClose: actions.popModal,
@@ -38,14 +38,7 @@ function Modals({ modalStack, isHidden, availableImports, actions }) {
/>
);
case 'import':
- return (
- <Import
- key={name}
- modalProps={modalProps}
- actions={actions}
- availableImports={availableImports}
- />
- );
+ return <Import key={name} modalProps={modalProps} actions={actions} />;
case 'import-ynab4':
return (
<ImportYNAB4 key={name} modalProps={modalProps} actions={actions} />
@@ -102,7 +95,6 @@ export default connect(
modalStack: state.modals.modalStack,
isHidden: state.modals.isHidden,
budgets: state.budgets.budgets,
- availableImports: state.budgets.availableImports,
}),
dispatch => ({ actions: bindActionCreators(actions, dispatch) }),
)(Modals);
diff --git a/packages/desktop-client/src/components/modals/ConfigureLinkedAccounts.js b/packages/desktop-client/src/components/modals/ConfigureLinkedAccounts.js
deleted file mode 100644
index dedafb9577..0000000000
--- a/packages/desktop-client/src/components/modals/ConfigureLinkedAccounts.js
+++ /dev/null
@@ -1,166 +0,0 @@
-import React, { useState } from 'react';
-
-import { determineOffBudget } from 'loot-core/src/shared/accounts';
-
-import Checkmark from '../../icons/v1/Checkmark';
-import { styles, colors } from '../../style';
-import { View, Text, Modal, Button } from '../common';
-
-function EmptyMessage() {
- return null;
-}
-
-function Account({ account, offbudget, onSelect }) {
- return (
- <View
- style={[
- { marginBottom: 8, flexShrink: 0, userSelect: 'none' },
- styles.mediumText,
- ]}
- onClick={onSelect}
- >
- <View
- style={[
- {
- padding: 12,
- ...styles.shadow,
- cursor: 'pointer',
- transition: 'transform .20s',
- fontSize: 14,
- borderRadius: 4,
- flexDirection: 'row',
- alignItems: 'center',
- border: '1px solid ' + colors.n10,
- },
- ]}
- >
- <View style={{ flex: 1 }}>
- <View style={{ fontWeight: 600 }}>{account.name}</View>
- <View
- style={{
- fontSize: 13,
- color: colors.n5,
- flexDirection: 'row',
- }}
- >
- <Text style={{ marginLeft: 4 }}>
- ...
- {account.mask}
- </Text>
- </View>
- </View>
-
- {offbudget ? (
- <Text style={{ color: colors.n8 }}>Off budget</Text>
- ) : (
- <>
- <Checkmark style={{ width: 15, height: 15, color: colors.g5 }} />
- <Text style={{ color: colors.g5, marginLeft: 5 }}>Budgeted</Text>
- </>
- )}
- </View>
- </View>
- );
-}
-
-export default function ConfigureLinkedAccounts({
- institution,
- publicToken,
- upgradingId,
- modalProps,
- accounts,
- actions,
-}) {
- let [offbudgetAccounts, setOffbudgetAccounts] = useState(() =>
- accounts.filter(acct => determineOffBudget(acct.type)).map(acct => acct.id),
- );
-
- function toggleAccount(id) {
- if (offbudgetAccounts.includes(id)) {
- setOffbudgetAccounts(offbudgetAccounts.filter(x => x !== id));
- } else {
- setOffbudgetAccounts([...offbudgetAccounts, id]);
- }
- }
-
- async function onNext() {
- let ids = await actions.connectNordigenAccounts(
- institution,
- publicToken,
- accounts.map(acct => acct.id),
- offbudgetAccounts,
- );
-
- actions.closeModal();
-
- if (ids.length === 1) {
- window.location.hash = '/accounts/' + ids[0];
- } else if (ids.length > 0) {
- window.location.hash = '/accounts';
- }
- }
-
- return (
- <Modal
- title={upgradingId ? 'Link Account' : 'Link Accounts'}
- {...modalProps}
- >
- {() => (
- <View style={{ maxWidth: 500 }}>
- <Text style={{ fontSize: 15, marginBottom: 15, lineHeight: '1.4em' }}>
- A <strong>budgeted account</strong> is one where expenses and income
- affect the budget. Usually things like investments are off budget.
- We’ve chosen some defaults here, but you can change the status if
- you like.
- </Text>
-
- <View
- style={{
- maxHeight: 300,
- overflow: 'auto',
- // Allow the shadow to appear on left/right edge
- paddingLeft: 5,
- paddingRight: 5,
- marginLeft: -5,
- marginRight: -5,
- }}
- >
- <View>
- {accounts.length === 0 ? (
- <EmptyMessage />
- ) : (
- accounts.map(account => {
- let offbudget = offbudgetAccounts.includes(account.id);
-
- return (
- <Account
- key={account.id}
- account={account}
- offbudget={offbudget}
- onSelect={() => toggleAccount(account.id)}
- />
- );
- })
- )}
- </View>
- </View>
-
- <View
- style={{
- flexDirection: 'row',
- justifyContent: 'flex-end',
- marginTop: 30,
- }}
- >
- <Button style={{ marginRight: 10 }} onClick={modalProps.onBack}>
- Back
- </Button>
- <Button primary onClick={onNext}>
- {upgradingId ? 'Link Account' : 'Next'}
- </Button>
- </View>
- </View>
- )}
- </Modal>
- );
-}
diff --git a/packages/desktop-client/src/hooks/useActions.ts b/packages/desktop-client/src/hooks/useActions.ts
new file mode 100644
index 0000000000..b60a9abe0e
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useActions.ts
@@ -0,0 +1,15 @@
+import { useMemo } from 'react';
+import { useDispatch } from 'react-redux';
+
+import { bindActionCreators } from 'redux';
+
+import * as actions from 'loot-core/src/client/actions';
+
+// https://react-redux.js.org/api/hooks#recipe-useactions
+// eslint-disable-next-line import/no-unused-modules
+export function useActions() {
+ const dispatch = useDispatch();
+ return useMemo(() => {
+ return bindActionCreators(actions, dispatch);
+ }, [dispatch]);
+}
diff --git a/packages/desktop-client/src/hooks/useFeatureFlag.ts b/packages/desktop-client/src/hooks/useFeatureFlag.ts
index 996bf328eb..b859204d67 100644
--- a/packages/desktop-client/src/hooks/useFeatureFlag.ts
+++ b/packages/desktop-client/src/hooks/useFeatureFlag.ts
@@ -1,11 +1,13 @@
import { useSelector } from 'react-redux';
-const DEFAULT_FEATURE_FLAG_STATE: Record<string, boolean> = {
+import { type FeatureFlag } from 'loot-core/src/client/state-types/prefs';
+
+const DEFAULT_FEATURE_FLAG_STATE: Record<FeatureFlag, boolean> = {
reportBudget: false,
goalTemplatesEnabled: false,
};
-export default function useFeatureFlag(name: string): boolean {
+export default function useFeatureFlag(name: FeatureFlag): boolean {
return useSelector(state => {
const value = state.prefs.local[`flags.${name}`];
@@ -15,7 +17,7 @@ export default function useFeatureFlag(name: string): boolean {
});
}
-export function useAllFeatureFlags(): Record<string, boolean> {
+export function useAllFeatureFlags(): Record<FeatureFlag, boolean> {
return useSelector(state => {
return {
...DEFAULT_FEATURE_FLAG_STATE,
diff --git a/packages/loot-core/package.json b/packages/loot-core/package.json
index df5a87b743..cdc8f71c0b 100644
--- a/packages/loot-core/package.json
+++ b/packages/loot-core/package.json
@@ -50,6 +50,7 @@
"@types/jest": "^27.5.0",
"@types/jlongster__sql.js": "npm:@types/sql.js@latest",
"@types/pegjs": "^0.10.3",
+ "@types/react-redux": "^7.1.25",
"@types/uuid": "^9.0.2",
"@types/webpack": "^5.28.0",
"@types/webpack-bundle-analyzer": "^4.6.0",
diff --git a/packages/loot-core/src/client/actions/account.ts b/packages/loot-core/src/client/actions/account.ts
index e793d49360..14f14d6133 100644
--- a/packages/loot-core/src/client/actions/account.ts
+++ b/packages/loot-core/src/client/actions/account.ts
@@ -1,17 +1,29 @@
import { send } from '../../platform/client/fetch';
import * as constants from '../constants';
+import type {
+ AccountSyncFailuresAction,
+ AccountSyncStatusAction,
+ SetAccountsSyncingAction,
+} from '../state-types/account';
import { addNotification } from './notifications';
import { getPayees, getAccounts } from './queries';
+import type { ActionResult } from './types';
-export function setAccountsSyncing(name) {
+export function setAccountsSyncing(
+ name: SetAccountsSyncingAction['name'],
+): ActionResult {
return {
type: constants.SET_ACCOUNTS_SYNCING,
name,
};
}
-export function markAccountFailed(id, errorType, errorCode) {
+export function markAccountFailed(
+ id: AccountSyncStatusAction['id'],
+ errorType?: string,
+ errorCode?: string,
+): ActionResult {
return {
type: 'ACCOUNT_SYNC_STATUS',
id,
@@ -20,21 +32,25 @@ export function markAccountFailed(id, errorType, errorCode) {
errorCode,
};
}
-export function markAccountSuccess(id) {
+export function markAccountSuccess(
+ id: AccountSyncStatusAction['id'],
+): ActionResult {
return {
type: 'ACCOUNT_SYNC_STATUS',
id,
failed: false,
};
}
-export function setFailedAccounts(syncErrors) {
+export function setFailedAccounts(
+ syncErrors: AccountSyncFailuresAction['syncErrors'],
+): ActionResult {
return {
type: 'ACCOUNT_SYNC_FAILURES',
syncErrors,
};
}
-export function unlinkAccount(id) {
+export function unlinkAccount(id: string): ActionResult {
return async dispatch => {
await send('account-unlink', { id });
dispatch(markAccountSuccess(id));
@@ -42,7 +58,7 @@ export function unlinkAccount(id) {
};
}
-export function linkAccount(requisitionId, account, upgradingId) {
+export function linkAccount(requisitionId, account, upgradingId): ActionResult {
return async dispatch => {
await send('nordigen-accounts-link', {
requisitionId,
@@ -59,7 +75,7 @@ export function connectAccounts(
publicToken,
accountIds,
offbudgetIds,
-) {
+): ActionResult {
return async dispatch => {
let ids = await send('accounts-connect', {
institution,
@@ -78,7 +94,7 @@ export function connectNordigenAccounts(
publicToken,
accountIds,
offbudgetIds,
-) {
+): ActionResult {
return async dispatch => {
let ids = await send('nordigen-accounts-connect', {
institution,
@@ -92,7 +108,7 @@ export function connectNordigenAccounts(
};
}
-export function syncAccounts(id) {
+export function syncAccounts(id): ActionResult {
return async (dispatch, getState) => {
if (getState().account.accountsSyncing) {
return false;
@@ -166,14 +182,14 @@ export function syncAccounts(id) {
}
// Remember the last transaction manually added to the system
-export function setLastTransaction(transaction) {
+export function setLastTransaction(transaction): ActionResult {
return {
type: constants.SET_LAST_TRANSACTION,
transaction,
};
}
-export function parseTransactions(filepath, options) {
+export function parseTransactions(filepath, options): ActionResult {
return async dispatch => {
return await send('transactions-parse-file', {
filepath,
@@ -182,7 +198,7 @@ export function parseTransactions(filepath, options) {
};
}
-export function importTransactions(id, transactions) {
+export function importTransactions(id, transactions): ActionResult {
return async dispatch => {
let {
errors = [],
@@ -213,14 +229,14 @@ export function importTransactions(id, transactions) {
};
}
-export function updateNewTransactions(changedId) {
+export function updateNewTransactions(changedId): ActionResult {
return {
type: constants.UPDATE_NEW_TRANSACTIONS,
changedId,
};
}
-export function markAccountRead(accountId) {
+export function markAccountRead(accountId): ActionResult {
return {
type: constants.MARK_ACCOUNT_READ,
accountId: accountId,
diff --git a/packages/loot-core/src/client/actions/app.ts b/packages/loot-core/src/client/actions/app.ts
index 7ee582794a..05d4476acb 100644
--- a/packages/loot-core/src/client/actions/app.ts
+++ b/packages/loot-core/src/client/actions/app.ts
@@ -1,21 +1,26 @@
import { send } from '../../platform/client/fetch';
import * as constants from '../constants';
+import type { AppState, SetLastUndoStateAction } from '../state-types/app';
-export function setAppState(state) {
+import type { ActionResult } from './types';
+
+export function setAppState(state: Partial<AppState>): ActionResult {
return {
type: constants.SET_APP_STATE,
state,
};
}
-export function updateApp() {
+export function updateApp(): ActionResult {
return async dispatch => {
global.Actual.applyAppUpdate();
dispatch(setAppState({ updateInfo: null }));
};
}
-export function setLastUndoState(undoState) {
+export function setLastUndoState(
+ undoState: SetLastUndoStateAction['undoState'],
+): ActionResult {
return {
type: constants.SET_LAST_UNDO_STATE,
undoState,
@@ -25,13 +30,16 @@ export function setLastUndoState(undoState) {
// This is only used in the fake web version where everything runs in
// the browser. It's a way to send a file to the backend to be
// imported into the virtual filesystem.
-export function uploadFile(filename: string, contents: ArrayBuffer) {
+export function uploadFile(
+ filename: string,
+ contents: ArrayBuffer,
+): ActionResult {
return dispatch => {
return send('upload-file-web', { filename, contents });
};
}
-export function focused() {
+export function focused(): ActionResult {
return dispatch => {
return send('app-focused');
};
diff --git a/packages/loot-core/src/client/actions/backups.ts b/packages/loot-core/src/client/actions/backups.ts
index 2bb7bc1daf..e36f872e14 100644
--- a/packages/loot-core/src/client/actions/backups.ts
+++ b/packages/loot-core/src/client/actions/backups.ts
@@ -1,10 +1,11 @@
import { send } from '../../platform/client/fetch';
import { closeBudget, loadBudget } from './budgets';
+import type { ActionResult } from './types';
// Take in the budget id so that backups can be loaded when a budget
// isn't opened
-export function loadBackup(budgetId, backupId) {
+export function loadBackup(budgetId, backupId): ActionResult {
return async (dispatch, getState) => {
const prefs = getState().prefs.local;
if (prefs && prefs.id) {
@@ -16,7 +17,7 @@ export function loadBackup(budgetId, backupId) {
};
}
-export function makeBackup() {
+export function makeBackup(): ActionResult {
return async (dispatch, getState) => {
const prefs = getState().prefs.local;
if (prefs && prefs.id) {
diff --git a/packages/loot-core/src/client/actions/budgets.ts b/packages/loot-core/src/client/actions/budgets.ts
index d9b6f18dfc..498541c627 100644
--- a/packages/loot-core/src/client/actions/budgets.ts
+++ b/packages/loot-core/src/client/actions/budgets.ts
@@ -1,12 +1,14 @@
import { send } from '../../platform/client/fetch';
import { getDownloadError, getSyncError } from '../../shared/errors';
+import type { Handlers } from '../../types/handlers';
import * as constants from '../constants';
import { setAppState } from './app';
import { closeModal, pushModal } from './modals';
import { loadPrefs, loadGlobalPrefs } from './prefs';
+import type { ActionResult } from './types';
-export function updateStatusText(text) {
+export function updateStatusText(text: string | null): ActionResult {
return (dispatch, getState) => {
const { loadingText } = getState().app;
// The presence of any loading text puts the app in a "loading"
@@ -19,7 +21,7 @@ export function updateStatusText(text) {
};
}
-export function loadBudgets() {
+export function loadBudgets(): ActionResult {
return async dispatch => {
const budgets = await send('get-budgets');
@@ -30,7 +32,7 @@ export function loadBudgets() {
};
}
-export function loadRemoteFiles() {
+export function loadRemoteFiles(): ActionResult {
return async dispatch => {
const files = await send('get-remote-files');
@@ -41,7 +43,7 @@ export function loadRemoteFiles() {
};
}
-export function loadAllFiles() {
+export function loadAllFiles(): ActionResult {
return async (dispatch, getState) => {
const budgets = await send('get-budgets');
const files = await send('get-remote-files');
@@ -56,7 +58,11 @@ export function loadAllFiles() {
};
}
-export function loadBudget(id, loadingText = '', options = {}) {
+export function loadBudget(
+ id: string,
+ loadingText = '',
+ options = {},
+): ActionResult {
return async (dispatch, getState) => {
dispatch(setAppState({ loadingText }));
@@ -91,13 +97,11 @@ export function loadBudget(id, loadingText = '', options = {}) {
await dispatch(loadPrefs());
- const prefs = getState().prefs.local;
dispatch(setAppState({ loadingText: null }));
- dispatch(setAppState({ maxMonths: prefs.maxMonths }));
};
}
-export function closeBudget() {
+export function closeBudget(): ActionResult {
return async (dispatch, getState) => {
const prefs = getState().prefs.local;
if (prefs && prefs.id) {
@@ -114,7 +118,7 @@ export function closeBudget() {
};
}
-export function closeBudgetUI() {
+export function closeBudgetUI(): ActionResult {
return async (dispatch, getState) => {
let prefs = getState().prefs.local;
if (prefs && prefs.id) {
@@ -123,14 +127,20 @@ export function closeBudgetUI() {
};
}
-export function deleteBudget(id, cloudFileId) {
+export function deleteBudget(
+ id: string | undefined,
+ cloudFileId: string | undefined,
+): ActionResult {
return async dispatch => {
await send('delete-budget', { id, cloudFileId });
await dispatch(loadAllFiles());
};
}
-export function createBudget({ testMode = false, demoMode = false } = {}) {
+export function createBudget({
+ testMode = false,
+ demoMode = false,
+} = {}): ActionResult {
return async (dispatch, getState) => {
dispatch(
setAppState({
@@ -155,7 +165,10 @@ export function createBudget({ testMode = false, demoMode = false } = {}) {
};
}
-export function importBudget(filepath, type) {
+export function importBudget(
+ filepath: string,
+ type: Parameters<Handlers['import-budget']>[0]['type'],
+): ActionResult {
return async (dispatch, getState) => {
const { error } = await send('import-budget', { filepath, type });
if (error) {
@@ -169,7 +182,7 @@ export function importBudget(filepath, type) {
};
}
-export function uploadBudget(id) {
+export function uploadBudget(id: string): ActionResult {
return async dispatch => {
let { error } = await send('upload-budget', { id });
if (error) {
@@ -181,7 +194,7 @@ export function uploadBudget(id) {
};
}
-export function closeAndDownloadBudget(cloudFileId) {
+export function closeAndDownloadBudget(cloudFileId: string): ActionResult {
return async dispatch => {
// It's very important that we set this loading message before
// closing the budget. Otherwise, the manager will ignore our
@@ -193,7 +206,10 @@ export function closeAndDownloadBudget(cloudFileId) {
};
}
-export function downloadBudget(cloudFileId, { replace = false } = {}) {
+export function downloadBudget(
+ cloudFileId: string,
+ { replace = false } = {},
+): ActionResult {
return async dispatch => {
dispatch(setAppState({ loadingText: 'Downloading...' }));
diff --git a/packages/loot-core/src/client/actions/debug.ts b/packages/loot-core/src/client/actions/debug.ts
deleted file mode 100644
index cad70bd366..0000000000
--- a/packages/loot-core/src/client/actions/debug.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import * as constants from '../constants';
-
-export function debugCell(sheet, name) {
- return {
- type: constants.DEBUG_CELL,
- sheet,
- name,
- };
-}
diff --git a/packages/loot-core/src/client/actions/index.ts b/packages/loot-core/src/client/actions/index.ts
index ceeb1124e4..ec9bda79e1 100644
--- a/packages/loot-core/src/client/actions/index.ts
+++ b/packages/loot-core/src/client/actions/index.ts
@@ -1,6 +1,5 @@
export * from './queries';
export * from './account';
-export * from './debug';
export * from './modals';
export * from './notifications';
export * from './prefs';
diff --git a/packages/loot-core/src/client/actions/modals.ts b/packages/loot-core/src/client/actions/modals.ts
index 04d5d31a44..27b33df09b 100644
--- a/packages/loot-core/src/client/actions/modals.ts
+++ b/packages/loot-core/src/client/actions/modals.ts
@@ -1,25 +1,19 @@
import * as constants from '../constants';
-export function pushModal(name, options) {
+import type { ActionResult } from './types';
+
+export function pushModal(name: string, options: unknown): ActionResult {
return { type: constants.PUSH_MODAL, name, options };
}
-export function replaceModal(name, options) {
+export function replaceModal(name: string, options: unknown): ActionResult {
return { type: constants.REPLACE_MODAL, name, options };
}
-export function hideModals() {
- return { type: constants.HIDE_MODALS };
-}
-
-export function showModals() {
- return { type: constants.SHOW_MODALS };
-}
-
-export function popModal() {
+export function popModal(): ActionResult {
return { type: constants.POP_MODAL };
}
-export function closeModal() {
+export function closeModal(): ActionResult {
return { type: constants.CLOSE_MODAL };
}
diff --git a/packages/loot-core/src/client/actions/notifications.ts b/packages/loot-core/src/client/actions/notifications.ts
index 732c744d92..ca3cd6964f 100644
--- a/packages/loot-core/src/client/actions/notifications.ts
+++ b/packages/loot-core/src/client/actions/notifications.ts
@@ -1,8 +1,13 @@
import { v4 as uuidv4 } from 'uuid';
import * as constants from '../constants';
+import { type Notification } from '../state-types/notifications';
-export function addNotification(notification) {
+import type { ActionResult } from './types';
+
+export function addNotification(
+ notification: Omit<Notification, 'id'> & { id?: string },
+): ActionResult {
return {
type: constants.ADD_NOTIFICATION,
notification: {
@@ -12,7 +17,7 @@ export function addNotification(notification) {
};
}
-export function addGenericErrorNotification() {
+export function addGenericErrorNotification(): ActionResult {
return addNotification({
type: 'error',
message:
@@ -21,7 +26,7 @@ export function addGenericErrorNotification() {
});
}
-export function removeNotification(id) {
+export function removeNotification(id: string): ActionResult {
return {
type: constants.REMOVE_NOTIFICATION,
id,
diff --git a/packages/loot-core/src/client/actions/prefs.ts b/packages/loot-core/src/client/actions/prefs.ts
index e0236cdd40..c6ca850f2e 100644
--- a/packages/loot-core/src/client/actions/prefs.ts
+++ b/packages/loot-core/src/client/actions/prefs.ts
@@ -2,8 +2,9 @@ import { send } from '../../platform/client/fetch';
import * as constants from '../constants';
import { closeModal } from './modals';
+import type { ActionResult } from './types';
-export function loadPrefs() {
+export function loadPrefs(): ActionResult {
return async (dispatch, getState) => {
let prefs = await send('load-prefs');
@@ -23,7 +24,7 @@ export function loadPrefs() {
};
}
-export function savePrefs(prefs) {
+export function savePrefs(prefs): ActionResult {
return async dispatch => {
await send('save-prefs', prefs);
dispatch({
@@ -33,7 +34,7 @@ export function savePrefs(prefs) {
};
}
-export function loadGlobalPrefs() {
+export function loadGlobalPrefs(): ActionResult {
return async (dispatch, getState) => {
let globalPrefs = await send('load-global-prefs');
dispatch({
@@ -45,7 +46,7 @@ export function loadGlobalPrefs() {
};
}
-export function saveGlobalPrefs(prefs) {
+export function saveGlobalPrefs(prefs): ActionResult {
return async dispatch => {
await send('save-global-prefs', prefs);
dispatch({
diff --git a/packages/loot-core/src/client/actions/queries.ts b/packages/loot-core/src/client/actions/queries.ts
index 3dc59dc5ea..63524f60e2 100644
--- a/packages/loot-core/src/client/actions/queries.ts
+++ b/packages/loot-core/src/client/actions/queries.ts
@@ -5,6 +5,7 @@ import * as constants from '../constants';
import { pushModal } from './modals';
import { addNotification, addGenericErrorNotification } from './notifications';
+import type { ActionResult } from './types';
export function applyBudgetAction(month, type, args) {
return async function (dispatch) {
@@ -91,7 +92,7 @@ export function applyBudgetAction(month, type, args) {
};
}
-export function getCategories() {
+export function getCategories(): ActionResult {
return async function (dispatch) {
const categories = await send('get-categories');
dispatch({
@@ -102,7 +103,11 @@ export function getCategories() {
};
}
-export function createCategory(name, groupId, isIncome) {
+export function createCategory(
+ name: string,
+ groupId: string,
+ isIncome: boolean,
+): ActionResult {
return async function (dispatch) {
let id = await send('category-create', {
name,
@@ -114,7 +119,7 @@ export function createCategory(name, groupId, isIncome) {
};
}
-export function deleteCategory(id, transferId) {
+export function deleteCategory(id: string, transferId?: string): ActionResult {
return async function (dispatch, getState) {
let { error } = await send('category-delete', { id, transferId });
@@ -143,28 +148,28 @@ export function deleteCategory(id, transferId) {
};
}
-export function updateCategory(category) {
+export function updateCategory(category): ActionResult {
return async dispatch => {
await send('category-update', category);
dispatch(getCategories());
};
}
-export function moveCategory(id, groupId, targetId) {
+export function moveCategory(id, groupId, targetId): ActionResult {
return async (dispatch, getState) => {
await send('category-move', { id, groupId, targetId });
await dispatch(getCategories());
};
}
-export function moveCategoryGroup(id, targetId) {
+export function moveCategoryGroup(id, targetId): ActionResult {
return async dispatch => {
await send('category-group-move', { id, targetId });
await dispatch(getCategories());
};
}
-export function createGroup(name) {
+export function createGroup(name): ActionResult {
return async dispatch => {
let id = await send('category-group-create', { name });
dispatch(getCategories());
@@ -172,7 +177,7 @@ export function createGroup(name) {
};
}
-export function updateGroup(group) {
+export function updateGroup(group): ActionResult {
// Strip off the categories field if it exist. It's not a real db
// field but groups have this extra field in the client most of the
// time
@@ -184,7 +189,7 @@ export function updateGroup(group) {
};
}
-export function deleteGroup(id, transferId) {
+export function deleteGroup(id, transferId): ActionResult {
return async function (dispatch, getState) {
await send('category-group-delete', { id, transferId });
await dispatch(getCategories());
@@ -193,7 +198,7 @@ export function deleteGroup(id, transferId) {
};
}
-export function getPayees() {
+export function getPayees(): ActionResult {
return async function (dispatch) {
let payees = await send('payees-get');
dispatch({
@@ -204,7 +209,7 @@ export function getPayees() {
};
}
-export function initiallyLoadPayees() {
+export function initiallyLoadPayees(): ActionResult {
return async function (dispatch, getState) {
if (getState().queries.payees.length === 0) {
return dispatch(getPayees());
@@ -212,13 +217,13 @@ export function initiallyLoadPayees() {
};
}
-export function createPayee(name) {
+export function createPayee(name: string): ActionResult {
return async dispatch => {
return send('payee-create', { name: name.trim() });
};
}
-export function getAccounts() {
+export function getAccounts(): ActionResult {
return async function (dispatch) {
const accounts = await send('accounts-get');
dispatch({ type: constants.LOAD_ACCOUNTS, accounts });
@@ -226,14 +231,14 @@ export function getAccounts() {
};
}
-export function updateAccount(account) {
+export function updateAccount(account): ActionResult {
return async function (dispatch) {
dispatch({ type: constants.UPDATE_ACCOUNT, account });
await send('account-update', account);
};
}
-export function createAccount(name, balance, offBudget) {
+export function createAccount(name, balance, offBudget): ActionResult {
return async function (dispatch) {
let id = await send('account-create', { name, balance, offBudget });
await dispatch(getAccounts());
@@ -242,7 +247,7 @@ export function createAccount(name, balance, offBudget) {
};
}
-export function openAccountCloseModal(accountId) {
+export function openAccountCloseModal(accountId): ActionResult {
return async function (dispatch, getState) {
const { balance, numTransactions } = await send('account-properties', {
id: accountId,
@@ -261,7 +266,12 @@ export function openAccountCloseModal(accountId) {
};
}
-export function closeAccount(accountId, transferAccountId, categoryId, forced) {
+export function closeAccount(
+ accountId,
+ transferAccountId,
+ categoryId,
+ forced,
+): ActionResult {
return async function (dispatch) {
await send('account-close', {
id: accountId,
@@ -273,14 +283,14 @@ export function closeAccount(accountId, transferAccountId, categoryId, forced) {
};
}
-export function reopenAccount(accountId) {
+export function reopenAccount(accountId): ActionResult {
return async function (dispatch) {
await send('account-reopen', { id: accountId });
dispatch(getAccounts());
};
}
-export function forceCloseAccount(accountId) {
+export function forceCloseAccount(accountId): ActionResult {
return closeAccount(accountId, null, null, true);
}
@@ -288,7 +298,7 @@ let _undo = throttle(() => send('undo'), 100);
let _redo = throttle(() => send('redo'), 100);
let _undoEnabled = true;
-export function setUndoEnabled(flag) {
+export function setUndoEnabled(flag: boolean) {
_undoEnabled = flag;
}
diff --git a/packages/loot-core/src/client/actions/types.d.ts b/packages/loot-core/src/client/actions/types.d.ts
new file mode 100644
index 0000000000..86aff269f1
--- /dev/null
+++ b/packages/loot-core/src/client/actions/types.d.ts
@@ -0,0 +1,7 @@
+import type { ThunkDispatch } from 'redux-thunk';
+
+import type { Action, State } from '../state-types';
+
+export type ActionResult = Parameters<
+ ThunkDispatch<State, Record<string, never>, Action>
+>[0];
diff --git a/packages/loot-core/src/client/constants.ts b/packages/loot-core/src/client/constants.ts
index 1fbe8a11ae..95a7e8fa9d 100644
--- a/packages/loot-core/src/client/constants.ts
+++ b/packages/loot-core/src/client/constants.ts
@@ -1,4 +1,3 @@
-export const LOAD_TRANSACTIONS = 'LOAD_TRANSACTIONS';
export const SET_NEW_TRANSACTIONS = 'SET_NEW_TRANSACTIONS';
export const UPDATE_NEW_TRANSACTIONS = 'UPDATE_NEW_TRANSACTIONS';
export const SET_LAST_TRANSACTION = 'SET_LAST_TRANSACTION';
@@ -6,25 +5,17 @@ export const MARK_ACCOUNT_READ = 'MARK_ACCOUNT_READ';
export const LOAD_ACCOUNTS = 'LOAD_ACCOUNTS';
export const UPDATE_ACCOUNT = 'UPDATE_ACCOUNT';
export const LOAD_CATEGORIES = 'LOAD_CATEGORIES';
-export const ADD_CATEGORY = 'ADD_CATEGORY';
-export const DELETE_CATEGORY = 'DELETE_CATEGORY';
export const LOAD_PAYEES = 'LOAD_PAYEES';
-export const LOAD_BANKS = 'LOAD_BANKS';
-export const SET_PROFILE = 'SET_PROFILE';
export const SET_PREFS = 'SET_PREFS';
export const MERGE_LOCAL_PREFS = 'MERGE_LOCAL_PREFS';
export const MERGE_GLOBAL_PREFS = 'MERGE_GLOBAL_PREFS';
export const SET_BUDGETS = 'SET_BUDGETS';
export const SET_REMOTE_FILES = 'SET_REMOTE_FILES';
export const SET_ALL_FILES = 'SET_ALL_FILES';
-export const SET_AVAILABLE_IMPORTS = 'SET_AVAILABLE_IMPORTS';
export const CLOSE_BUDGET = 'CLOSE_BUDGET';
export const SET_APP_STATE = 'SET_APP_STATE';
-export const DEBUG_CELL = 'DEBUG_CELL';
export const PUSH_MODAL = 'PUSH_MODAL';
export const REPLACE_MODAL = 'REPLACE_MODAL';
-export const HIDE_MODALS = 'HIDE_MODALS';
-export const SHOW_MODALS = 'SHOW_MODALS';
export const CLOSE_MODAL = 'CLOSE_MODAL';
export const POP_MODAL = 'POP_MODAL';
export const ADD_NOTIFICATION = 'ADD_NOTIFICATION';
diff --git a/packages/loot-core/src/client/reducers/account.ts b/packages/loot-core/src/client/reducers/account.ts
index 3fb71e659c..dc78b508f8 100644
--- a/packages/loot-core/src/client/reducers/account.ts
+++ b/packages/loot-core/src/client/reducers/account.ts
@@ -1,18 +1,17 @@
import * as constants from '../constants';
+import type { Action } from '../state-types';
+import type { AccountState } from '../state-types/account';
-const initialState = {
- banks: [],
+const initialState: AccountState = {
failedAccounts: new Map(),
accountsSyncing: null,
};
-export default function update(state = initialState, action) {
+export default function update(
+ state = initialState,
+ action: Action,
+): AccountState {
switch (action.type) {
- case constants.LOAD_BANKS:
- return {
- ...state,
- banks: action.banks,
- };
case constants.SET_ACCOUNTS_SYNCING:
return {
...state,
diff --git a/packages/loot-core/src/client/reducers/app.ts b/packages/loot-core/src/client/reducers/app.ts
index 6fe4dc3685..b85e12022c 100644
--- a/packages/loot-core/src/client/reducers/app.ts
+++ b/packages/loot-core/src/client/reducers/app.ts
@@ -1,6 +1,8 @@
import * as constants from '../constants';
+import type { Action } from '../state-types';
+import type { AppState } from '../state-types/app';
-export const initialState = {
+export const initialState: AppState = {
loadingText: null,
updateInfo: null,
showUpdateNotification: true,
@@ -9,7 +11,7 @@ export const initialState = {
lastSplitState: { current: null },
};
-export default function update(state = initialState, action) {
+export default function update(state = initialState, action: Action): AppState {
switch (action.type) {
case constants.SET_APP_STATE:
return {
diff --git a/packages/loot-core/src/client/reducers/budgets.ts b/packages/loot-core/src/client/reducers/budgets.ts
index ddd75630c7..e37484b88a 100644
--- a/packages/loot-core/src/client/reducers/budgets.ts
+++ b/packages/loot-core/src/client/reducers/budgets.ts
@@ -1,12 +1,19 @@
+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) {
+function sortFiles(arr: File[]) {
arr.sort((x, y) => {
let name1 = x.name.toLowerCase();
let name2 = y.name.toLowerCase();
let i = name1 < name2 ? -1 : name1 > name2 ? 1 : 0;
if (i === 0) {
- i = x.id < y.id ? -1 : x.id > y.id ? 1 : 0;
+ let xId = x.state === 'remote' ? x.cloudFileId : x.id;
+ let yId = x.state === 'remote' ? x.cloudFileId : x.id;
+ i = xId < yId ? -1 : xId > yId ? 1 : 0;
}
return i;
});
@@ -20,18 +27,28 @@ function sortFiles(arr) {
// 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, remoteFiles) {
+function reconcileFiles(
+ localFiles: Budget[],
+ remoteFiles: RemoteFile[] | null,
+): File[] {
+ console.log({ localFiles, remoteFiles });
let reconciled = new Set();
- let files = localFiles.map(localFile => {
- if (localFile.cloudFileId) {
+ let files = localFiles.map((localFile): File & { deleted: boolean } => {
+ let { 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, state: 'unknown' };
+ return {
+ ...localFile,
+ cloudFileId,
+ groupId,
+ deleted: false,
+ state: 'unknown',
+ };
}
let remote = remoteFiles.find(f => localFile.cloudFileId === f.fileId);
@@ -42,6 +59,8 @@ function reconcileFiles(localFiles, remoteFiles) {
if (remote.groupId === localFile.groupId) {
return {
...localFile,
+ cloudFileId,
+ groupId,
name: remote.name,
deleted: remote.deleted,
encryptKeyId: remote.encryptKeyId,
@@ -51,6 +70,8 @@ function reconcileFiles(localFiles, remoteFiles) {
} else {
return {
...localFile,
+ cloudFileId,
+ groupId,
name: remote.name,
deleted: remote.deleted,
encryptKeyId: remote.encryptKeyId,
@@ -59,10 +80,16 @@ function reconcileFiles(localFiles, remoteFiles) {
};
}
} else {
- return { ...localFile, state: 'broken' };
+ return {
+ ...localFile,
+ cloudFileId,
+ groupId,
+ deleted: false,
+ state: 'broken',
+ };
}
} else {
- return { ...localFile, state: 'local' };
+ return { ...localFile, deleted: false, state: 'local' };
}
});
@@ -93,14 +120,16 @@ function reconcileFiles(localFiles, remoteFiles) {
.concat(sorted.filter(f => f.state === 'broken'));
}
-const initialState = {
+const initialState: BudgetsState = {
budgets: [],
- availableImports: [],
remoteFiles: null,
allFiles: null,
};
-export default function update(state = initialState, action) {
+export default function update(
+ state = initialState,
+ action: Action,
+): BudgetsState {
switch (action.type) {
case constants.SET_BUDGETS:
return {
@@ -117,15 +146,10 @@ export default function update(state = initialState, action) {
case constants.SET_ALL_FILES:
return {
...state,
- budgets: action.budgetes,
+ budgets: action.budgets,
remoteFiles: action.remoteFiles,
allFiles: reconcileFiles(action.budgets, action.remoteFiles),
};
- case constants.SET_AVAILABLE_IMPORTS:
- return {
- ...state,
- availableImports: action.imports,
- };
case constants.SIGN_OUT:
// If the user logs out, make sure to reset all the files
return { ...state, allFiles: null };
diff --git a/packages/loot-core/src/client/reducers/debug.ts b/packages/loot-core/src/client/reducers/debug.ts
deleted file mode 100644
index 24d461269f..0000000000
--- a/packages/loot-core/src/client/reducers/debug.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import * as constants from '../constants';
-
-const initialState = {
- selectedCell: null,
-};
-
-function update(state = initialState, action) {
- switch (action.type) {
- case constants.DEBUG_CELL:
- return {
- ...state,
- selectedCell: action.sheet
- ? { sheet: action.sheet, name: action.name }
- : null,
- };
- default:
- }
- return state;
-}
-
-export default update;
diff --git a/packages/loot-core/src/client/reducers/index.ts b/packages/loot-core/src/client/reducers/index.ts
index 17d0f75293..77c5c76518 100644
--- a/packages/loot-core/src/client/reducers/index.ts
+++ b/packages/loot-core/src/client/reducers/index.ts
@@ -1,11 +1,9 @@
import account from './account';
import app from './app';
import budgets from './budgets';
-import debug from './debug';
import modals from './modals';
import notifications from './notifications';
import prefs from './prefs';
-import profile from './profile';
import queries from './queries';
import user from './user';
@@ -13,8 +11,6 @@ const reducers = {
app,
queries,
account,
- debug,
- profile,
prefs,
modals,
notifications,
diff --git a/packages/loot-core/src/client/reducers/modals.ts b/packages/loot-core/src/client/reducers/modals.ts
index 0bdd2246d5..2c40d09144 100644
--- a/packages/loot-core/src/client/reducers/modals.ts
+++ b/packages/loot-core/src/client/reducers/modals.ts
@@ -1,11 +1,13 @@
import * as constants from '../constants';
+import type { Action } from '../state-types';
+import type { ModalsState } from '../state-types/modals';
-const initialState = {
+const initialState: ModalsState = {
modalStack: [],
isHidden: false,
};
-function update(state = initialState, action) {
+function update(state = initialState, action: Action): ModalsState {
switch (action.type) {
case constants.PUSH_MODAL:
return {
@@ -24,10 +26,6 @@ function update(state = initialState, action) {
return { ...state, modalStack: state.modalStack.slice(0, -1) };
case constants.CLOSE_MODAL:
return { ...state, modalStack: [] };
- case constants.HIDE_MODALS:
- return { ...state, isHidden: true };
- case constants.SHOW_MODALS:
- return { ...state, isHidden: false };
case constants.SET_APP_STATE:
if ('loadingText' in action.state) {
return {
diff --git a/packages/loot-core/src/client/reducers/notifications.ts b/packages/loot-core/src/client/reducers/notifications.ts
index 3bacabe343..7c722d14c3 100644
--- a/packages/loot-core/src/client/reducers/notifications.ts
+++ b/packages/loot-core/src/client/reducers/notifications.ts
@@ -1,10 +1,15 @@
import * as constants from '../constants';
+import type { Action } from '../state-types';
+import type { NotificationsState } from '../state-types/notifications';
const initialState = {
notifications: [],
};
-export default function update(state = initialState, action) {
+export default function update(
+ state = initialState,
+ action: Action,
+): NotificationsState {
switch (action.type) {
case constants.ADD_NOTIFICATION:
if (state.notifications.find(n => n.id === action.notification.id)) {
diff --git a/packages/loot-core/src/client/reducers/prefs.ts b/packages/loot-core/src/client/reducers/prefs.ts
index a115d68f83..45f95090fe 100644
--- a/packages/loot-core/src/client/reducers/prefs.ts
+++ b/packages/loot-core/src/client/reducers/prefs.ts
@@ -1,12 +1,17 @@
import { setNumberFormat } from '../../shared/util';
import * as constants from '../constants';
+import type { Action } from '../state-types';
+import type { PrefsState } from '../state-types/prefs';
-const initialState = {
+const initialState: PrefsState = {
local: null,
global: null,
};
-export default function update(state = initialState, action) {
+export default function update(
+ state = initialState,
+ action: Action,
+): PrefsState {
switch (action.type) {
case constants.SET_PREFS:
if (action.prefs) {
diff --git a/packages/loot-core/src/client/reducers/profile.ts b/packages/loot-core/src/client/reducers/profile.ts
deleted file mode 100644
index 740c8cb31a..0000000000
--- a/packages/loot-core/src/client/reducers/profile.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import * as constants from '../constants';
-
-const initialState = {};
-
-export default function update(state = initialState, action) {
- switch (action.type) {
- case constants.SET_PROFILE:
- return {
- ...state,
- ...action.profile,
- };
- default:
- }
- return state;
-}
diff --git a/packages/loot-core/src/client/reducers/queries.ts b/packages/loot-core/src/client/reducers/queries.ts
index 96fa91b71a..8cd82fb88a 100644
--- a/packages/loot-core/src/client/reducers/queries.ts
+++ b/packages/loot-core/src/client/reducers/queries.ts
@@ -2,8 +2,10 @@ import memoizeOne from 'memoize-one';
import { groupById } from '../../shared/util';
import * as constants from '../constants';
+import type { Action } from '../state-types';
+import type { QueriesState } from '../state-types/queries';
-const initialState = {
+const initialState: QueriesState = {
newTransactions: [],
matchedTransactions: [],
lastTransaction: null,
@@ -17,7 +19,10 @@ const initialState = {
earliestTransaction: null,
};
-export default function update(state = initialState, action) {
+export default function update(
+ state = initialState,
+ action: Action,
+): QueriesState {
switch (action.type) {
case constants.SET_NEW_TRANSACTIONS:
return {
@@ -57,7 +62,9 @@ export default function update(state = initialState, action) {
return {
...state,
accounts: state.accounts.map(account => {
+ // @ts-expect-error Not typed yet
if (account.id === action.account.id) {
+ // @ts-expect-error Not typed yet
return { ...account, ...action.account };
}
return account;
@@ -74,37 +81,6 @@ export default function update(state = initialState, action) {
...state,
payees: action.payees,
};
- case constants.ADD_CATEGORY: {
- let category = { id: 'temp', name: action.name };
-
- return {
- ...state,
- categories: {
- grouped: state.categories.grouped.map(group => {
- if (group.id === action.groupId) {
- return { ...group, categories: [category, ...group.categories] };
- }
- return group;
- }),
- list: [category, ...state.categories.list],
- },
- };
- }
- case constants.DELETE_CATEGORY: {
- return {
- ...state,
- categories: {
- grouped: state.categories.grouped.map(group => {
- return {
- ...group,
- categories: group.categories.filter(cat => cat.id !== action.id),
- };
- }),
- list: state.categories.list.filter(cat => cat.id !== action.id),
- },
- };
- }
-
default:
}
return state;
diff --git a/packages/loot-core/src/client/reducers/user.ts b/packages/loot-core/src/client/reducers/user.ts
index 5af8ed05d1..d9ec3de90f 100644
--- a/packages/loot-core/src/client/reducers/user.ts
+++ b/packages/loot-core/src/client/reducers/user.ts
@@ -1,10 +1,14 @@
import * as constants from '../constants';
+import type { UserActions, UserState } from '../state-types/user';
-const initialState = {
+const initialState: UserState = {
data: null,
};
-export default function update(state = initialState, action) {
+export default function update(
+ state = initialState,
+ action: UserActions,
+): UserState {
switch (action.type) {
case constants.GET_USER_DATA:
return { ...state, data: action.data };
diff --git a/packages/loot-core/src/client/shared-listeners.ts b/packages/loot-core/src/client/shared-listeners.ts
index 88566f1fe3..a46f1490c9 100644
--- a/packages/loot-core/src/client/shared-listeners.ts
+++ b/packages/loot-core/src/client/shared-listeners.ts
@@ -1,5 +1,7 @@
import { listen, send } from '../platform/client/fetch';
+import type { Notification } from './state-types/notifications';
+
export function listenForSyncEvent(actions, store) {
let attemptedSyncRepair = false;
@@ -43,7 +45,7 @@ export function listenForSyncEvent(actions, store) {
actions.getAccounts();
}
} else if (type === 'error') {
- let notif = null;
+ let notif: Notification | null = null;
let learnMore =
'[Learn more](https://actualbudget.org/docs/getting-started/sync/#debugging-sync-issues)';
const githubIssueLink =
diff --git a/packages/loot-core/src/client/state-types/account.d.ts b/packages/loot-core/src/client/state-types/account.d.ts
new file mode 100644
index 0000000000..2b119bc271
--- /dev/null
+++ b/packages/loot-core/src/client/state-types/account.d.ts
@@ -0,0 +1,39 @@
+import type * as constants from '../constants';
+
+export type AccountState = {
+ failedAccounts: Map<string, { type: string; code: string }>;
+ accountsSyncing: string | null;
+};
+
+export type SetAccountsSyncingAction = {
+ type: typeof constants.SET_ACCOUNTS_SYNCING;
+ name: string | null;
+};
+
+export type AccountSyncStatusAction = {
+ type: typeof constants.ACCOUNT_SYNC_STATUS;
+ id: string;
+} & (
+ | {
+ failed: false;
+ }
+ | {
+ failed: true;
+ errorType: string;
+ errorCode: string;
+ }
+);
+
+export type AccountSyncFailuresAction = {
+ type: typeof constants.ACCOUNT_SYNC_FAILURES;
+ syncErrors: Array<{
+ id: string;
+ type: string;
+ code: string;
+ }>;
+};
+
+export type AccountActions =
+ | SetAccountsSyncingAction
+ | AccountSyncStatusAction
+ | AccountSyncFailuresAction;
diff --git a/packages/loot-core/src/client/state-types/app.d.ts b/packages/loot-core/src/client/state-types/app.d.ts
new file mode 100644
index 0000000000..7420aa7251
--- /dev/null
+++ b/packages/loot-core/src/client/state-types/app.d.ts
@@ -0,0 +1,37 @@
+import type { UndoState } from '../../server/undo';
+import type * as constants from '../constants';
+
+export type SplitState = { ids: Set<string>; mode: 'collapse' | 'expand' };
+
+export type AppState = {
+ loadingText: string | null;
+ updateInfo: {
+ version: string;
+ releaseDate: string;
+ releaseNotes: string;
+ } | null;
+ showUpdateNotification: boolean;
+ managerHasInitialized: boolean;
+ lastUndoState: { current: UndoState | null };
+ lastSplitState: { current: SplitState | null };
+};
+
+export type SetAppStateAction = {
+ type: typeof constants.SET_APP_STATE;
+ state: Partial<AppState>;
+};
+
+export type SetLastUndoStateAction = {
+ type: typeof constants.SET_LAST_UNDO_STATE;
+ undoState: UndoState | null;
+};
+
+export type SetLastSplitStateAction = {
+ type: typeof constants.SET_LAST_SPLIT_STATE;
+ splitState: SplitState | null;
+};
+
+export type AppActions =
+ | SetAppStateAction
+ | SetLastUndoStateAction
+ | SetLastSplitStateAction;
diff --git a/packages/loot-core/src/client/state-types/budgets.d.ts b/packages/loot-core/src/client/state-types/budgets.d.ts
new file mode 100644
index 0000000000..caa53f81de
--- /dev/null
+++ b/packages/loot-core/src/client/state-types/budgets.d.ts
@@ -0,0 +1,36 @@
+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
new file mode 100644
index 0000000000..de285e9f80
--- /dev/null
+++ b/packages/loot-core/src/client/state-types/index.d.ts
@@ -0,0 +1,41 @@
+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';
+import type { NotificationsActions, NotificationsState } from './notifications';
+import type { PrefsActions, PrefsState } from './prefs';
+import type { QueriesActions, QueriesState } from './queries';
+import type { UserActions, UserState } from './user';
+
+export type CloseBudgetAction = {
+ type: typeof constants.CLOSE_BUDGET;
+};
+
+export type Action =
+ | AccountActions
+ | AppActions
+ | BudgetsActions
+ | ModalsActions
+ | NotificationsActions
+ | PrefsActions
+ | QueriesActions
+ | UserActions
+ | CloseBudgetAction;
+
+export type State = {
+ account: AccountState;
+ app: AppState;
+ budgets: BudgetsState;
+ modals: ModalsState;
+ notifications: NotificationsState;
+ prefs: PrefsState;
+ queries: QueriesState;
+ user: UserState;
+};
+
+declare module 'react-redux' {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-empty-interface
+ export interface DefaultRootState extends State {}
+}
diff --git a/packages/loot-core/src/client/state-types/modals.d.ts b/packages/loot-core/src/client/state-types/modals.d.ts
new file mode 100644
index 0000000000..c3c9bbe4c1
--- /dev/null
+++ b/packages/loot-core/src/client/state-types/modals.d.ts
@@ -0,0 +1,38 @@
+import type * as constants from '../constants';
+
+// TODO: type this more throughly
+type Modal = {
+ name: string;
+ options: unknown;
+};
+
+export type PushModalAction = {
+ type: typeof constants.PUSH_MODAL;
+ name: string;
+ options: unknown;
+};
+
+export type ReplaceModalAction = {
+ type: typeof constants.REPLACE_MODAL;
+ name: string;
+ options: unknown;
+};
+
+export type PopModalAction = {
+ type: typeof constants.POP_MODAL;
+};
+
+export type CloseModalAction = {
+ type: typeof constants.CLOSE_MODAL;
+};
+
+export type ModalsActions =
+ | PushModalAction
+ | ReplaceModalAction
+ | PopModalAction
+ | CloseModalAction;
+
+export type ModalsState = {
+ modalStack: Modal[];
+ isHidden: boolean;
+};
diff --git a/packages/loot-core/src/client/state-types/notifications.d.ts b/packages/loot-core/src/client/state-types/notifications.d.ts
new file mode 100644
index 0000000000..236f714059
--- /dev/null
+++ b/packages/loot-core/src/client/state-types/notifications.d.ts
@@ -0,0 +1,38 @@
+import type * as constants from '../constants';
+
+export type Notification = {
+ id?: string;
+ // 'warning' is unhandled??
+ type?: 'message' | 'error' | 'warning';
+ pre?: string;
+ title?: string;
+ message: string;
+ sticky?: boolean;
+ timeout?: number;
+ button?: {
+ title: string;
+ action: () => void | Promise<void>;
+ };
+ messageActions?: Record<string, () => void>;
+ onClose?: () => void;
+ internal?: unknown;
+};
+type NotificationWithId = Notification & { id: string };
+
+export type NotificationsState = {
+ notifications: NotificationWithId[];
+};
+
+type AddNotificationAction = {
+ type: typeof constants.ADD_NOTIFICATION;
+ notification: NotificationWithId;
+};
+
+type RemoveNotificationAction = {
+ type: typeof constants.REMOVE_NOTIFICATION;
+ id: string;
+};
+
+export type NotificationsActions =
+ | AddNotificationAction
+ | RemoveNotificationAction;
diff --git a/packages/loot-core/src/client/state-types/prefs.d.ts b/packages/loot-core/src/client/state-types/prefs.d.ts
new file mode 100644
index 0000000000..660b468260
--- /dev/null
+++ b/packages/loot-core/src/client/state-types/prefs.d.ts
@@ -0,0 +1,74 @@
+import { type numberFormats } from '../../shared/util';
+import type * as constants from '../constants';
+
+export type FeatureFlag = 'reportBudget' | 'goalTemplatesEnabled';
+
+type NullableValues<T> = { [K in keyof T]: T[K] | null };
+
+export type LocalPrefs = NullableValues<
+ {
+ firstDayOfWeekIdx: `${0 | 1 | 2 | 3 | 4 | 5 | 6}`;
+ dateFormat: string;
+ numberFormat: (typeof numberFormats)[number]['value'];
+ hideFraction: boolean;
+ hideClosedAccounts: boolean;
+ hideMobileMessage: boolean;
+ budgetName: string;
+ 'ui.showClosedAccounts': boolean;
+ 'expand-splits': boolean;
+ [key: `show-extra-balances-${string}`]: boolean;
+ [key: `hide-cleared-${string}`]: boolean;
+ 'budget.collapsed': boolean;
+ 'budget.summaryCollapsed': boolean;
+ 'budget.showHiddenCategories': boolean;
+ // TODO: pull from src/components/modals/ImportTransactions.js
+ [key: `parse-date-${string}-${'csv' | 'qif'}`]: string;
+ [key: `csv-mappings-${string}`]: string;
+ [key: `csv-delimiter-${string}`]: ',' | ';';
+ [key: `flip-amount-${string}-${'csv' | 'qif'}`]: boolean;
+ 'flags.updateNotificationShownForVersion': string;
+ id: string;
+ isCached: boolean;
+ lastUploaded: string;
+ cloudFileId: string;
+ groupId: string;
+ budgetType: 'report' | 'rollover';
+ encryptKeyId: string;
+ lastSyncedTimestamp: string;
+ userId: string;
+ resetClock: boolean;
+ lastScheduleRun: string;
+ } & Record<`flags.${FeatureFlag}`, boolean>
+>;
+
+export type GlobalPrefs = NullableValues<{
+ floatingSidebar: boolean;
+ maxMonths: number;
+ documentDir: string; // Electron only
+}>;
+
+export type PrefsState = {
+ local: LocalPrefs | null;
+ global: GlobalPrefs | null;
+};
+
+export type SetPrefsAction = {
+ type: typeof constants.SET_PREFS;
+ prefs: LocalPrefs;
+ globalPrefs: GlobalPrefs;
+};
+
+export type MergeLocalPrefsAction = {
+ type: typeof constants.MERGE_LOCAL_PREFS;
+ prefs: Partial<LocalPrefs>;
+};
+
+export type MergeGlobalPrefsAction = {
+ type: typeof constants.MERGE_GLOBAL_PREFS;
+ globalPrefs: Partial<GlobalPrefs>;
+};
+
+export type PrefsActions =
+ | SetPrefsAction
+ | MergeLocalPrefsAction
+ | MergeGlobalPrefsAction;
diff --git a/packages/loot-core/src/client/state-types/queries.d.ts b/packages/loot-core/src/client/state-types/queries.d.ts
new file mode 100644
index 0000000000..bad2b1904e
--- /dev/null
+++ b/packages/loot-core/src/client/state-types/queries.d.ts
@@ -0,0 +1,65 @@
+import type { Handlers } from '../../types/handlers';
+import type * as constants from '../constants';
+
+export type QueriesState = {
+ newTransactions: unknown[];
+ matchedTransactions: unknown[];
+ lastTransaction: unknown | null;
+ updatedAccounts: string[];
+ accounts: AccountEntity[];
+ categories: Awaited<ReturnType<Handlers['get-categories']>>;
+ payees: unknown[];
+ earliestTransaction: unknown | null;
+};
+
+type SetNewTransactionsAction = {
+ type: typeof constants.SET_NEW_TRANSACTIONS;
+ newTransactions?: unknown[];
+ matchedTransactions?: unknown[];
+ updatedAccounts?: string[];
+};
+
+type UpdateNewTransactionsAction = {
+ type: typeof constants.UPDATE_NEW_TRANSACTIONS;
+ changedId: string;
+};
+
+type SetLastTransactionAction = {
+ type: typeof constants.SET_LAST_TRANSACTION;
+ transaction: unknown;
+};
+
+type MarkAccountReadAction = {
+ type: typeof constants.MARK_ACCOUNT_READ;
+ accountId: string;
+};
+
+type LoadAccountsAction = {
+ type: typeof constants.LOAD_ACCOUNTS;
+ accounts: AccountEntity[];
+};
+
+type UpdateAccountAction = {
+ type: typeof constants.UPDATE_ACCOUNT;
+ account: unknown;
+};
+
+type LoadCategoriesAction = {
+ type: typeof constants.LOAD_CATEGORIES;
+ categories: State['categories'];
+};
+
+type LoadPayeesAction = {
+ type: typeof constants.LOAD_PAYEES;
+ payees: unknown[];
+};
+
+export type QueriesActions =
+ | SetNewTransactionsAction
+ | UpdateNewTransactionsAction
+ | SetLastTransactionAction
+ | MarkAccountReadAction
+ | LoadAccountsAction
+ | UpdateAccountAction
+ | LoadCategoriesAction
+ | LoadPayeesAction;
diff --git a/packages/loot-core/src/client/state-types/user.d.ts b/packages/loot-core/src/client/state-types/user.d.ts
new file mode 100644
index 0000000000..289aadaf95
--- /dev/null
+++ b/packages/loot-core/src/client/state-types/user.d.ts
@@ -0,0 +1,13 @@
+import type { Handlers } from '../../types/handlers';
+import type * as constants from '../constants';
+
+export type UserState = {
+ data: Awaited<ReturnType<Handlers['subscribe-get-user']>>;
+};
+
+export type GetUserDataAction = {
+ type: typeof constants.GET_USER_DATA;
+ data: State['data'];
+};
+
+export type UserActions = GetUserDataAction;
diff --git a/packages/loot-core/src/mocks/budget.ts b/packages/loot-core/src/mocks/budget.ts
index 56f7c894df..ccfb3e6085 100644
--- a/packages/loot-core/src/mocks/budget.ts
+++ b/packages/loot-core/src/mocks/budget.ts
@@ -10,7 +10,6 @@ import { batchMessages, setSyncingMode } from '../server/sync';
import * as monthUtils from '../shared/months';
import q from '../shared/query';
import type {
- AccountEntity,
CategoryGroupEntity,
PayeeEntity,
TransactionEntity,
@@ -563,7 +562,7 @@ export async function createTestBudget(handlers) {
await db.runQuery('DELETE FROM categories;');
await db.runQuery('DELETE FROM category_groups');
- let accounts: AccountEntity[] = [
+ let accounts: { name: string; offBudget?: 1; id?: string }[] = [
{ name: 'Bank of America' },
{ name: 'Ally Savings' },
{ name: 'Capital One Checking' },
diff --git a/packages/loot-core/src/server/accounts/sync.ts b/packages/loot-core/src/server/accounts/sync.ts
index 4b72d0f638..4e97ad717e 100644
--- a/packages/loot-core/src/server/accounts/sync.ts
+++ b/packages/loot-core/src/server/accounts/sync.ts
@@ -22,7 +22,7 @@ import { batchUpdateTransactions } from './transactions';
// Plaid article about API options:
// https://support.plaid.com/customer/en/portal/articles/2612155-transactions-returned-per-request
-function BankSyncError(type, code) {
+function BankSyncError(type: string, code: string) {
return { type: 'BankSyncError', category: type, code };
}
diff --git a/packages/loot-core/src/server/budget/cleanup-template.ts b/packages/loot-core/src/server/budget/cleanup-template.ts
index 95045d6c57..48e520c0e1 100644
--- a/packages/loot-core/src/server/budget/cleanup-template.ts
+++ b/packages/loot-core/src/server/budget/cleanup-template.ts
@@ -1,14 +1,15 @@
+import { Notification } from '../../client/state-types/notifications';
import * as monthUtils from '../../shared/months';
import * as db from '../db';
import { setBudget, getSheetValue } from './actions';
import { parse } from './cleanup-template.pegjs';
-export function cleanupTemplate({ month }) {
+export function cleanupTemplate({ month }: { month: string }) {
return processCleanup(month);
}
-async function processCleanup(month) {
+async function processCleanup(month: string): Promise<Notification> {
let num_sources = 0;
let num_sinks = 0;
let total_weight = 0;
diff --git a/packages/loot-core/src/server/budget/goaltemplates.ts b/packages/loot-core/src/server/budget/goaltemplates.ts
index d746e6f365..2be3544373 100644
--- a/packages/loot-core/src/server/budget/goaltemplates.ts
+++ b/packages/loot-core/src/server/budget/goaltemplates.ts
@@ -1,3 +1,4 @@
+import { Notification } from '../../client/state-types/notifications';
import * as monthUtils from '../../shared/months';
import {
extractScheduleConds,
@@ -34,7 +35,10 @@ function checkScheduleTemplates(template) {
return { lowPriority, errorNotice };
}
-async function processTemplate(month, force) {
+async function processTemplate(
+ month: string,
+ force: boolean,
+): Promise<Notification> {
let num_applied = 0;
let errors = [];
let category_templates = await getCategoryTemplates();
@@ -645,7 +649,7 @@ async function applyCategoryTemplate(
}
}
-async function checkTemplates() {
+async function checkTemplates(): Promise<Notification> {
let category_templates = await getCategoryTemplates();
let errors = [];
diff --git a/packages/loot-core/src/server/budget/types/handlers.d.ts b/packages/loot-core/src/server/budget/types/handlers.d.ts
index d779784048..8def30dd25 100644
--- a/packages/loot-core/src/server/budget/types/handlers.d.ts
+++ b/packages/loot-core/src/server/budget/types/handlers.d.ts
@@ -1,3 +1,5 @@
+import type { Notification } from '../../../client/state-types/notifications';
+
export interface BudgetHandlers {
'budget/budget-amount': (arg: {
category: string /* category id */;
@@ -11,13 +13,19 @@ export interface BudgetHandlers {
'budget/set-3month-avg': (...args: unknown[]) => Promise<unknown>;
- 'budget/check-templates': (...args: unknown[]) => Promise<unknown>;
+ 'budget/check-templates': () => Promise<Notification>;
- 'budget/apply-goal-template': (...args: unknown[]) => Promise<unknown>;
+ 'budget/apply-goal-template': (arg: {
+ month: string;
+ }) => Promise<Notification>;
- 'budget/overwrite-goal-template': (...args: unknown[]) => Promise<unknown>;
+ 'budget/overwrite-goal-template': (arg: {
+ month: string;
+ }) => Promise<Notification>;
- 'budget/cleanup-goal-template': (...args: unknown[]) => Promise<unknown>;
+ 'budget/cleanup-goal-template': (arg: {
+ month: string;
+ }) => Promise<Notification>;
'budget/hold-for-next-month': (...args: unknown[]) => Promise<unknown>;
diff --git a/packages/loot-core/src/server/undo.ts b/packages/loot-core/src/server/undo.ts
index 4fffa90490..a53ca60db1 100644
--- a/packages/loot-core/src/server/undo.ts
+++ b/packages/loot-core/src/server/undo.ts
@@ -10,7 +10,7 @@ import { Message, sendMessages } from './sync';
type MarkerMessage = { type: 'marker'; meta?: unknown };
type MessagesMessage = {
type: 'messages';
- messages: unknown[];
+ messages: Message[];
meta?: unknown;
oldData;
undoTag;
@@ -21,6 +21,13 @@ let MESSAGE_HISTORY: Array<MarkerMessage | MessagesMessage> = [
let CURSOR = 0;
let HISTORY_SIZE = 20;
+export type UndoState = {
+ messages: Message[];
+ meta?: unknown;
+ tables: string[];
+ undoTag: string;
+};
+
function trimHistory() {
MESSAGE_HISTORY = MESSAGE_HISTORY.slice(0, CURSOR + 1);
diff --git a/packages/loot-core/src/shared/accounts.ts b/packages/loot-core/src/shared/accounts.ts
deleted file mode 100644
index cb74510ffe..0000000000
--- a/packages/loot-core/src/shared/accounts.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-export function determineOffBudget(plaidAccountType) {
- switch (plaidAccountType) {
- case 'brokerage':
- case 'investment':
- case 'loan':
- case 'other':
- return true;
- case 'credit':
- case 'depository':
- default:
- return false;
- }
-}
diff --git a/packages/loot-core/src/shared/util.ts b/packages/loot-core/src/shared/util.ts
index f1dec4b333..e28d1d4c8a 100644
--- a/packages/loot-core/src/shared/util.ts
+++ b/packages/loot-core/src/shared/util.ts
@@ -188,7 +188,7 @@ export let numberFormats = [
{ value: 'dot-comma', label: '1.000,33', labelNoFraction: '1.000' },
{ value: 'space-comma', label: '1 000,33', labelNoFraction: '1 000' },
{ value: 'space-dot', label: '1 000.33', labelNoFraction: '1 000' },
-];
+] as const;
let numberFormat: {
value: string | null;
diff --git a/packages/loot-core/src/types/budget.d.ts b/packages/loot-core/src/types/budget.d.ts
new file mode 100644
index 0000000000..f77d9acf5c
--- /dev/null
+++ b/packages/loot-core/src/types/budget.d.ts
@@ -0,0 +1,6 @@
+export type Budget = {
+ id: string;
+ cloudFileId?: string;
+ groupId?: string;
+ name: string;
+};
diff --git a/packages/loot-core/src/types/file.d.ts b/packages/loot-core/src/types/file.d.ts
new file mode 100644
index 0000000000..394adee071
--- /dev/null
+++ b/packages/loot-core/src/types/file.d.ts
@@ -0,0 +1,35 @@
+import { Budget } from './budget';
+
+export type FileState =
+ | 'local'
+ | 'remote'
+ | 'synced'
+ | 'detached'
+ | 'broken'
+ | 'unknown';
+
+export type LocalFile = Omit<Budget, 'cloudFileId' | 'groupId'> & {
+ state: 'local';
+};
+export type SyncableLocalFile = Budget & {
+ cloudFileId: string;
+ groupId: string;
+ state: 'broken' | 'unknown';
+};
+export type SyncedLocalFile = Budget & {
+ cloudFileId: string;
+ groupId: string;
+ encryptKeyId?: string;
+ hasKey: boolean;
+ state: 'synced' | 'detached';
+};
+export type RemoteFile = {
+ cloudFileId: string;
+ groupId: string;
+ name: string;
+ enccryptKeyId?: string;
+ hasKey: boolean;
+ state: 'remote';
+};
+
+export type File = LocalFile | SyncableLocalFile | SyncedLocalFile | RemoteFile;
diff --git a/packages/loot-core/src/types/models/account.d.ts b/packages/loot-core/src/types/models/account.d.ts
index 5d062d8a4c..3bb86d4cb9 100644
--- a/packages/loot-core/src/types/models/account.d.ts
+++ b/packages/loot-core/src/types/models/account.d.ts
@@ -1,10 +1,19 @@
-export interface AccountEntity {
- id?: string;
+export type AccountEntity = {
+ id: string;
name: string;
- offbudget?: boolean;
- closed?: boolean;
- sort_order?: number;
- tombstone?: boolean;
- // TODO: remove once properly typed
- [k: string]: unknown;
-}
+ offbudget: 0 | 1;
+ closed: 0 | 1;
+ sort_order: number;
+ tombstone: 0 | 1;
+ subtype: string | null; // TODO: remove?
+} & (_SyncFields<true> | _SyncFields<false>);
+
+type _SyncFields<T> = {
+ account_id: T extends true ? string : null;
+ bank: T extends true ? string : null;
+ mask: T extends true ? string : null; // end of bank account number
+ official_name: T extends true ? string : null;
+ balance_current: T extends true ? number : null;
+ balance_available: T extends true ? number : null;
+ balance_limit: T extends true ? number : null;
+};
diff --git a/packages/loot-core/src/types/server-handlers.d.ts b/packages/loot-core/src/types/server-handlers.d.ts
index 061e40353d..5fd3046481 100644
--- a/packages/loot-core/src/types/server-handlers.d.ts
+++ b/packages/loot-core/src/types/server-handlers.d.ts
@@ -1,9 +1,11 @@
+import { GlobalPrefs, LocalPrefs } from '../client/state-types/prefs';
import { ParseFileResult } from '../server/accounts/parse-file';
import { batchUpdateTransactions } from '../server/accounts/transactions';
import { Backup } from '../server/backups';
import { RemoteFile } from '../server/cloud-storage';
import { Message } from '../server/sync';
+import { AccountEntity } from './models';
import { EmptyObject } from './util';
export interface ServerHandlers {
@@ -40,9 +42,10 @@ export interface ServerHandlers {
'transactions-export-query': (arg: { query: queryState }) => Promise<unknown>;
+ // incomplete
'get-categories': () => Promise<{
- grouped: unknown[];
- list: unknown[];
+ grouped: { id: string }[];
+ list: { id: string }[];
}>;
'get-earliest-transaction': () => Promise<unknown>;
@@ -134,7 +137,7 @@ export interface ServerHandlers {
'account-update': (arg: { id; name }) => Promise<unknown>;
- 'accounts-get': () => Promise<unknown>;
+ 'accounts-get': () => Promise<AccountEntity[]>;
'account-properties': (arg: {
id;
@@ -168,10 +171,10 @@ export interface ServerHandlers {
}) => Promise<unknown>;
'account-create': (arg: {
- name;
- balance;
- offBudget;
- closed?;
+ name: string;
+ balance: number;
+ offBudget?: boolean;
+ closed?: 0 | 1;
}) => Promise<string>;
'account-close': (arg: {
@@ -240,17 +243,11 @@ export interface ServerHandlers {
'save-global-prefs': (prefs) => Promise<'ok'>;
- 'load-global-prefs': () => Promise<{
- floatingSidebar: boolean;
- maxMonths: number;
- autoUpdate: boolean;
- documentDir: string;
- keyId: string;
- }>;
+ 'load-global-prefs': () => Promise<GlobalPrefs>;
'save-prefs': (prefsToSet) => Promise<'ok'>;
- 'load-prefs': () => Promise<Record<string, unknown> | null>;
+ 'load-prefs': () => Promise<LocalPrefs | null>;
'sync-reset': () => Promise<{ error?: { reason: string; meta?: unknown } }>;
@@ -294,14 +291,7 @@ export interface ServerHandlers {
| { messages: Message[] }
>;
- 'get-budgets': () => Promise<
- {
- id: string;
- cloudFileId: string;
- groupId: string;
- name: string;
- }[]
- >;
+ 'get-budgets': () => Promise<Budget[]>;
'get-remote-files': () => Promise<RemoteFile[]>;
diff --git a/upcoming-release-notes/1269.md b/upcoming-release-notes/1269.md
new file mode 100644
index 0000000000..81c02bbd8c
--- /dev/null
+++ b/upcoming-release-notes/1269.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [j-f1]
+---
+
+Add TypeScript typings to most of the Redux-related functionality
diff --git a/yarn.lock b/yarn.lock
index e9d22d5ddc..6621bacda1 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -88,6 +88,7 @@ __metadata:
"@types/react": ^18.2.0
"@types/react-dom": ^18.2.1
"@types/react-modal": ^3.16.0
+ "@types/react-redux": ^7.1.25
"@types/react-router-dom": ^5.3.3
"@types/uuid": ^9.0.2
"@types/webpack-bundle-analyzer": ^4.6.0
@@ -4151,6 +4152,16 @@ __metadata:
languageName: node
linkType: hard
+"@types/hoist-non-react-statics@npm:^3.3.0":
+ version: 3.3.1
+ resolution: "@types/hoist-non-react-statics@npm:3.3.1"
+ dependencies:
+ "@types/react": "*"
+ hoist-non-react-statics: ^3.3.0
+ checksum: 2c0778570d9a01d05afabc781b32163f28409bb98f7245c38d5eaf082416fdb73034003f5825eb5e21313044e8d2d9e1f3fe2831e345d3d1b1d20bcd12270719
+ languageName: node
+ linkType: hard
+
"@types/html-minifier-terser@npm:^6.0.0":
version: 6.1.0
resolution: "@types/html-minifier-terser@npm:6.1.0"
@@ -4354,6 +4365,18 @@ __metadata:
languageName: node
linkType: hard
+"@types/react-redux@npm:^7.1.25":
+ version: 7.1.25
+ resolution: "@types/react-redux@npm:7.1.25"
+ dependencies:
+ "@types/hoist-non-react-statics": ^3.3.0
+ "@types/react": "*"
+ hoist-non-react-statics: ^3.3.0
+ redux: ^4.0.0
+ checksum: a61ec25cbf8bb3720850402d3c49493fcff4afb73ad447d161460b5d4c600c984ad48708e8564d2fd32052eaa3c3b3f655c5b300ce813429637cce9e5958329f
+ languageName: node
+ linkType: hard
+
"@types/react-router-dom@npm:^5.3.3":
version: 5.3.3
resolution: "@types/react-router-dom@npm:5.3.3"
@@ -12329,6 +12352,7 @@ __metadata:
"@types/jest": ^27.5.0
"@types/jlongster__sql.js": "npm:@types/sql.js@latest"
"@types/pegjs": ^0.10.3
+ "@types/react-redux": ^7.1.25
"@types/uuid": ^9.0.2
"@types/webpack": ^5.28.0
"@types/webpack-bundle-analyzer": ^4.6.0
@@ -15552,7 +15576,7 @@ __metadata:
languageName: node
linkType: hard
-"redux@npm:^4.0.5, redux@npm:^4.2.0":
+"redux@npm:^4.0.0, redux@npm:^4.0.5, redux@npm:^4.2.0":
version: 4.2.1
resolution: "redux@npm:4.2.1"
dependencies: