Skip to content

A local-first personal finance app

Revert "Mobile running balance" because its causing extreme slowness in large accounts. (#5405)

youngcw6e2154d40181
diff --git a/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx b/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
index cc8de1dcc5..6402e4dcec 100644
--- a/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
+++ b/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
@@ -16,7 +16,6 @@ import { View } from '@actual-app/components/view';
import { listen, send } from 'loot-core/platform/client/fetch';
import { type Query } from 'loot-core/shared/query';
import { isPreviewId } from 'loot-core/shared/transactions';
-import { type IntegerAmount } from 'loot-core/shared/util';
import {
type AccountEntity,
type TransactionEntity,
@@ -32,9 +31,8 @@ import { SchedulesProvider } from '@desktop-client/hooks/useCachedSchedules';
import { useDateFormat } from '@desktop-client/hooks/useDateFormat';
import { useFailedAccounts } from '@desktop-client/hooks/useFailedAccounts';
import { useNavigate } from '@desktop-client/hooks/useNavigate';
-import { useTransactions } from '@desktop-client/hooks/usePreviewTransactions';
import { accountSchedulesQuery } from '@desktop-client/hooks/useSchedules';
-import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';
+import { useTransactions } from '@desktop-client/hooks/useTransactions';
import { useTransactionsSearch } from '@desktop-client/hooks/useTransactionsSearch';
import {
collapseModals,
@@ -150,19 +148,6 @@ function AccountHeader({ account }: { readonly account: AccountEntity }) {
dispatch(reopenAccount({ id: account.id }));
}, [account.id, dispatch]);
- const [showBalances, setBalances] = useSyncedPref(
- `show-balances-${account.id}`,
- );
- const onToggleRunningBalance = useCallback(() => {
- const newVal = showBalances === 'true' ? 'false' : 'true';
- setBalances(newVal);
- dispatch(
- collapseModals({
- rootModalName: 'account-menu',
- }),
- );
- }, [showBalances, setBalances, dispatch]);
-
const onClick = useCallback(() => {
dispatch(
pushModal({
@@ -174,7 +159,6 @@ function AccountHeader({ account }: { readonly account: AccountEntity }) {
onEditNotes,
onCloseAccount,
onReopenAccount,
- onToggleRunningBalance,
},
},
}),
@@ -186,7 +170,6 @@ function AccountHeader({ account }: { readonly account: AccountEntity }) {
onEditNotes,
onReopenAccount,
onSave,
- onToggleRunningBalance,
]);
return (
@@ -258,73 +241,39 @@ function TransactionListWithPreviews({
readonly accountName: AccountEntity['name'] | string;
}) {
const { t } = useTranslation();
- const dateFormat = useDateFormat() || 'MM/dd/yyyy';
- const dispatch = useDispatch();
- const navigate = useNavigate();
-
- const onRefresh = useCallback(() => {
- if (accountId) {
- dispatch(syncAndDownload({ accountId }));
- }
- }, [accountId, dispatch]);
-
const baseTransactionsQuery = useCallback(
() =>
queries.transactions(accountId).options({ splits: 'all' }).select('*'),
[accountId],
);
- const runningBalancesQuery = useCallback(
- () =>
- queries
- .transactions(accountId)
- .options({ splits: 'none' })
- .select({ balance: { $sumOver: '$amount' } }),
- [accountId],
- );
-
- const [showBalances] = useSyncedPref(`show-balances-${accountId}`);
const [transactionsQuery, setTransactionsQuery] = useState<Query>(
baseTransactionsQuery(),
);
- const [balancesQuery] = useState<Query>(runningBalancesQuery);
const {
transactions,
- runningBalances,
isLoading: isTransactionsLoading,
reload: reloadTransactions,
isLoadingMore,
loadMore: loadMoreTransactions,
} = useTransactions({
query: transactionsQuery,
- runningBalanceQuery: balancesQuery,
- options: {
- calculateRunningBalances: true,
- },
});
- const { isSearching, search: onSearch } = useTransactionsSearch({
- updateQuery: setTransactionsQuery,
- resetQuery: () => setTransactionsQuery(baseTransactionsQuery()),
- dateFormat,
- });
+ const { previewTransactions, isLoading: isPreviewTransactionsLoading } =
+ useAccountPreviewTransactions({
+ accountId: account?.id,
+ });
- const {
- previewTransactions,
- runningBalances: previewRunningBalances,
- isLoading: isPreviewTransactionsLoading,
- } = useAccountPreviewTransactions({
- accountId: account?.id,
- });
+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';
+ const dispatch = useDispatch();
+ const navigate = useNavigate();
- const allBalances = useMemo(
- () =>
- new Map<TransactionEntity['id'], IntegerAmount>([
- ...previewRunningBalances,
- ...runningBalances,
- ]),
- [runningBalances, previewRunningBalances],
- );
+ const onRefresh = useCallback(() => {
+ if (accountId) {
+ dispatch(syncAndDownload({ accountId }));
+ }
+ }, [accountId, dispatch]);
useEffect(() => {
if (accountId) {
@@ -347,6 +296,12 @@ function TransactionListWithPreviews({
});
}, [dispatch, reloadTransactions]);
+ const { isSearching, search: onSearch } = useTransactionsSearch({
+ updateQuery: setTransactionsQuery,
+ resetQuery: () => setTransactionsQuery(baseTransactionsQuery()),
+ dateFormat,
+ });
+
const onOpenTransaction = useCallback(
(transaction: TransactionEntity) => {
if (!isPreviewId(transaction.id)) {
@@ -418,8 +373,6 @@ function TransactionListWithPreviews({
balance={balanceQueries.balance}
balanceCleared={balanceQueries.cleared}
balanceUncleared={balanceQueries.uncleared}
- runningBalances={allBalances}
- showBalances={isSearching ? false : showBalances === 'true'}
isLoadingMore={isLoadingMore}
onLoadMore={loadMoreTransactions}
searchPlaceholder={t('Search {{accountName}}', { accountName })}
diff --git a/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx b/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
index 0aa86c24ba..40abfc7e5f 100644
--- a/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
@@ -154,7 +154,6 @@ function TransactionListWithPreviews({
balance={balance}
balanceCleared={balanceCleared}
balanceUncleared={balanceUncleared}
- runningBalances={undefined}
searchPlaceholder={`Search ${category.name}`}
onSearch={onSearch}
isLoadingMore={isLoadingMore}
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx
index de0b2bfa1a..1a4bbf1a4d 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx
@@ -32,11 +32,7 @@ import { View } from '@actual-app/components/view';
import * as monthUtils from 'loot-core/shared/months';
import { isPreviewId } from 'loot-core/shared/transactions';
import { validForTransfer } from 'loot-core/shared/transfer';
-import {
- groupById,
- type IntegerAmount,
- integerToCurrency,
-} from 'loot-core/shared/util';
+import { groupById, integerToCurrency } from 'loot-core/shared/util';
import {
type AccountEntity,
type TransactionEntity,
@@ -88,8 +84,6 @@ function Loading({ style, 'aria-label': ariaLabel }: LoadingProps) {
type TransactionListProps = {
isLoading: boolean;
transactions: readonly TransactionEntity[];
- showBalances?: boolean;
- runningBalances?: Map<TransactionEntity['id'], IntegerAmount>;
onOpenTransaction?: (transaction: TransactionEntity) => void;
isLoadingMore: boolean;
onLoadMore: () => void;
@@ -99,8 +93,6 @@ type TransactionListProps = {
export function TransactionList({
isLoading,
transactions,
- showBalances,
- runningBalances,
onOpenTransaction,
isLoadingMore,
onLoadMore,
@@ -206,13 +198,10 @@ export function TransactionList({
t => !isPreviewId(t.id) || !t.is_child,
)}
addIdAndValue
- dependencies={[transactions, showBalances, runningBalances]}
>
{transaction => (
<TransactionListItem
key={transaction.id}
- showBalance={showBalances}
- balance={runningBalances?.get(transaction.id)}
value={transaction}
onPress={trans => onTransactionPress(trans)}
onLongPress={trans => onTransactionPress(trans, true)}
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
index f6fdf4ae2d..f677f60ed1 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
@@ -30,7 +30,7 @@ import {
} from '@react-aria/interactions';
import { isPreviewId } from 'loot-core/shared/transactions';
-import { type IntegerAmount, integerToCurrency } from 'loot-core/shared/util';
+import { integerToCurrency } from 'loot-core/shared/util';
import {
type AccountEntity,
type TransactionEntity,
@@ -38,10 +38,7 @@ import {
import { lookupName, Status } from './TransactionEdit';
-import {
- makeAmountFullStyle,
- makeBalanceAmountStyle,
-} from '@desktop-client/components/budget/util';
+import { makeAmountFullStyle } from '@desktop-client/components/budget/util';
import { useAccount } from '@desktop-client/hooks/useAccount';
import { useCachedSchedules } from '@desktop-client/hooks/useCachedSchedules';
import { useCategories } from '@desktop-client/hooks/useCategories';
@@ -77,15 +74,11 @@ const getScheduleIconStyle = ({ isPreview }: { isPreview: boolean }) => ({
type TransactionListItemProps = ComponentPropsWithoutRef<
typeof ListBoxItem<TransactionEntity>
> & {
- showBalance?: boolean;
- balance?: IntegerAmount;
onPress: (transaction: TransactionEntity) => void;
onLongPress: (transaction: TransactionEntity) => void;
};
export function TransactionListItem({
- showBalance,
- balance,
onPress,
onLongPress,
...props
@@ -290,7 +283,7 @@ export function TransactionListItem({
</TextOneLine>
)}
</View>
- <View style={{ textAlign: 'right' }}>
+ <View style={{ justifyContent: 'center' }}>
<Text
style={{
...textStyle,
@@ -299,17 +292,6 @@ export function TransactionListItem({
>
{integerToCurrency(amount)}
</Text>
- {showBalance && (
- <Text
- style={{
- fontSize: 11,
- fontWeight: '400',
- ...makeBalanceAmountStyle(balance || 0),
- }}
- >
- {integerToCurrency(balance || 0)}
- </Text>
- )}
</View>
</View>
</Button>
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.tsx
index 39454632ec..3297de169a 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.tsx
@@ -6,7 +6,6 @@ import { styles } from '@actual-app/components/styles';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { type IntegerAmount } from 'loot-core/shared/util';
import {
type AccountEntity,
type TransactionEntity,
@@ -87,8 +86,6 @@ type TransactionListWithBalancesProps = {
balanceUncleared?:
| Binding<'category', 'balanceUncleared'>
| Binding<'account', 'balanceUncleared'>;
- showBalances?: boolean;
- runningBalances?: Map<TransactionEntity['id'], IntegerAmount>;
searchPlaceholder: string;
onSearch: (searchText: string) => void;
isLoadingMore: boolean;
@@ -104,8 +101,6 @@ export function TransactionListWithBalances({
balance,
balanceCleared,
balanceUncleared,
- showBalances,
- runningBalances,
searchPlaceholder = 'Search...',
onSearch,
isLoadingMore,
@@ -153,8 +148,6 @@ export function TransactionListWithBalances({
<TransactionList
isLoading={isLoading}
transactions={transactions}
- showBalances={showBalances}
- runningBalances={runningBalances}
isLoadingMore={isLoadingMore}
onLoadMore={onLoadMore}
onOpenTransaction={onOpenTransaction}
diff --git a/packages/desktop-client/src/components/modals/AccountMenuModal.tsx b/packages/desktop-client/src/components/modals/AccountMenuModal.tsx
index ffcc783097..9810b71fa8 100644
--- a/packages/desktop-client/src/components/modals/AccountMenuModal.tsx
+++ b/packages/desktop-client/src/components/modals/AccountMenuModal.tsx
@@ -33,7 +33,6 @@ import { validateAccountName } from '@desktop-client/components/util/accountVali
import { useAccount } from '@desktop-client/hooks/useAccount';
import { useAccounts } from '@desktop-client/hooks/useAccounts';
import { useNotes } from '@desktop-client/hooks/useNotes';
-import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';
import { type Modal as ModalType } from '@desktop-client/modals/modalsSlice';
type AccountMenuModalProps = Extract<
@@ -48,7 +47,6 @@ export function AccountMenuModal({
onReopenAccount,
onEditNotes,
onClose,
- onToggleRunningBalance,
}: AccountMenuModalProps) {
const { t } = useTranslation();
const account = useAccount(accountId);
@@ -126,7 +124,6 @@ export function AccountMenuModal({
account={account}
onClose={onCloseAccount}
onReopen={onReopenAccount}
- onToggleRunningBalance={onToggleRunningBalance}
/>
}
title={
@@ -204,14 +201,12 @@ type AdditionalAccountMenuProps = {
account: AccountEntity;
onClose?: (accountId: string) => void;
onReopen?: (accountId: string) => void;
- onToggleRunningBalance?: () => void;
};
function AdditionalAccountMenu({
account,
onClose,
onReopen,
- onToggleRunningBalance,
}: AdditionalAccountMenuProps) {
const { t } = useTranslation();
const triggerRef = useRef(null);
@@ -225,7 +220,6 @@ function AdditionalAccountMenu({
...itemStyle,
...(item.name === 'close' && { color: theme.errorTextMenu }),
});
- const [showBalances] = useSyncedPref(`show-balances-${account.id}`);
return (
<View>
@@ -251,13 +245,6 @@ function AdditionalAccountMenu({
<Menu
getItemStyle={getItemStyle}
items={[
- {
- name: 'balance',
- text:
- showBalances === 'true'
- ? t('Hide running balance')
- : t('Show running balance'),
- },
account.closed
? {
name: 'reopen',
@@ -281,9 +268,6 @@ function AdditionalAccountMenu({
case 'reopen':
onReopen?.(account.id);
break;
- case 'balance':
- onToggleRunningBalance?.();
- break;
default:
throw new Error(`Unrecognized menu option: ${name}`);
}
diff --git a/packages/desktop-client/src/components/reports/reports/Calendar.tsx b/packages/desktop-client/src/components/reports/reports/Calendar.tsx
index 0ca65fcf0f..09fb3b733b 100644
--- a/packages/desktop-client/src/components/reports/reports/Calendar.tsx
+++ b/packages/desktop-client/src/components/reports/reports/Calendar.tsx
@@ -709,7 +709,6 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
onOpenTransaction={onOpenTransaction}
isLoadingMore={false}
account={undefined}
- runningBalances={undefined}
/>
</View>
</animated.div>
diff --git a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
index 1eec313360..08e9171ade 100644
--- a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
+++ b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
@@ -1,6 +1,6 @@
import { useCallback, useMemo } from 'react';
-import { groupById, type IntegerAmount } from 'loot-core/shared/util';
+import { groupById } from 'loot-core/shared/util';
import {
type ScheduleEntity,
type AccountEntity,
@@ -19,15 +19,9 @@ type UseAccountPreviewTransactionsProps = {
accountId?: AccountEntity['id'] | undefined;
};
-// Mirrors the `splits` AQL option from the server
-type TransactionSplitsOption = 'all' | 'inline' | 'grouped' | 'none';
-
-type UseAccountPreviewTransactionsResult = {
- previewTransactions: ReadonlyArray<TransactionEntity>;
- runningBalances: Map<TransactionEntity['id'], IntegerAmount>;
- isLoading: boolean;
- error?: Error;
-};
+type UseAccountPreviewTransactionsResult = ReturnType<
+ typeof usePreviewTransactions
+>;
/**
* Preview transactions for a given account. This will invert the payees, accounts,
@@ -76,17 +70,21 @@ export function useAccountPreviewTransactions({
const {
previewTransactions: allPreviewTransactions,
+ runningBalances: allRunningBalances,
isLoading,
error,
} = usePreviewTransactions({
filter: accountSchedulesFilter,
+ options: {
+ startingBalance: accountBalanceValue ?? 0,
+ },
});
return useMemo(() => {
if (!accountId) {
return {
previewTransactions: allPreviewTransactions,
- runningBalances: new Map(),
+ runningBalances: allRunningBalances,
isLoading,
error,
};
@@ -99,11 +97,6 @@ export function useAccountPreviewTransactions({
getTransferAccountByPayee,
});
- const allRunningBalances = calculateRunningBalancesBottomUp(
- previewTransactions,
- 'all',
- accountBalanceValue ?? 0,
- );
const transactionIds = new Set(previewTransactions.map(t => t.id));
const runningBalances = allRunningBalances;
for (const transactionId of runningBalances.keys()) {
@@ -120,8 +113,8 @@ export function useAccountPreviewTransactions({
};
}, [
accountId,
- accountBalanceValue,
allPreviewTransactions,
+ allRunningBalances,
error,
getPayeeByTransferAccount,
getTransferAccountByPayee,
@@ -171,41 +164,3 @@ function accountPreview({
};
});
}
-
-export function calculateRunningBalancesBottomUp(
- transactions: TransactionEntity[],
- splits: TransactionSplitsOption,
- startingBalance: IntegerAmount = 0,
-) {
- return (
- transactions
- .filter(t => {
- switch (splits) {
- case 'all':
- // Only calculate parent/non-split amounts
- return !t.parent_id;
- default:
- // inline
- // grouped
- // none
- return true;
- }
- })
- // We're using `reduceRight` here to calculate the running balance in reverse order (bottom up).
- .reduceRight((acc, transaction, index, arr) => {
- const previousTransactionIndex = index + 1;
- if (previousTransactionIndex >= arr.length) {
- // This is the last transaction in the list,
- // so we set the running balance to the starting balance + the amount of the transaction
- acc.set(transaction.id, startingBalance + transaction.amount);
- return acc;
- }
- const previousTransaction = arr[previousTransactionIndex];
- const previousRunningBalance = acc.get(previousTransaction.id) ?? 0;
- const currentRunningBalance =
- previousRunningBalance + transaction.amount;
- acc.set(transaction.id, currentRunningBalance);
- return acc;
- }, new Map<TransactionEntity['id'], IntegerAmount>())
- );
-}
diff --git a/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts b/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts
index d803128de4..7bdd64b6a1 100644
--- a/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts
+++ b/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts
@@ -6,7 +6,6 @@ import {
type CategoryEntity,
} from 'loot-core/types/models';
-import { calculateRunningBalancesBottomUp } from './useAccountPreviewTransactions';
import { useCategory } from './useCategory';
import { useCategoryScheduleGoalTemplates } from './useCategoryScheduleGoalTemplates';
import { usePreviewTransactions } from './usePreviewTransactions';
@@ -52,10 +51,14 @@ export function useCategoryPreviewTransactions({
const {
previewTransactions: allPreviewTransactions,
+ runningBalances: allRunningBalances,
isLoading,
error,
} = usePreviewTransactions({
filter: categorySchedulesFilter,
+ options: {
+ startingBalance: categoryBalanceValue ?? 0,
+ },
});
return useMemo(() => {
@@ -74,11 +77,7 @@ export function useCategoryPreviewTransactions({
);
const transactionIds = new Set(previewTransactions.map(t => t.id));
- const runningBalances = calculateRunningBalancesBottomUp(
- previewTransactions,
- 'all',
- categoryBalanceValue ?? 0,
- );
+ const runningBalances = allRunningBalances;
for (const transactionId of runningBalances.keys()) {
if (!transactionIds.has(transactionId)) {
runningBalances.delete(transactionId);
@@ -93,8 +92,8 @@ export function useCategoryPreviewTransactions({
};
}, [
allPreviewTransactions,
+ allRunningBalances,
category,
- categoryBalanceValue,
error,
isLoading,
schedulesToPreview,
diff --git a/packages/desktop-client/src/hooks/usePreviewTransactions.ts b/packages/desktop-client/src/hooks/usePreviewTransactions.ts
index 6c150abd16..4055d8e8e1 100644
--- a/packages/desktop-client/src/hooks/usePreviewTransactions.ts
+++ b/packages/desktop-client/src/hooks/usePreviewTransactions.ts
@@ -23,7 +23,6 @@ import { useCachedSchedules } from './useCachedSchedules';
import { type ScheduleStatuses } from './useSchedules';
import { useSyncedPref } from './useSyncedPref';
-import { aqlQuery } from '@desktop-client/queries/aqlQuery';
import {
pagedQuery,
type PagedQuery,
@@ -45,10 +44,6 @@ type UseTransactionsProps = {
* to prevent unnecessary re-renders i.e. `useMemo`, `useState`, etc.
*/
query?: Query;
- /**
- * Query to use to calculate the running balance
- */
- runningBalanceQuery?: Query;
/**
* The options to configure the hook behavior.
*/
@@ -114,7 +109,6 @@ type UseTransactionsResult = {
export function useTransactions({
query,
- runningBalanceQuery,
options = { pageCount: 50, calculateRunningBalances: false },
}: UseTransactionsProps): UseTransactionsResult {
const [isLoading, setIsLoading] = useState(true);
@@ -162,6 +156,19 @@ export function useTransactions({
onData: data => {
if (!isUnmounted) {
setTransactions(data);
+
+ const calculateFn = getCalculateRunningBalancesFn(
+ optionsRef.current?.calculateRunningBalances,
+ );
+ if (calculateFn) {
+ setRunningBalances(
+ calculateFn(
+ data,
+ query.state.tableOptions?.splits as TransactionSplitsOption,
+ ),
+ );
+ }
+
setIsLoading(false);
}
},
@@ -177,20 +184,6 @@ export function useTransactions({
};
}, [query]);
- useEffect(() => {
- if (options.calculateRunningBalances && runningBalanceQuery) {
- aqlQuery(runningBalanceQuery).then(data => {
- const map = new Map<TransactionEntity['id'], IntegerAmount>();
- data.data.forEach((val: { id: string; balance: IntegerAmount }) => {
- map.set(val.id, val.balance);
- });
- setRunningBalances(map);
- });
- } else {
- setRunningBalances(new Map());
- }
- }, [runningBalanceQuery, options.calculateRunningBalances]);
-
const loadMore = useCallback(async () => {
if (!pagedQueryRef.current) {
return;
@@ -223,16 +216,24 @@ export function useTransactions({
type UsePreviewTransactionsProps = {
filter?: (schedule: ScheduleEntity) => boolean;
+ options?: {
+ /**
+ * The starting balance to start the running balance calculation from.
+ */
+ startingBalance?: IntegerAmount;
+ };
};
type UsePreviewTransactionsResult = {
previewTransactions: ReadonlyArray<TransactionEntity>;
+ runningBalances: Map<TransactionEntity['id'], IntegerAmount>;
isLoading: boolean;
error?: Error;
};
export function usePreviewTransactions({
filter,
+ options,
}: UsePreviewTransactionsProps = {}): UsePreviewTransactionsResult {
const [previewTransactions, setPreviewTransactions] = useState<
TransactionEntity[]
@@ -245,9 +246,18 @@ export function usePreviewTransactions({
} = useCachedSchedules();
const [isLoading, setIsLoading] = useState(isSchedulesLoading);
const [error, setError] = useState<Error | undefined>(undefined);
+ const [runningBalances, setRunningBalances] = useState<
+ Map<TransactionEntity['id'], IntegerAmount>
+ >(new Map());
const [upcomingLength] = useSyncedPref('upcomingScheduledTransactionLength');
+ // We don't want to re-render if options changes.
+ // Putting options in a ref will prevent that and
+ // allow us to use the latest options on next render.
+ const optionsRef = useRef(options);
+ optionsRef.current = options;
+
const scheduleTransactions = useMemo(() => {
if (isSchedulesLoading) {
return [];
@@ -362,6 +372,19 @@ export function usePreviewTransactions({
const ungroupedTransactions = ungroupTransactions(withDefaults);
setPreviewTransactions(ungroupedTransactions);
+ setRunningBalances(
+ // We always use the bottom up calculation for preview transactions
+ // because the hook controls the order of the transactions. We don't
+ // need to provide a custom way for consumers to calculate the running
+ // balances, at least as of writing.
+ calculateRunningBalancesBottomUp(
+ ungroupedTransactions,
+ // Preview transactions are behaves like 'all' splits
+ 'all',
+ optionsRef.current?.startingBalance,
+ ),
+ );
+
setIsLoading(false);
}
})
@@ -380,6 +403,7 @@ export function usePreviewTransactions({
const returnError = error || scheduleQueryError;
return {
previewTransactions,
+ runningBalances,
isLoading: isLoading || isSchedulesLoading,
...(returnError && { error: returnError }),
};
@@ -395,3 +419,51 @@ export function isForPreview(
['due', 'upcoming', 'missed', 'paid'].includes(status!)
);
}
+
+function getCalculateRunningBalancesFn(
+ calculateRunningBalances: CalculateRunningBalancesOption = false,
+) {
+ return calculateRunningBalances === true
+ ? calculateRunningBalancesBottomUp
+ : typeof calculateRunningBalances === 'function'
+ ? calculateRunningBalances
+ : undefined;
+}
+
+export function calculateRunningBalancesBottomUp(
+ transactions: TransactionEntity[],
+ splits: TransactionSplitsOption,
+ startingBalance: IntegerAmount = 0,
+) {
+ return (
+ transactions
+ .filter(t => {
+ switch (splits) {
+ case 'all':
+ // Only calculate parent/non-split amounts
+ return !t.parent_id;
+ default:
+ // inline
+ // grouped
+ // none
+ return true;
+ }
+ })
+ // We're using `reduceRight` here to calculate the running balance in reverse order (bottom up).
+ .reduceRight((acc, transaction, index, arr) => {
+ const previousTransactionIndex = index + 1;
+ if (previousTransactionIndex >= arr.length) {
+ // This is the last transaction in the list,
+ // so we set the running balance to the starting balance + the amount of the transaction
+ acc.set(transaction.id, startingBalance + transaction.amount);
+ return acc;
+ }
+ const previousTransaction = arr[previousTransactionIndex];
+ const previousRunningBalance = acc.get(previousTransaction.id) ?? 0;
+ const currentRunningBalance =
+ previousRunningBalance + transaction.amount;
+ acc.set(transaction.id, currentRunningBalance);
+ return acc;
+ }, new Map<TransactionEntity['id'], IntegerAmount>())
+ );
+}
diff --git a/packages/desktop-client/src/modals/modalsSlice.ts b/packages/desktop-client/src/modals/modalsSlice.ts
index 5e5d6d3aa0..af324a5e6b 100644
--- a/packages/desktop-client/src/modals/modalsSlice.ts
+++ b/packages/desktop-client/src/modals/modalsSlice.ts
@@ -277,7 +277,6 @@ export type Modal =
onReopenAccount: (accountId: AccountEntity['id']) => void;
onEditNotes: (id: NoteEntity['id']) => void;
onClose?: () => void;
- onToggleRunningBalance?: () => void;
};
}
| {
diff --git a/upcoming-release-notes/5219.md b/upcoming-release-notes/5219.md
deleted file mode 100644
index b0a0b6524b..0000000000
--- a/upcoming-release-notes/5219.md
+++ /dev/null
@@ -1,6 +0,0 @@
----
-category: Enhancements
-authors: [youngcw]
----
-
-Mobile running balance
diff --git a/upcoming-release-notes/5405.md b/upcoming-release-notes/5405.md
new file mode 100644
index 0000000000..8b0acccc66
--- /dev/null
+++ b/upcoming-release-notes/5405.md
@@ -0,0 +1,7 @@
+---
+category: Bugfix
+authors: [youngcw]
+---
+
+Remove mobile running balance feature to improve performance for large accounts.
+