Skip to content

A local-first personal finance app

Fix wrong scheduled transfer payment direction on PWA (#3402)

Joel Jeremy Marquez881410bc74f6
diff --git a/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-1-chromium-linux.png b/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-1-chromium-linux.png
index d91968278e..cb84ec5339 100644
Binary files a/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-1-chromium-linux.png and b/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-1-chromium-linux.png differ
diff --git a/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-2-chromium-linux.png b/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-2-chromium-linux.png
index 48800ef95f..2e33859da8 100644
Binary files a/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-2-chromium-linux.png and b/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-2-chromium-linux.png differ
diff --git a/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-3-chromium-linux.png b/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-3-chromium-linux.png
index f2b6f3b80e..03cc182961 100644
Binary files a/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-3-chromium-linux.png and b/packages/desktop-client/e2e/accounts.mobile.test.js-snapshots/Mobile-Accounts-opens-individual-account-page-and-checks-that-filtering-is-working-3-chromium-linux.png differ
diff --git a/packages/desktop-client/src/components/accounts/Account.tsx b/packages/desktop-client/src/components/accounts/Account.tsx
index 1771ca3168..65783c0891 100644
--- a/packages/desktop-client/src/components/accounts/Account.tsx
+++ b/packages/desktop-client/src/components/accounts/Account.tsx
@@ -5,6 +5,7 @@ import React, {
createRef,
useMemo,
type ReactElement,
+ useEffect,
} from 'react';
import { Trans } from 'react-i18next';
import { useSelector } from 'react-redux';
@@ -30,7 +31,6 @@ import {
import { send, listen } from 'loot-core/src/platform/client/fetch';
import { currentDay } from 'loot-core/src/shared/months';
import { q, type Query } from 'loot-core/src/shared/query';
-import { getScheduledAmount } from 'loot-core/src/shared/schedules';
import {
updateTransaction,
realizeTempTransactions,
@@ -50,6 +50,7 @@ import {
type TransactionFilterEntity,
} from 'loot-core/src/types/models';
+import { useAccountPreviewTransactions } from '../../hooks/useAccountPreviewTransactions';
import { useAccounts } from '../../hooks/useAccounts';
import { useActions } from '../../hooks/useActions';
import { useCategories } from '../../hooks/useCategories';
@@ -57,7 +58,6 @@ import { useDateFormat } from '../../hooks/useDateFormat';
import { useFailedAccounts } from '../../hooks/useFailedAccounts';
import { useLocalPref } from '../../hooks/useLocalPref';
import { usePayees } from '../../hooks/usePayees';
-import { usePreviewTransactions } from '../../hooks/usePreviewTransactions';
import {
SelectedProviderWithItems,
type Actions,
@@ -147,7 +147,6 @@ type AllTransactionsProps = {
transactions: TransactionEntity[],
balances: Record<string, { balance: number }> | null,
) => ReactElement;
- collapseTransactions: (ids: string[]) => void;
};
function AllTransactions({
@@ -157,14 +156,24 @@ function AllTransactions({
showBalances,
filtered,
children,
- collapseTransactions,
}: AllTransactionsProps) {
const accountId = account?.id;
- const prependTransactions: (TransactionEntity & { _inverse?: boolean })[] =
- usePreviewTransactions(collapseTransactions).map(trans => ({
- ...trans,
- _inverse: accountId ? accountId !== trans.account : false,
- }));
+ const { dispatch: splitsExpandedDispatch } = useSplitsExpanded();
+ const { previewTransactions, isLoading: isPreviewTransactionsLoading } =
+ useAccountPreviewTransactions({ accountId });
+
+ useEffect(() => {
+ if (!isPreviewTransactionsLoading) {
+ splitsExpandedDispatch({
+ type: 'close-splits',
+ ids: previewTransactions.filter(t => t.is_parent).map(t => t.id),
+ });
+ }
+ }, [
+ isPreviewTransactionsLoading,
+ previewTransactions,
+ splitsExpandedDispatch,
+ ]);
transactions ??= [];
@@ -184,29 +193,26 @@ function AllTransactions({
}
// Reverse so we can calculate from earliest upcoming schedule.
- const scheduledBalances = [...prependTransactions]
+ const previewBalances = [...previewTransactions]
.reverse()
- .map(scheduledTransaction => {
- const amount =
- (scheduledTransaction._inverse ? -1 : 1) *
- getScheduledAmount(scheduledTransaction.amount);
+ .map(previewTransaction => {
return {
// TODO: fix me
// eslint-disable-next-line react-hooks/exhaustive-deps
- balance: (runningBalance += amount),
- id: scheduledTransaction.id,
+ balance: (runningBalance += previewTransaction.amount),
+ id: previewTransaction.id,
};
});
- return groupById(scheduledBalances);
- }, [showBalances, prependTransactions, runningBalance]);
+ return groupById(previewBalances);
+ }, [showBalances, previewTransactions, runningBalance]);
const allTransactions = useMemo(() => {
// Don't prepend scheduled transactions if we are filtering
- if (!filtered && prependTransactions.length > 0) {
- return prependTransactions.concat(transactions);
+ if (!filtered && previewTransactions.length > 0) {
+ return previewTransactions.concat(transactions);
}
return transactions;
- }, [filtered, prependTransactions, transactions]);
+ }, [filtered, previewTransactions, transactions]);
const allBalances = useMemo(() => {
// Don't prepend scheduled transactions if we are filtering
@@ -216,7 +222,7 @@ function AllTransactions({
return balances;
}, [filtered, prependBalances, balances]);
- if (!prependTransactions?.length || filtered) {
+ if (!previewTransactions?.length || filtered) {
return children(transactions, balances);
}
return children(allTransactions, allBalances);
@@ -1669,9 +1675,6 @@ class AccountInternal extends PureComponent<
balances={balances}
showBalances={showBalances}
filtered={transactionsFiltered}
- collapseTransactions={ids =>
- this.props.splitsExpandedDispatch({ type: 'close-splits', ids })
- }
>
{(allTransactions, allBalances) => (
<SelectedProviderWithItems
diff --git a/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx b/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
index 7c804fb8a0..1d72fea856 100644
--- a/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
+++ b/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
@@ -22,7 +22,6 @@ import {
SchedulesProvider,
} from 'loot-core/client/data-hooks/schedules';
import {
- usePreviewTransactions,
useTransactions,
useTransactionsSearch,
} from 'loot-core/client/data-hooks/transactions';
@@ -35,6 +34,7 @@ import {
type TransactionEntity,
} from 'loot-core/types/models';
+import { useAccountPreviewTransactions } from '../../../hooks/useAccountPreviewTransactions';
import { useDateFormat } from '../../../hooks/useDateFormat';
import { useFailedAccounts } from '../../../hooks/useFailedAccounts';
import { useNavigate } from '../../../hooks/useNavigate';
@@ -239,7 +239,9 @@ function TransactionListWithPreviews({
query: transactionsQuery,
});
- const { data: previewTransactions } = usePreviewTransactions();
+ const { previewTransactions } = useAccountPreviewTransactions({
+ accountId: account?.id || '',
+ });
const dateFormat = useDateFormat() || 'MM/dd/yyyy';
const dispatch = useDispatch();
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.jsx b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.jsx
index d23c88b743..cbe373495e 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.jsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.jsx
@@ -64,6 +64,7 @@ import { MobilePageHeader, Page } from '../../Page';
import { AmountInput } from '../../util/AmountInput';
import { MobileBackButton } from '../MobileBackButton';
import { FieldLabel, TapField, InputField, ToggleField } from '../MobileForms';
+import { getPrettyPayee } from '../utils';
import { FocusableAmountInput } from './FocusableAmountInput';
@@ -71,18 +72,6 @@ function getFieldName(transactionId, field) {
return `${field}-${transactionId}`;
}
-export function getDescriptionPretty(transaction, payee, transferAcct) {
- const { amount } = transaction;
-
- if (transferAcct) {
- return `Transfer ${amount > 0 ? 'from' : 'to'} ${transferAcct.name}`;
- } else if (payee) {
- return payee.name;
- }
-
- return '';
-}
-
function serializeTransaction(transaction, dateFormat) {
const { date, amount } = transaction;
return {
@@ -291,7 +280,8 @@ const ChildTransactionEdit = forwardRef(
amountFocused,
amountSign,
getCategory,
- getPrettyPayee,
+ getPayee,
+ getTransferAccount,
isOffBudget,
isBudgetTransfer,
onEditField,
@@ -302,6 +292,11 @@ const ChildTransactionEdit = forwardRef(
) => {
const { editingField, onRequestActiveEdit, onClearActiveEdit } =
useSingleActiveEditForm();
+ const prettyPayee = getPrettyPayee({
+ transaction,
+ payee: getPayee(transaction),
+ transferAccount: getTransferAccount(transaction),
+ });
return (
<View
innerRef={ref}
@@ -325,7 +320,7 @@ const ChildTransactionEdit = forwardRef(
editingField &&
editingField !== getFieldName(transaction.id, 'payee')
}
- value={getPrettyPayee(transaction)}
+ value={prettyPayee}
onClick={() => onEditField(transaction.id, 'payee')}
data-testid={`payee-field-${transaction.id}`}
/>
@@ -503,7 +498,7 @@ const TransactionEditInner = memo(function TransactionEditInner({
[payeesById],
);
- const getTransferAcct = useCallback(
+ const getTransferAccount = useCallback(
trans => {
const payee = trans && getPayee(trans);
return payee?.transfer_acct && accountsById?.[payee.transfer_acct];
@@ -511,24 +506,12 @@ const TransactionEditInner = memo(function TransactionEditInner({
[accountsById, getPayee],
);
- const getPrettyPayee = useCallback(
- trans => {
- if (trans?.is_parent) {
- return 'Split';
- }
- const transPayee = trans && getPayee(trans);
- const transTransferAcct = trans && getTransferAcct(trans);
- return getDescriptionPretty(trans, transPayee, transTransferAcct);
- },
- [getPayee, getTransferAcct],
- );
-
const isBudgetTransfer = useCallback(
trans => {
- const transferAcct = trans && getTransferAcct(trans);
+ const transferAcct = trans && getTransferAccount(trans);
return transferAcct && !transferAcct.offbudget;
},
- [getTransferAcct],
+ [getTransferAccount],
);
const getCategory = useCallback(
@@ -759,11 +742,11 @@ const TransactionEditInner = memo(function TransactionEditInner({
const account = getAccount(transaction);
const isOffBudget = account && !!account.offbudget;
- const title = getDescriptionPretty(
+ const title = getPrettyPayee({
transaction,
- getPayee(transaction),
- getTransferAcct(transaction),
- );
+ payee: getPayee(transaction),
+ transferAccount: getTransferAccount(transaction),
+ });
const transactionDate = parseDate(transaction.date, dateFormat, new Date());
const dateDefaultValue = monthUtils.dayFromDate(transactionDate);
@@ -834,7 +817,7 @@ const TransactionEditInner = memo(function TransactionEditInner({
fontWeight: 300,
}),
}}
- value={getPrettyPayee(transaction)}
+ value={title}
disabled={
editingField &&
editingField !== getFieldName(transaction.id, 'payee')
@@ -882,7 +865,8 @@ const TransactionEditInner = memo(function TransactionEditInner({
}}
isOffBudget={isOffBudget}
getCategory={getCategory}
- getPrettyPayee={getPrettyPayee}
+ getPayee={getPayee}
+ getTransferAccount={getTransferAccount}
isBudgetTransfer={isBudgetTransfer}
onUpdate={onUpdateInner}
onEditField={onEditFieldInner}
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
index a929d96f41..f46037d140 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
@@ -12,7 +12,6 @@ import {
useLongPress,
} from '@react-aria/interactions';
-import { getScheduledAmount } from 'loot-core/src/shared/schedules';
import { isPreviewId } from 'loot-core/src/shared/transactions';
import { integerToCurrency } from 'loot-core/src/shared/util';
import { type TransactionEntity } from 'loot-core/types/models';
@@ -32,8 +31,9 @@ import { Button } from '../../common/Button2';
import { Text } from '../../common/Text';
import { TextOneLine } from '../../common/TextOneLine';
import { View } from '../../common/View';
+import { getPrettyPayee } from '../utils';
-import { lookupName, getDescriptionPretty, Status } from './TransactionEdit';
+import { lookupName, Status } from './TransactionEdit';
const ROW_HEIGHT = 60;
@@ -56,7 +56,7 @@ export function TransactionListItem({
const payee = usePayee(transaction?.payee || '');
const account = useAccount(transaction?.account || '');
- const transferAcct = useAccount(payee?.transfer_acct || '');
+ const transferAccount = useAccount(payee?.transfer_acct || '');
const isPreview = isPreviewId(transaction?.id || '');
const newTransactions = useSelector(state => state.queries.newTransactions);
@@ -84,32 +84,25 @@ export function TransactionListItem({
const {
id,
- amount: originalAmount,
+ amount,
category: categoryId,
cleared: isCleared,
reconciled: isReconciled,
is_parent: isParent,
is_child: isChild,
- schedule,
+ schedule: scheduleId,
} = transaction;
const isAdded = newTransactions.includes(id);
-
- let amount = originalAmount;
- if (isPreview) {
- amount = getScheduledAmount(amount);
- }
-
const categoryName = lookupName(categories, categoryId);
-
- const prettyDescription = getDescriptionPretty(
+ const prettyPayee = getPrettyPayee({
transaction,
payee,
- transferAcct,
- );
+ transferAccount,
+ });
const specialCategory = account?.offbudget
? 'Off Budget'
- : transferAcct && !transferAcct.offbudget
+ : transferAccount && !transferAccount.offbudget
? 'Transfer'
: isParent
? 'Split'
@@ -169,7 +162,7 @@ export function TransactionListItem({
>
<View>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
- {schedule && (
+ {scheduleId && (
<SvgArrowsSynchronize
style={{
width: 12,
@@ -183,13 +176,13 @@ export function TransactionListItem({
style={{
...textStyle,
fontWeight: isAdded ? '600' : '400',
- ...(prettyDescription === '' && {
+ ...(prettyPayee === '' && {
color: theme.tableTextLight,
fontStyle: 'italic',
}),
}}
>
- {prettyDescription || 'Empty'}
+ {prettyPayee || '(No payee)'}
</TextOneLine>
</View>
{isPreview ? (
diff --git a/packages/desktop-client/src/components/mobile/utils.ts b/packages/desktop-client/src/components/mobile/utils.ts
new file mode 100644
index 0000000000..db935fd748
--- /dev/null
+++ b/packages/desktop-client/src/components/mobile/utils.ts
@@ -0,0 +1,31 @@
+import {
+ type AccountEntity,
+ type PayeeEntity,
+ type TransactionEntity,
+} from 'loot-core/types/models';
+
+type GetPrettyPayeeProps = {
+ transaction?: TransactionEntity;
+ payee?: PayeeEntity;
+ transferAccount?: AccountEntity;
+};
+
+export function getPrettyPayee({
+ transaction,
+ payee,
+ transferAccount,
+}: GetPrettyPayeeProps) {
+ if (!transaction) {
+ return '';
+ }
+
+ if (transferAccount) {
+ return `Transfer ${transaction?.amount > 0 ? 'from' : 'to'} ${transferAccount.name}`;
+ } else if (transaction.is_parent) {
+ return 'Split';
+ } else if (payee) {
+ return payee.name;
+ }
+
+ return '';
+}
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.jsx b/packages/desktop-client/src/components/transactions/TransactionsTable.jsx
index 5f0f8334ff..152bed07a8 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.jsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.jsx
@@ -31,7 +31,6 @@ import {
import { evalArithmetic } from 'loot-core/src/shared/arithmetic';
import { currentDay } from 'loot-core/src/shared/months';
import * as monthUtils from 'loot-core/src/shared/months';
-import { getScheduledAmount } from 'loot-core/src/shared/schedules';
import {
splitTransaction,
updateTransaction,
@@ -94,11 +93,7 @@ function getDisplayValue(obj, name) {
}
function serializeTransaction(transaction, showZeroInDeposit) {
- let { amount, date } = transaction;
-
- if (isPreviewId(transaction.id)) {
- amount = (transaction._inverse ? -1 : 1) * getScheduledAmount(amount);
- }
+ const { amount, date: originalDate } = transaction;
let debit = amount < 0 ? -amount : null;
let credit = amount > 0 ? amount : null;
@@ -111,6 +106,7 @@ function serializeTransaction(transaction, showZeroInDeposit) {
}
}
+ let date = originalDate;
// Validate the date format
if (!isDateValid(parseISO(date))) {
// Be a little forgiving if the date isn't valid. This at least
@@ -676,7 +672,13 @@ function PayeeCell({
isCreatingPayee.current = false;
}
}}
- formatter={() => getPayeePretty(transaction, payee, transferAccount)}
+ formatter={() => {
+ const payeeName = getPayeePretty(transaction, payee, transferAccount);
+ if (!payeeName && isPreview) {
+ return '(No payee)';
+ }
+ return payeeName;
+ }}
unexposedContent={props => {
const payeeName = (
<UnexposedCellContent
@@ -750,6 +752,16 @@ function PayeeCell({
);
}
+const payeeIconButtonStyle = {
+ marginLeft: -5,
+ marginRight: 2,
+ width: 23,
+ height: 23,
+ color: 'inherit',
+};
+const scheduleIconStyle = { width: 13, height: 13 };
+const transferIconStyle = { width: 10, height: 10 };
+
function PayeeIcons({
transaction,
transferAccount,
@@ -757,22 +769,6 @@ function PayeeIcons({
onNavigateToSchedule,
}) {
const scheduleId = transaction.schedule;
-
- const buttonStyle = useMemo(
- () => ({
- marginLeft: -5,
- marginRight: 2,
- width: 23,
- height: 23,
- color: 'inherit',
- }),
- [],
- );
-
- const scheduleIconStyle = useMemo(() => ({ width: 13, height: 13 }), []);
-
- const transferIconStyle = useMemo(() => ({ width: 10, height: 10 }), []);
-
const { isLoading, schedules = [] } = useCachedSchedules();
if (isLoading) {
@@ -787,6 +783,7 @@ function PayeeIcons({
}
const recurring = schedule && schedule._date && !!schedule._date.frequency;
+ const isDeposit = transaction.amount > 0;
return (
<>
@@ -794,7 +791,7 @@ function PayeeIcons({
<Button
variant="bare"
aria-label="See schedule details"
- style={buttonStyle}
+ style={payeeIconButtonStyle}
onPress={() => {
onNavigateToSchedule(scheduleId);
}}
@@ -810,14 +807,14 @@ function PayeeIcons({
<Button
variant="bare"
aria-label="See transfer account"
- style={buttonStyle}
+ style={payeeIconButtonStyle}
onPress={() => {
if (!isTemporaryId(transaction.id)) {
onNavigateToTransferAccount(transferAccount.id);
}
}}
>
- {(transaction._inverse ? -1 : 1) * transaction.amount > 0 ? (
+ {isDeposit ? (
<SvgLeftArrow2 style={transferIconStyle} />
) : (
<SvgRightArrow2 style={transferIconStyle} />
@@ -1010,7 +1007,6 @@ const Transaction = memo(function Transaction({
reconciled,
is_parent: isParent,
_unmatched = false,
- _inverse = false,
} = transaction;
// Join in some data
@@ -1028,9 +1024,7 @@ const Transaction = memo(function Transaction({
const backgroundFocus = focusedField === 'select';
const amountStyle = hideFraction ? { letterSpacing: -0.5 } : null;
- const runningBalance = !isTemporaryId(id)
- ? balance
- : balance + (_inverse ? -1 : 1) * amount;
+ const runningBalance = !isTemporaryId(id) ? balance : balance + amount;
// Ok this entire logic is a dirty, dirty hack.. but let me explain.
// Problem: the split-error Popover (which has the buttons to distribute/add split)
@@ -2164,13 +2158,8 @@ export const TransactionTable = forwardRef((props, ref) => {
}
const payee = t.payee && payees[t.payee];
- let transferAccount;
- if (t._inverse) {
- transferAccount = t.account && accounts[t.account];
- } else {
- transferAccount =
- payee?.transfer_acct && accounts[payee.transfer_acct];
- }
+ const transferAccount =
+ payee?.transfer_acct && accounts[payee.transfer_acct];
return [t.id, transferAccount || null];
}),
);
diff --git a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
new file mode 100644
index 0000000000..04b630f43d
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
@@ -0,0 +1,93 @@
+import { useMemo } from 'react';
+
+import { usePreviewTransactions } from 'loot-core/client/data-hooks/transactions';
+import {
+ type AccountEntity,
+ type PayeeEntity,
+ type TransactionEntity,
+} from 'loot-core/types/models';
+
+import { useAccounts } from './useAccounts';
+import { usePayees } from './usePayees';
+
+type UseAccountPreviewTransactionsProps = {
+ accountId: AccountEntity['id'];
+};
+
+type UseAccountPreviewTransactionsResult = {
+ isLoading: ReturnType<typeof usePreviewTransactions>['isLoading'];
+ previewTransactions: ReturnType<typeof usePreviewTransactions>['data'];
+};
+
+/**
+ * Preview transactions for a given account. This will invert the payees, accounts,
+ * and amounts depending on which account the preview transactions are being viewed from.
+ */
+export function useAccountPreviewTransactions({
+ accountId,
+}: UseAccountPreviewTransactionsProps): UseAccountPreviewTransactionsResult {
+ const { data: originalPreviewTransactions, isLoading } =
+ usePreviewTransactions();
+ const accounts = useAccounts();
+ const payees = usePayees();
+
+ const previewTransactions = useMemo(() => {
+ if (!accountId || isLoading) {
+ return [];
+ }
+ return 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,
+ ),
+ });
+ }, [accountId, accounts, isLoading, originalPreviewTransactions, payees]);
+
+ return { isLoading, previewTransactions };
+}
+
+type AccountPreviewProps = {
+ accountId?: AccountEntity['id'];
+ transactions: readonly TransactionEntity[];
+ getPayeeByTransferAccount: (
+ transferAccountId: PayeeEntity['transfer_acct'],
+ ) => PayeeEntity | undefined;
+ getTransferAccountByPayee: (
+ payeeId: TransactionEntity['payee'],
+ ) => AccountEntity | undefined;
+};
+
+function accountPreview({
+ accountId,
+ transactions,
+ getPayeeByTransferAccount,
+ getTransferAccountByPayee,
+}: AccountPreviewProps): TransactionEntity[] {
+ return transactions.map(transaction => {
+ const inverse = transaction.account !== accountId;
+ return {
+ ...transaction,
+ amount: inverse ? -transaction.amount : transaction.amount,
+ payee: inverse
+ ? getPayeeByTransferAccount(transaction.account)?.id || ''
+ : transaction.payee,
+ account: inverse
+ ? getTransferAccountByPayee(transaction.payee)?.id || ''
+ : transaction.account,
+ subtransactions: transaction.subtransactions?.map(st => ({
+ ...st,
+ amount: inverse ? -st.amount : st.amount,
+ payee: inverse
+ ? getPayeeByTransferAccount(st.account)?.id || ''
+ : st.payee,
+ account: inverse
+ ? getTransferAccountByPayee(st.payee)?.id || ''
+ : st.account,
+ })),
+ };
+ });
+}
diff --git a/packages/desktop-client/src/hooks/usePreviewTransactions.ts b/packages/desktop-client/src/hooks/usePreviewTransactions.ts
deleted file mode 100644
index 4deba06145..0000000000
--- a/packages/desktop-client/src/hooks/usePreviewTransactions.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { useState } from 'react';
-
-import {
- type ScheduleStatuses,
- useCachedSchedules,
-} from 'loot-core/client/data-hooks/schedules';
-import { send } from 'loot-core/platform/client/fetch';
-import { ungroupTransactions } from 'loot-core/shared/transactions';
-import {
- type TransactionEntity,
- type ScheduleEntity,
-} from 'loot-core/types/models';
-
-import { usePrevious } from './usePrevious';
-
-/**
- * @deprecated Please use `usePreviewTransactions` hook from `loot-core/client/data-hooks/transactions` instead.
- */
-export function usePreviewTransactions(
- collapseTransactions?: (ids: string[]) => void,
-) {
- const [previewTransactions, setPreviewTransactions] = useState<
- TransactionEntity[]
- >([]);
-
- const scheduleData = useCachedSchedules();
- const previousScheduleData = usePrevious(scheduleData);
-
- if (scheduleData.isLoading) {
- return [];
- }
-
- if (scheduleData && scheduleData !== previousScheduleData) {
- // Kick off an async rules application
- const schedules = scheduleData.schedules.filter(s =>
- isForPreview(s, scheduleData.statuses),
- );
-
- const baseTrans = schedules.map(schedule => ({
- id: 'preview/' + schedule.id,
- payee: schedule._payee,
- account: schedule._account,
- amount: schedule._amount,
- date: schedule.next_date,
- schedule: schedule.id,
- }));
-
- Promise.all(
- baseTrans.map(transaction => send('rules-run', { transaction })),
- ).then(newTrans => {
- const withDefaults = newTrans.map(t => ({
- ...t,
- category: scheduleData.statuses.get(t.schedule),
- schedule: t.schedule,
- subtransactions: t.subtransactions?.map((st: TransactionEntity) => ({
- ...st,
- id: 'preview/' + st.id,
- schedule: t.schedule,
- })),
- }));
- setPreviewTransactions(ungroupTransactions(withDefaults));
- if (collapseTransactions) {
- collapseTransactions(withDefaults.map(t => t.id));
- }
- });
- }
-
- return previewTransactions;
-}
-
-function isForPreview(schedule: ScheduleEntity, statuses: ScheduleStatuses) {
- const status = statuses.get(schedule.id);
- return (
- !schedule.completed &&
- (status === 'due' || status === 'upcoming' || status === 'missed')
- );
-}
diff --git a/packages/loot-core/src/client/data-hooks/schedules.tsx b/packages/loot-core/src/client/data-hooks/schedules.tsx
index 612ff885a3..6207b6304a 100644
--- a/packages/loot-core/src/client/data-hooks/schedules.tsx
+++ b/packages/loot-core/src/client/data-hooks/schedules.tsx
@@ -66,7 +66,7 @@ type UseSchedulesResult = ScheduleData & {
export function useSchedules({
query,
}: UseSchedulesProps = {}): UseSchedulesResult {
- const [isLoading, setIsLoading] = useState(false);
+ const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | undefined>(undefined);
const [data, setData] = useState<ScheduleData>({
schedules: [],
diff --git a/packages/loot-core/src/client/data-hooks/transactions.ts b/packages/loot-core/src/client/data-hooks/transactions.ts
index 81669004c6..60ec93e1f2 100644
--- a/packages/loot-core/src/client/data-hooks/transactions.ts
+++ b/packages/loot-core/src/client/data-hooks/transactions.ts
@@ -4,6 +4,7 @@ import debounce from 'lodash/debounce';
import { send } from '../../platform/client/fetch';
import { type Query } from '../../shared/query';
+import { getScheduledAmount } from '../../shared/schedules';
import { ungroupTransactions } from '../../shared/transactions';
import {
type ScheduleEntity,
@@ -33,7 +34,7 @@ export function useTransactions({
query,
options = { pageCount: 50 },
}: UseTransactionsProps): UseTransactionsResult {
- const [isLoading, setIsLoading] = useState(false);
+ const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | undefined>(undefined);
const [transactions, setTransactions] = useState<
ReadonlyArray<TransactionEntity>
@@ -112,7 +113,7 @@ export function usePreviewTransactions(): UsePreviewTransactionsResult {
schedules,
statuses,
} = useCachedSchedules();
- const [isLoading, setIsLoading] = useState(false);
+ const [isLoading, setIsLoading] = useState(isSchedulesLoading);
const [error, setError] = useState<Error | undefined>(undefined);
const scheduleTransactions = useMemo(() => {
@@ -129,7 +130,7 @@ export function usePreviewTransactions(): UsePreviewTransactionsResult {
id: 'preview/' + schedule.id,
payee: schedule._payee,
account: schedule._account,
- amount: schedule._amount,
+ amount: getScheduledAmount(schedule._amount),
date: schedule.next_date,
schedule: schedule.id,
}));
diff --git a/packages/loot-core/src/client/query-hooks.ts b/packages/loot-core/src/client/query-hooks.ts
index 774a38ac64..e5ea7449dc 100644
--- a/packages/loot-core/src/client/query-hooks.ts
+++ b/packages/loot-core/src/client/query-hooks.ts
@@ -21,12 +21,12 @@ export function useQuery<Response = unknown>(
const query = useMemo(makeQuery, dependencies);
const [data, setData] = useState<ReadonlyArray<Response> | null>(null);
- const [isLoading, setIsLoading] = useState(query !== null);
+ const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | undefined>(undefined);
useEffect(() => {
setError(query === null ? new Error('Query is null') : undefined);
- setIsLoading(query !== null);
+ setIsLoading(!!query);
if (!query) {
return;
diff --git a/packages/loot-core/src/shared/schedules.ts b/packages/loot-core/src/shared/schedules.ts
index 42f88b930f..b1b0b99116 100644
--- a/packages/loot-core/src/shared/schedules.ts
+++ b/packages/loot-core/src/shared/schedules.ts
@@ -272,11 +272,15 @@ export function extractScheduleConds(conditions) {
};
}
-export function getScheduledAmount(amount) {
- if (amount && typeof amount !== 'number') {
- return Math.round((amount.num1 + amount.num2) / 2);
+export function getScheduledAmount(
+ amount: number | { num1: number; num2: number },
+ inverse: boolean = false,
+): number {
+ if (typeof amount === 'number') {
+ return inverse ? -amount : amount;
}
- return amount;
+ const avg = (amount.num1 + amount.num2) / 2;
+ return inverse ? -Math.round(avg) : Math.round(avg);
}
export function describeSchedule(schedule, payee) {
diff --git a/packages/loot-core/src/types/models/schedule.d.ts b/packages/loot-core/src/types/models/schedule.d.ts
index 1e64793e4b..1fdc885da4 100644
--- a/packages/loot-core/src/types/models/schedule.d.ts
+++ b/packages/loot-core/src/types/models/schedule.d.ts
@@ -32,7 +32,7 @@ export interface ScheduleEntity {
// underlying rule
_payee: PayeeEntity['id'];
_account: AccountEntity['id'];
- _amount: unknown;
+ _amount: number | { num1: number; num2: number };
_amountOp: string;
_date: RecurConfig;
_conditions: unknown;
diff --git a/upcoming-release-notes/3402.md b/upcoming-release-notes/3402.md
new file mode 100644
index 0000000000..a9717b796f
--- /dev/null
+++ b/upcoming-release-notes/3402.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [joel-jeremy]
+---
+
+Fix wrong scheduled transfer payment direction on PWA