Skip to content

A local-first personal finance app

Add `runningBalances` to `usePreviewTransactions` and an option to set the starting balance to start running balance calculation from (#4994)

Joel Jeremy Marquez7dd98c4f86cb
diff --git a/packages/desktop-client/src/components/accounts/Reconcile.tsx b/packages/desktop-client/src/components/accounts/Reconcile.tsx
index 9610c83344..5aa450d90c 100644
--- a/packages/desktop-client/src/components/accounts/Reconcile.tsx
+++ b/packages/desktop-client/src/components/accounts/Reconcile.tsx
@@ -127,7 +127,7 @@ export function ReconcileMenu({
onReconcile,
onClose,
}: ReconcileMenuProps) {
- const balanceQuery = queries.accountBalance(account);
+ const balanceQuery = queries.accountBalance(account.id);
const clearedBalance = useSheetValue<'account', `balance-${string}-cleared`>({
name: (balanceQuery.name + '-cleared') as `balance-${string}-cleared`,
value: null,
diff --git a/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx b/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
index 4d870c602a..ce433f1bd6 100644
--- a/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
+++ b/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
@@ -265,7 +265,7 @@ function TransactionListWithPreviews({
});
const { previewTransactions } = useAccountPreviewTransactions({
- accountId: account?.id || '',
+ accountId: account?.id,
});
const dateFormat = useDateFormat() || 'MM/dd/yyyy';
@@ -406,9 +406,9 @@ function queriesFromAccountId(
default:
return entity
? {
- balance: queries.accountBalance(entity),
- cleared: queries.accountBalanceCleared(entity),
- uncleared: queries.accountBalanceUncleared(entity),
+ balance: queries.accountBalance(entity.id),
+ cleared: queries.accountBalanceCleared(entity.id),
+ uncleared: queries.accountBalanceUncleared(entity.id),
}
: { balance: queries.allAccountBalance() };
}
diff --git a/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx b/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx
index 30b49f60de..19312ee093 100644
--- a/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx
+++ b/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx
@@ -134,7 +134,9 @@ type AccountListItemProps = ComponentPropsWithoutRef<
isConnected: boolean;
isPending: boolean;
isFailed: boolean;
- getBalanceQuery: (account: AccountEntity) => Binding<'account', 'balance'>;
+ getBalanceQuery: (
+ accountId: AccountEntity['id'],
+ ) => Binding<'account', 'balance'>;
onSelect: (account: AccountEntity) => void;
};
@@ -214,7 +216,7 @@ function AccountListItem({
</TextOneLine>
</View>
</View>
- <CellValue binding={getBalanceQuery(account)} type="financial">
+ <CellValue binding={getBalanceQuery(account.id)} type="financial">
{props => (
<CellValueText<'account', 'balance'>
{...props}
@@ -248,7 +250,9 @@ function EmptyMessage() {
type AllAccountListProps = {
accounts: AccountEntity[];
- getAccountBalance: (account: AccountEntity) => Binding<'account', 'balance'>;
+ getAccountBalance: (
+ accountId: AccountEntity['id'],
+ ) => Binding<'account', 'balance'>;
getOnBudgetBalance: () => Binding<'account', 'onbudget-accounts-balance'>;
getOffBudgetBalance: () => Binding<'account', 'offbudget-accounts-balance'>;
getClosedAccountsBalance: () => Binding<'account', 'closed-accounts-balance'>;
@@ -377,7 +381,9 @@ function AllAccountList({
type AccountListProps = {
'aria-label': string;
accounts: AccountEntity[];
- getAccountBalance: (account: AccountEntity) => Binding<'account', 'balance'>;
+ getAccountBalance: (
+ accountId: AccountEntity['id'],
+ ) => Binding<'account', 'balance'>;
onOpenAccount: (account: AccountEntity) => void;
};
diff --git a/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx b/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
index c43536faa6..1bfde2240a 100644
--- a/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
@@ -134,9 +134,9 @@ function TransactionListWithPreviews({
[navigate],
);
- const balance = queries.categoryBalance(category, month);
- const balanceCleared = queries.categoryBalanceCleared(category, month);
- const balanceUncleared = queries.categoryBalanceUncleared(category, month);
+ const balance = queries.categoryBalance(category.id, month);
+ const balanceCleared = queries.categoryBalanceCleared(category.id, month);
+ const balanceUncleared = queries.categoryBalanceUncleared(category.id, month);
const { previewTransactions } = useCategoryPreviewTransactions({
categoryId: category.id,
diff --git a/packages/desktop-client/src/components/sidebar/Accounts.tsx b/packages/desktop-client/src/components/sidebar/Accounts.tsx
index e1e8c82c7e..423a2175fa 100644
--- a/packages/desktop-client/src/components/sidebar/Accounts.tsx
+++ b/packages/desktop-client/src/components/sidebar/Accounts.tsx
@@ -123,7 +123,7 @@ export function Accounts() {
failed={failedAccounts.has(account.id)}
updated={updatedAccounts.includes(account.id)}
to={getAccountPath(account)}
- query={queries.accountBalance(account)}
+ query={queries.accountBalance(account.id)}
onDragChange={onDragChange}
onDrop={onReorder}
outerStyle={makeDropPadding(i)}
@@ -154,7 +154,7 @@ export function Accounts() {
failed={failedAccounts.has(account.id)}
updated={updatedAccounts.includes(account.id)}
to={getAccountPath(account)}
- query={queries.accountBalance(account)}
+ query={queries.accountBalance(account.id)}
onDragChange={onDragChange}
onDrop={onReorder}
outerStyle={makeDropPadding(i)}
@@ -181,7 +181,7 @@ export function Accounts() {
name={account.name}
account={account}
to={getAccountPath(account)}
- query={queries.accountBalance(account)}
+ query={queries.accountBalance(account.id)}
onDragChange={onDragChange}
onDrop={onReorder}
/>
diff --git a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
index 34b1201ec7..43d4b7efbf 100644
--- a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
+++ b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
@@ -1,7 +1,10 @@
-import { useMemo } from 'react';
+import { useCallback, useMemo } from 'react';
import { usePreviewTransactions } from 'loot-core/client/data-hooks/transactions';
+import { accountBalance } from 'loot-core/client/queries';
+import { groupById } from 'loot-core/shared/util';
import {
+ type ScheduleEntity,
type AccountEntity,
type PayeeEntity,
type TransactionEntity,
@@ -10,14 +13,15 @@ import {
import { useAccounts } from './useAccounts';
import { usePayees } from './usePayees';
+import { useSheetValue } from '@desktop-client/components/spreadsheet/useSheetValue';
+
type UseAccountPreviewTransactionsProps = {
accountId?: AccountEntity['id'] | undefined;
};
-type UseAccountPreviewTransactionsResult = {
- isLoading: ReturnType<typeof usePreviewTransactions>['isLoading'];
- previewTransactions: ReturnType<typeof usePreviewTransactions>['data'];
-};
+type UseAccountPreviewTransactionsResult = ReturnType<
+ typeof usePreviewTransactions
+>;
/**
* Preview transactions for a given account. This will invert the payees, accounts,
@@ -26,43 +30,106 @@ type UseAccountPreviewTransactionsResult = {
export function useAccountPreviewTransactions({
accountId,
}: UseAccountPreviewTransactionsProps): UseAccountPreviewTransactionsResult {
- const { data: originalPreviewTransactions, isLoading } =
- usePreviewTransactions();
const accounts = useAccounts();
+ const accountsById = useMemo(() => groupById(accounts), [accounts]);
const payees = usePayees();
+ const payeesById = useMemo(() => groupById(payees), [payees]);
+
+ const getPayeeByTransferAccount = useCallback(
+ (transferAccountId?: AccountEntity['id']) =>
+ payees.find(p => p.transfer_acct === transferAccountId) || null,
+ [payees],
+ );
+
+ const getTransferAccountByPayee = useCallback(
+ (payeeId?: PayeeEntity['id']) => {
+ if (!payeeId) {
+ return null;
+ }
+
+ const transferAccountId = payeesById[payeeId]?.transfer_acct;
+ if (!transferAccountId) {
+ return null;
+ }
+ return accountsById[transferAccountId];
+ },
+ [accountsById, payeesById],
+ );
+
+ const accountSchedulesFilter = useCallback(
+ (schedule: ScheduleEntity) =>
+ schedule._account === accountId ||
+ getTransferAccountByPayee(schedule._payee)?.id === accountId,
+ [accountId, getTransferAccountByPayee],
+ );
+
+ const accountBalanceValue = useSheetValue<'account', 'balance'>(
+ accountBalance(accountId || ''),
+ );
- const previewTransactions = useMemo(() => {
+ const {
+ previewTransactions: allPreviewTransactions,
+ runningBalances: allRunningBalances,
+ isLoading,
+ error,
+ } = usePreviewTransactions({
+ filter: accountSchedulesFilter,
+ options: {
+ startingBalance: accountBalanceValue ?? 0,
+ },
+ });
+
+ return useMemo(() => {
if (!accountId) {
- return originalPreviewTransactions;
+ return {
+ previewTransactions: [],
+ runningBalances: new Map(),
+ isLoading: false,
+ error: undefined,
+ };
}
- return accountPreview({
+ const previewTransactions = accountPreview({
accountId,
- transactions: originalPreviewTransactions,
- getPayeeByTransferAccount: transferAccountId =>
- payees.find(p => p.transfer_acct === transferAccountId),
- getTransferAccountByPayee: payeeId =>
- accounts.find(
- a => a.id === payees.find(p => p.id === payeeId)?.transfer_acct,
- ),
+ transactions: allPreviewTransactions,
+ getPayeeByTransferAccount,
+ getTransferAccountByPayee,
});
- }, [accountId, accounts, originalPreviewTransactions, payees]);
- return {
+ const transactionIds = new Set(previewTransactions.map(t => t.id));
+ const runningBalances = allRunningBalances;
+ for (const transactionId of runningBalances.keys()) {
+ if (!transactionIds.has(transactionId)) {
+ runningBalances.delete(transactionId);
+ }
+ }
+
+ return {
+ isLoading,
+ previewTransactions,
+ runningBalances,
+ error,
+ };
+ }, [
+ accountId,
+ allPreviewTransactions,
+ allRunningBalances,
+ error,
+ getPayeeByTransferAccount,
+ getTransferAccountByPayee,
isLoading,
- previewTransactions,
- };
+ ]);
}
type AccountPreviewProps = {
accountId?: AccountEntity['id'];
transactions: readonly TransactionEntity[];
getPayeeByTransferAccount: (
- transferAccountId: PayeeEntity['transfer_acct'],
- ) => PayeeEntity | undefined;
+ transferAccountId?: AccountEntity['id'],
+ ) => PayeeEntity | null;
getTransferAccountByPayee: (
- payeeId: TransactionEntity['payee'],
- ) => AccountEntity | undefined;
+ payeeId?: PayeeEntity['id'],
+ ) => AccountEntity | null;
};
function accountPreview({
diff --git a/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts b/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts
index d1028ddbbc..59ac5f2699 100644
--- a/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts
+++ b/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts
@@ -1,47 +1,101 @@
-import { useMemo } from 'react';
+import { useCallback, useMemo } from 'react';
import { usePreviewTransactions } from 'loot-core/client/data-hooks/transactions';
+import { categoryBalance } from 'loot-core/client/queries';
import * as monthUtils from 'loot-core/shared/months';
-import { type CategoryEntity } from 'loot-core/types/models';
+import {
+ type ScheduleEntity,
+ type CategoryEntity,
+} from 'loot-core/types/models';
import { useCategory } from './useCategory';
import { useCategoryScheduleGoalTemplates } from './useCategoryScheduleGoalTemplates';
+import { useSheetValue } from '@desktop-client/components/spreadsheet/useSheetValue';
+
type UseCategoryPreviewTransactionsProps = {
categoryId: CategoryEntity['id'];
month: string;
};
+type UseCategoryPreviewTransactionsResult = ReturnType<
+ typeof usePreviewTransactions
+>;
+
export function useCategoryPreviewTransactions({
categoryId,
month,
-}: UseCategoryPreviewTransactionsProps) {
+}: UseCategoryPreviewTransactionsProps): UseCategoryPreviewTransactionsResult {
const category = useCategory(categoryId);
const { schedules } = useCategoryScheduleGoalTemplates({
category,
});
- const { data: allPreviewTransactions, isLoading } = usePreviewTransactions();
- return useMemo(() => {
- const schedulesToPreview = new Set(
- schedules
- .filter(schedule => monthUtils.getMonth(schedule.next_date) === month)
- .map(schedule => schedule.id),
- );
+ const schedulesToPreview = useMemo(
+ () =>
+ new Set(
+ schedules
+ .filter(schedule => monthUtils.getMonth(schedule.next_date) === month)
+ .map(schedule => schedule.id),
+ ),
+ [month, schedules],
+ );
+ const categoryBalanceValue = useSheetValue<'category', 'balance'>(
+ categoryBalance(categoryId, month),
+ );
+
+ const categorySchedulesFilter = useCallback(
+ (schedule: ScheduleEntity) => schedulesToPreview.has(schedule.id),
+ [schedulesToPreview],
+ );
+
+ const {
+ previewTransactions: allPreviewTransactions,
+ runningBalances: allRunningBalances,
+ isLoading,
+ error,
+ } = usePreviewTransactions({
+ filter: categorySchedulesFilter,
+ options: {
+ startingBalance: categoryBalanceValue ?? 0,
+ },
+ });
+ return useMemo(() => {
if (!category || !schedulesToPreview.size) {
return {
previewTransactions: [],
+ runningBalances: new Map(),
isLoading: false,
+ error: undefined,
};
}
+ const previewTransactions = allPreviewTransactions.filter(
+ transaction =>
+ transaction.schedule && schedulesToPreview.has(transaction.schedule),
+ );
+
+ const transactionIds = new Set(previewTransactions.map(t => t.id));
+ const runningBalances = allRunningBalances;
+ for (const transactionId of runningBalances.keys()) {
+ if (!transactionIds.has(transactionId)) {
+ runningBalances.delete(transactionId);
+ }
+ }
+
return {
- previewTransactions: allPreviewTransactions.filter(
- transaction =>
- transaction.schedule && schedulesToPreview.has(transaction.schedule),
- ),
+ previewTransactions,
+ runningBalances,
isLoading,
+ error,
};
- }, [allPreviewTransactions, category, isLoading, month, schedules]);
+ }, [
+ allPreviewTransactions,
+ allRunningBalances,
+ category,
+ error,
+ isLoading,
+ schedulesToPreview,
+ ]);
}
diff --git a/packages/desktop-client/src/hooks/useCategoryScheduleGoalTemplates.ts b/packages/desktop-client/src/hooks/useCategoryScheduleGoalTemplates.ts
index f8fbfd14ce..f87c421568 100644
--- a/packages/desktop-client/src/hooks/useCategoryScheduleGoalTemplates.ts
+++ b/packages/desktop-client/src/hooks/useCategoryScheduleGoalTemplates.ts
@@ -73,12 +73,22 @@ export function useCategoryScheduleGoalTemplates({
const schedules = allSchedules.filter(s =>
scheduleGoalDefinitions.some(g => g.name === s.name),
);
- const statuses = new Map(
- [...allStatuses].filter(([id]) => schedules.some(s => s.id === id)),
- );
- const statusLabels = new Map(
- [...allStatusLabels].filter(([id]) => schedules.some(s => s.id === id)),
- );
+
+ const scheduleIds = new Set(schedules.map(s => s.id));
+
+ const statuses = allStatuses;
+ for (const scheduleId of statuses.keys()) {
+ if (!scheduleIds.has(scheduleId)) {
+ statuses.delete(scheduleId);
+ }
+ }
+
+ const statusLabels = allStatusLabels;
+ for (const scheduleId of statusLabels.keys()) {
+ if (!scheduleIds.has(scheduleId)) {
+ statusLabels.delete(scheduleId);
+ }
+ }
return {
schedules,
diff --git a/packages/loot-core/src/client/data-hooks/transactions.ts b/packages/loot-core/src/client/data-hooks/transactions.ts
index c5c777017e..3a4cc1aa7c 100644
--- a/packages/loot-core/src/client/data-hooks/transactions.ts
+++ b/packages/loot-core/src/client/data-hooks/transactions.ts
@@ -7,7 +7,7 @@ import debounce from 'lodash/debounce';
import { send } from '../../platform/client/fetch';
import { currentDay, addDays, parseDate } from '../../shared/months';
-import { type QueryState, type Query } from '../../shared/query';
+import { type Query } from '../../shared/query';
import {
getScheduledAmount,
extractScheduleConds,
@@ -26,6 +26,16 @@ import { type PagedQuery, pagedQuery } from '../query-helpers';
import { type ScheduleStatuses, useCachedSchedules } from './schedules';
+// Mirrors the `splits` AQL option from the server
+type TransactionSplitsOption = 'all' | 'inline' | 'grouped' | 'none';
+
+type CalculateRunningBalancesOption =
+ | ((
+ transactions: TransactionEntity[],
+ splits: TransactionSplitsOption,
+ ) => Map<TransactionEntity['id'], IntegerAmount>)
+ | boolean;
+
type UseTransactionsProps = {
/**
* The Query class is immutable so it is important to memoize the query object
@@ -58,12 +68,7 @@ type UseTransactionsProps = {
* a custom `calculateRunningBalances` function should be used instead.
* @default false
*/
- calculateRunningBalances?:
- | ((
- transactions: TransactionEntity[],
- queryState: QueryState,
- ) => Map<TransactionEntity['id'], IntegerAmount>)
- | boolean;
+ calculateRunningBalances?: CalculateRunningBalancesOption;
};
};
@@ -150,9 +155,16 @@ export function useTransactions({
if (!isUnmounted) {
setTransactions(data);
- const calculateFn = getCalculateRunningBalancesFn(optionsRef.current);
+ const calculateFn = getCalculateRunningBalancesFn(
+ optionsRef.current?.calculateRunningBalances,
+ );
if (calculateFn) {
- setRunningBalances(calculateFn(data, query.state));
+ setRunningBalances(
+ calculateFn(
+ data,
+ query.state.tableOptions?.splits as TransactionSplitsOption,
+ ),
+ );
}
setIsLoading(false);
@@ -200,13 +212,27 @@ export function useTransactions({
};
}
+type UsePreviewTransactionsProps = {
+ filter?: (schedule: ScheduleEntity) => boolean;
+ options?: {
+ /**
+ * The starting balance to start the running balance calculation from.
+ */
+ startingBalance?: IntegerAmount;
+ };
+};
+
type UsePreviewTransactionsResult = {
- data: ReadonlyArray<TransactionEntity>;
+ previewTransactions: ReadonlyArray<TransactionEntity>;
+ runningBalances: Map<TransactionEntity['id'], IntegerAmount>;
isLoading: boolean;
error?: Error;
};
-export function usePreviewTransactions(): UsePreviewTransactionsResult {
+export function usePreviewTransactions({
+ filter,
+ options,
+}: UsePreviewTransactionsProps = {}): UsePreviewTransactionsResult {
const [previewTransactions, setPreviewTransactions] = useState<
TransactionEntity[]
>([]);
@@ -218,18 +244,26 @@ export function usePreviewTransactions(): UsePreviewTransactionsResult {
} = 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 [];
}
- // Kick off an async rules application
- const schedulesForPreview = schedules.filter(s =>
- isForPreview(s, statuses),
- );
+ const schedulesForPreview = schedules
+ .filter(s => isForPreview(s, statuses))
+ .filter(filter ? filter : () => true);
const today = d.startOfDay(parseDate(currentDay()));
@@ -297,7 +331,7 @@ export function usePreviewTransactions(): UsePreviewTransactionsResult {
parseDate(b.date).getTime() - parseDate(a.date).getTime() ||
a.amount - b.amount,
);
- }, [isSchedulesLoading, schedules, statuses, upcomingLength]);
+ }, [filter, isSchedulesLoading, schedules, statuses, upcomingLength]);
useEffect(() => {
let isUnmounted = false;
@@ -313,6 +347,7 @@ export function usePreviewTransactions(): UsePreviewTransactionsResult {
Promise.all(
scheduleTransactions.map(transaction =>
+ // Kick off an async rules application
send('rules-run', { transaction }),
),
)
@@ -331,7 +366,22 @@ export function usePreviewTransactions(): UsePreviewTransactionsResult {
),
}));
- setPreviewTransactions(ungroupTransactions(withDefaults));
+ 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);
}
})
@@ -349,7 +399,8 @@ export function usePreviewTransactions(): UsePreviewTransactionsResult {
const returnError = error || scheduleQueryError;
return {
- data: previewTransactions,
+ previewTransactions,
+ runningBalances,
isLoading: isLoading || isSchedulesLoading,
...(returnError && { error: returnError }),
};
@@ -411,9 +462,8 @@ function isForPreview(schedule: ScheduleEntity, statuses: ScheduleStatuses) {
}
function getCalculateRunningBalancesFn(
- options: UseTransactionsProps['options'],
+ calculateRunningBalances: CalculateRunningBalancesOption = false,
) {
- const calculateRunningBalances = options?.calculateRunningBalances ?? false;
return calculateRunningBalances === true
? calculateRunningBalancesBottomUp
: typeof calculateRunningBalances === 'function'
@@ -421,14 +471,14 @@ function getCalculateRunningBalancesFn(
: undefined;
}
-function calculateRunningBalancesBottomUp(
+export function calculateRunningBalancesBottomUp(
transactions: TransactionEntity[],
- queryState: QueryState,
+ splits: TransactionSplitsOption,
+ startingBalance: IntegerAmount = 0,
) {
return (
transactions
.filter(t => {
- const splits = queryState.tableOptions?.splits;
switch (splits) {
case 'all':
// Only calculate parent/non-split amounts
@@ -445,8 +495,8 @@ function calculateRunningBalancesBottomUp(
const previousTransactionIndex = index + 1;
if (previousTransactionIndex >= arr.length) {
// This is the last transaction in the list,
- // so we set the running balance to the amount of the transaction
- acc.set(transaction.id, transaction.amount);
+ // 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];
diff --git a/packages/loot-core/src/client/queries.ts b/packages/loot-core/src/client/queries.ts
index 83162d66c2..c0c4256b54 100644
--- a/packages/loot-core/src/client/queries.ts
+++ b/packages/loot-core/src/client/queries.ts
@@ -134,31 +134,31 @@ export function transactionsSearch(
});
}
-export function accountBalance(acct: AccountEntity) {
+export function accountBalance(accountId: AccountEntity['id']) {
return {
- name: accountParametrizedField('balance')(acct.id),
+ name: accountParametrizedField('balance')(accountId),
query: q('transactions')
- .filter({ account: acct.id })
+ .filter({ account: accountId })
.options({ splits: 'none' })
.calculate({ $sum: '$amount' }),
} satisfies Binding<'account', 'balance'>;
}
-export function accountBalanceCleared(acct: AccountEntity) {
+export function accountBalanceCleared(accountId: AccountEntity['id']) {
return {
- name: accountParametrizedField('balanceCleared')(acct.id),
+ name: accountParametrizedField('balanceCleared')(accountId),
query: q('transactions')
- .filter({ account: acct.id, cleared: true })
+ .filter({ account: accountId, cleared: true })
.options({ splits: 'none' })
.calculate({ $sum: '$amount' }),
} satisfies Binding<'account', 'balanceCleared'>;
}
-export function accountBalanceUncleared(acct: AccountEntity) {
+export function accountBalanceUncleared(accountId: AccountEntity['id']) {
return {
- name: accountParametrizedField('balanceUncleared')(acct.id),
+ name: accountParametrizedField('balanceUncleared')(accountId),
query: q('transactions')
- .filter({ account: acct.id, cleared: false })
+ .filter({ account: accountId, cleared: false })
.options({ splits: 'none' })
.calculate({ $sum: '$amount' }),
} satisfies Binding<'account', 'balanceUncleared'>;
@@ -200,12 +200,15 @@ export function closedAccountBalance() {
} satisfies Binding<'account', 'closed-accounts-balance'>;
}
-export function categoryBalance(category: CategoryEntity, month: string) {
+export function categoryBalance(
+ categoryId: CategoryEntity['id'],
+ month: string,
+) {
return {
- name: categoryParametrizedField('balance')(category.id),
+ name: categoryParametrizedField('balance')(categoryId),
query: q('transactions')
.filter({
- category: category.id,
+ category: categoryId,
date: { $transform: '$month', $eq: month },
})
.options({ splits: 'inline' })
@@ -214,14 +217,14 @@ export function categoryBalance(category: CategoryEntity, month: string) {
}
export function categoryBalanceCleared(
- category: CategoryEntity,
+ categoryId: CategoryEntity['id'],
month: string,
) {
return {
- name: categoryParametrizedField('balanceCleared')(category.id),
+ name: categoryParametrizedField('balanceCleared')(categoryId),
query: q('transactions')
.filter({
- category: category.id,
+ category: categoryId,
date: { $transform: '$month', $eq: month },
cleared: true,
})
@@ -231,14 +234,14 @@ export function categoryBalanceCleared(
}
export function categoryBalanceUncleared(
- category: CategoryEntity,
+ categoryId: CategoryEntity['id'],
month: string,
) {
return {
- name: categoryParametrizedField('balanceUncleared')(category.id),
+ name: categoryParametrizedField('balanceUncleared')(categoryId),
query: q('transactions')
.filter({
- category: category.id,
+ category: categoryId,
date: { $transform: '$month', $eq: month },
cleared: false,
})
diff --git a/upcoming-release-notes/4994.md b/upcoming-release-notes/4994.md
new file mode 100644
index 0000000000..186b11afa3
--- /dev/null
+++ b/upcoming-release-notes/4994.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [joel-jeremy]
+---
+
+Add runningBalances to usePreviewTransactions and an option to set the starting balance to start running balance calculation from