Skip to content

A local-first personal finance app

⚙️ Moving TransactionsTable and TransactionList over to Typescript (#4930)

Alec Bakholdin21fb090ddf91
diff --git a/packages/desktop-client/src/components/accounts/Account.tsx b/packages/desktop-client/src/components/accounts/Account.tsx
index c55f6ac18d..7ec73d210e 100644
--- a/packages/desktop-client/src/components/accounts/Account.tsx
+++ b/packages/desktop-client/src/components/accounts/Account.tsx
@@ -924,7 +924,7 @@ class AccountInternal extends PureComponent<
return this.props.matchedTransactions.includes(id);
};
- onCreatePayee = (name: string) => {
+ onCreatePayee = async (name: string) => {
const trimmed = name.trim();
if (trimmed !== '') {
return this.props.dispatch(createPayee({ name })).unwrap();
@@ -1460,7 +1460,7 @@ class AccountInternal extends PureComponent<
onScheduleAction = async (
name: 'skip' | 'post-transaction' | 'complete',
- ids: string[],
+ ids: TransactionEntity['id'][],
) => {
const scheduleIds = ids.map(id => id.split('/')[1]);
@@ -1797,6 +1797,7 @@ class AccountInternal extends PureComponent<
<View style={{ flex: 1 }}>
<TransactionList
headerContent={undefined}
+ // @ts-ignore TODO
tableRef={this.table}
account={account}
transactions={transactions}
@@ -1811,7 +1812,7 @@ class AccountInternal extends PureComponent<
balances={allBalances}
showBalances={!!allBalances}
showReconciled={showReconciled}
- showCleared={showCleared}
+ showCleared={!!showCleared}
showAccount={
!accountId ||
accountId === 'offbudget' ||
@@ -1849,8 +1850,8 @@ class AccountInternal extends PureComponent<
) : null
}
onSort={this.onSort}
- sortField={this.state.sort?.field}
- ascDesc={this.state.sort?.ascDesc}
+ sortField={this.state.sort?.field ?? ''}
+ ascDesc={this.state.sort?.ascDesc ?? 'asc'}
onChange={this.onTransactionsChange}
onBatchDelete={this.onBatchDelete}
onBatchDuplicate={this.onBatchDuplicate}
diff --git a/packages/desktop-client/src/components/reports/reports/Calendar.tsx b/packages/desktop-client/src/components/reports/reports/Calendar.tsx
index 6bd08840dc..dcae987e79 100644
--- a/packages/desktop-client/src/components/reports/reports/Calendar.tsx
+++ b/packages/desktop-client/src/components/reports/reports/Calendar.tsx
@@ -1,14 +1,14 @@
-import React, {
- useState,
+import {
+ type Ref,
+ useCallback,
useEffect,
useMemo,
useRef,
- type Ref,
- useCallback,
+ useState,
} from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { useParams, useSearchParams } from 'react-router-dom';
-import { useSpring, animated, config } from 'react-spring';
+import { animated, config, useSpring } from 'react-spring';
import { Button } from '@actual-app/components/button';
import { useResponsive } from '@actual-app/components/hooks/useResponsive';
@@ -34,8 +34,8 @@ import { q, type Query } from 'loot-core/shared/query';
import { ungroupTransactions } from 'loot-core/shared/transactions';
import { amountToCurrency } from 'loot-core/shared/util';
import {
- type RuleConditionEntity,
type CalendarWidget,
+ type RuleConditionEntity,
type TimeFrame,
type TransactionEntity,
} from 'loot-core/types/models';
@@ -47,6 +47,7 @@ import { MobileBackButton } from '../../mobile/MobileBackButton';
import { TransactionList as TransactionListMobile } from '../../mobile/transactions/TransactionList';
import { MobilePageHeader, Page, PageHeader } from '../../Page';
import { PrivacyFilter } from '../../PrivacyFilter';
+import { type TableHandleRef } from '../../table';
import { TransactionList } from '../../transactions/TransactionList';
import { chartTheme } from '../chart-theme';
import { DateRange } from '../DateRange';
@@ -190,7 +191,7 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
}, [start, end, conditions, conditionsOp, firstDayOfWeekIdx, dirty]);
const [sortField, setSortField] = useState('');
- const [ascDesc, setAscDesc] = useState('desc');
+ const [ascDesc, setAscDesc] = useState<'asc' | 'desc'>('desc');
useEffect(() => {
const conditionsOpKey = conditionsOp === 'or' ? '$or' : '$and';
@@ -286,7 +287,7 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
const navigate = useNavigate();
const { isNarrowWidth } = useResponsive();
const title = widget?.meta?.name || t('Calendar');
- const table = useRef(null);
+ const table = useRef<TableHandleRef<TransactionEntity>>(null);
const dateFormat = useDateFormat();
const onSaveWidgetName = async (newName: string) => {
@@ -591,12 +592,12 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
flexGrow: 1,
overflow: isNarrowWidth ? 'auto' : 'hidden',
}}
- ref={table}
+ // TODO: make TableHandleRef conform to HTMLDivEle
+ ref={table as unknown as Ref<HTMLDivElement>}
>
{!isNarrowWidth ? (
<SplitsExpandedProvider initialMode="collapse">
<TransactionList
- headerContent={undefined}
tableRef={table}
account={undefined}
transactions={transactionsGrouped}
@@ -614,7 +615,6 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
isAdding={false}
isNew={() => false}
isMatched={() => false}
- isFiltered={() => true}
dateFormat={dateFormat}
hideFraction={false}
renderEmpty={() => (
@@ -635,7 +635,7 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {
onChange={() => {}}
onRefetch={() => setDirty(true)}
onCloseAddTransaction={() => {}}
- onCreatePayee={() => {}}
+ onCreatePayee={async () => null}
onApplyFilter={() => {}}
onBatchDelete={() => {}}
onBatchDuplicate={() => {}}
diff --git a/packages/desktop-client/src/components/schedules/StatusBadge.tsx b/packages/desktop-client/src/components/schedules/StatusBadge.tsx
index c0b4b3a772..d9460a420b 100644
--- a/packages/desktop-client/src/components/schedules/StatusBadge.tsx
+++ b/packages/desktop-client/src/components/schedules/StatusBadge.tsx
@@ -18,8 +18,19 @@ import { type ScheduleStatusType } from 'loot-core/client/data-hooks/schedules';
import { titleFirst } from 'loot-core/shared/util';
// Consists of Schedule Statuses + Transaction statuses
-type StatusTypes = ScheduleStatusType | 'cleared' | 'pending' | 'reconciled';
-export function getStatusProps(status: StatusTypes) {
+export type StatusTypes =
+ | ScheduleStatusType
+ | 'cleared'
+ | 'pending'
+ | 'reconciled';
+
+export const defaultStatusProps = {
+ color: theme.buttonNormalDisabledText,
+ backgroundColor: theme.tableRowHeaderBackground,
+ Icon: SvgCheckCircleHollow,
+};
+
+export function getStatusProps(status: StatusTypes | null | undefined) {
switch (status) {
case 'missed':
return {
@@ -76,11 +87,7 @@ export function getStatusProps(status: StatusTypes) {
Icon: SvgLockClosed,
};
default:
- return {
- color: theme.buttonNormalDisabledText,
- backgroundColor: theme.tableRowHeaderBackground,
- Icon: SvgCheckCircleHollow,
- };
+ return defaultStatusProps;
}
}
diff --git a/packages/desktop-client/src/components/table.tsx b/packages/desktop-client/src/components/table.tsx
index a0a2a31d18..0b120bd36f 100644
--- a/packages/desktop-client/src/components/table.tsx
+++ b/packages/desktop-client/src/components/table.tsx
@@ -1,5 +1,6 @@
// @ts-strict-ignore
import React, {
+ type FocusEvent,
forwardRef,
useCallback,
useImperativeHandle,
@@ -66,7 +67,7 @@ function fireBlur(onBlur, e) {
}
type FieldProps = ComponentProps<typeof View> & {
- width: CSSProperties['width'];
+ width?: CSSProperties['width'];
name?: string;
truncate?: boolean;
contentStyle?: CSSProperties;
@@ -152,7 +153,7 @@ type CellProps = Omit<ComponentProps<typeof View>, 'children' | 'value'> & {
props: ComponentProps<typeof UnexposedCellContent>,
) => ReactNode;
value?: string;
- valueStyle?: CSSProperties;
+ valueStyle?: CSSProperties | null;
onExpose?: (name: string) => void;
privacyFilter?: ComponentProps<
typeof ConditionalPrivacyFilter
@@ -411,7 +412,7 @@ export function InputCell({
);
}
-function shouldSaveFromKey(e) {
+function shouldSaveFromKey(e: KeyboardEvent) {
switch (e.key) {
case 'Tab':
case 'Enter':
@@ -422,17 +423,17 @@ function shouldSaveFromKey(e) {
}
type CustomCellRenderProps = {
- onBlur: (ev: UIEvent<unknown>) => void;
- onKeyDown: (ev: KeyboardEvent<unknown>) => void;
+ onBlur: (ev: FocusEvent) => void;
+ onKeyDown: (ev: KeyboardEvent) => void;
onUpdate: (value: string) => void;
onSave: (value: string) => void;
- shouldSaveFromKey: (ev: KeyboardEvent<unknown>) => boolean;
+ shouldSaveFromKey: (ev: KeyboardEvent) => boolean;
inputStyle: CSSProperties;
};
type CustomCellProps = Omit<ComponentProps<typeof Cell>, 'children'> & {
- children: (props: CustomCellRenderProps) => ReactNode;
- onUpdate: (value: string) => void;
- onBlur: (ev: UIEvent<unknown>) => void;
+ children?: (props: CustomCellRenderProps) => ReactNode;
+ onUpdate?: (value: string) => void;
+ onBlur?: (ev: UIEvent<unknown>) => void;
};
export function CustomCell({
value: defaultValue,
@@ -449,7 +450,7 @@ export function CustomCell({
setPrevDefaultValue(defaultValue);
}
- function onBlur_(e) {
+ function onBlur_(e: FocusEvent) {
// Only save on blur if the app is focused. Blur events fire when
// the app unfocuses, and it's unintuitive to save the value since
// the input will be focused again when the app regains focus
@@ -459,7 +460,7 @@ export function CustomCell({
}
}
- function onKeyDown(e) {
+ function onKeyDown(e: KeyboardEvent) {
if (shouldSaveFromKey(e)) {
onUpdate?.(value);
}
@@ -468,7 +469,7 @@ export function CustomCell({
return (
<Cell {...props} value={defaultValue}>
{() =>
- children({
+ children?.({
onBlur: onBlur_,
onKeyDown,
onUpdate: val => setValue(val),
@@ -881,7 +882,7 @@ const rowStyle: CSSProperties = {
width: '100%',
};
-type TableHandleRef<T extends TableItem = TableItem> = {
+export type TableHandleRef<T extends TableItem = TableItem> = {
scrollTo: (id: T['id'], alignment?: string) => void;
scrollToTop: () => void;
getScrolledItem: () => T['id'];
@@ -906,7 +907,7 @@ export function TableWithNavigator({
type TableItem = { id: number | string };
-type TableProps<T extends TableItem = TableItem> = {
+export type TableProps<T extends TableItem = TableItem> = {
items: T[];
count?: number;
headers?: ReactNode | TableHeaderProps['headers'];
@@ -929,6 +930,7 @@ type TableProps<T extends TableItem = TableItem> = {
navigator?: ReturnType<typeof useTableNavigator<T>>;
listContainerRef?: RefObject<HTMLDivElement>;
onScroll?: () => void;
+ onKeyDown?: (e: KeyboardEvent) => void;
isSelected?: (id: T['id']) => boolean;
saveScrollWidth?: (parent, child) => void;
};
@@ -1212,8 +1214,8 @@ export const Table = forwardRef(
// @ts-expect-error fix me
Table.displayName = 'Table';
-type TableNavigator<T extends TableItem> = {
- onEdit: (id: T['id'], field?: string) => void;
+export type TableNavigator<T extends TableItem> = {
+ onEdit: (id: T['id'] | null, field?: string) => void;
editingId: T['id'];
focusedField: string;
getNavigatorProps: (userProps: object) => object;
@@ -1233,7 +1235,7 @@ export function useTableNavigator<T extends TableItem>(
const modalStackLength = useRef(modalState.modalStack.length);
// onEdit is passed to children, so make sure it maintains identity
- const onEdit = useCallback((id: T['id'], field?: string) => {
+ const onEdit = useCallback((id: T['id'] | null, field?: string) => {
setEditingId(id);
setFocusedField(id ? field : null);
}, []);
diff --git a/packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx b/packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx
index 255a222586..992473100d 100644
--- a/packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx
+++ b/packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx
@@ -43,7 +43,7 @@ type SelectedTransactionsButtonProps = {
onSetTransfer: (selectedIds: string[]) => void;
onScheduleAction: (
action: 'post-transaction' | 'skip' | 'complete',
- selectedIds: string[],
+ selectedIds: TransactionEntity['id'][],
) => void;
showMakeTransfer: boolean;
onMakeAsSplitTransaction: (selectedIds: string[]) => void;
diff --git a/packages/desktop-client/src/components/transactions/TransactionList.jsx b/packages/desktop-client/src/components/transactions/TransactionList.tsx
similarity index 76%
rename from packages/desktop-client/src/components/transactions/TransactionList.jsx
rename to packages/desktop-client/src/components/transactions/TransactionList.tsx
index 47c53f2d32..3eb12d3a2f 100644
--- a/packages/desktop-client/src/components/transactions/TransactionList.jsx
+++ b/packages/desktop-client/src/components/transactions/TransactionList.tsx
@@ -1,21 +1,36 @@
-import React, { useRef, useCallback, useLayoutEffect } from 'react';
+// @ts-strict-ignore
+// TODO: remove strict
+import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react';
import { theme } from '@actual-app/components/theme';
import { send } from 'loot-core/platform/client/fetch';
import {
- splitTransaction,
- updateTransaction,
addSplitTransaction,
- realizeTempTransactions,
applyTransactionDiff,
+ realizeTempTransactions,
+ splitTransaction,
+ updateTransaction,
} from 'loot-core/shared/transactions';
-import { getChangedValues, applyChanges } from 'loot-core/shared/util';
+import { applyChanges, getChangedValues } from 'loot-core/shared/util';
+import {
+ type AccountEntity,
+ type CategoryEntity,
+ type PayeeEntity,
+ type RuleConditionEntity,
+ type ScheduleEntity,
+ type TransactionEntity,
+ type TransactionFilterEntity,
+} from 'loot-core/types/models';
import { pushModal } from '../../modals/modalsSlice';
import { useDispatch } from '../../redux';
+import { type TableHandleRef } from '../table';
-import { TransactionTable } from './TransactionsTable';
+import {
+ TransactionTable,
+ type TransactionTableProps,
+} from './TransactionsTable';
import { useNavigate } from '@desktop-client/hooks/useNavigate';
import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';
@@ -46,7 +61,7 @@ async function saveDiff(diff, learnCategories) {
learnCategories,
});
- if (remoteUpdates.length > 0) {
+ if (remoteUpdates && remoteUpdates.updated.length > 0) {
return { updates: remoteUpdates };
}
return {};
@@ -55,11 +70,61 @@ async function saveDiff(diff, learnCategories) {
async function saveDiffAndApply(diff, changes, onChange, learnCategories) {
const remoteDiff = await saveDiff(diff, learnCategories);
onChange(
+ // TODO:
+ // @ts-ignore testing
applyTransactionDiff(changes.newTransaction, remoteDiff),
+ // @ts-ignore testing
applyChanges(remoteDiff, changes.data),
);
}
+type TransactionListProps = Pick<
+ TransactionTableProps,
+ | 'accounts'
+ | 'allowSplitTransaction'
+ | 'ascDesc'
+ | 'balances'
+ | 'categoryGroups'
+ | 'dateFormat'
+ | 'hideFraction'
+ | 'isAdding'
+ | 'isMatched'
+ | 'isNew'
+ | 'loadMoreTransactions'
+ | 'onBatchDelete'
+ | 'onBatchDuplicate'
+ | 'onBatchLinkSchedule'
+ | 'onBatchUnlinkSchedule'
+ | 'onCloseAddTransaction'
+ | 'onCreatePayee'
+ | 'onCreateRule'
+ | 'onMakeAsNonSplitTransactions'
+ | 'onSort'
+ | 'onScheduleAction'
+ | 'payees'
+ | 'renderEmpty'
+ | 'showAccount'
+ | 'showBalances'
+ | 'showCleared'
+ | 'showReconciled'
+ | 'showSelection'
+ | 'sortField'
+ | 'transactions'
+> & {
+ tableRef: RefObject<TableHandleRef<TransactionEntity> | null>;
+ allTransactions: TransactionEntity[];
+ account: AccountEntity | undefined;
+ category: CategoryEntity | undefined;
+ onChange: (
+ transaction: TransactionEntity,
+ transactions: TransactionEntity[],
+ ) => void;
+ onApplyFilter: (
+ f: Partial<RuleConditionEntity> | TransactionFilterEntity,
+ ) => void;
+ onRefetch: () => void;
+};
+
export function TransactionList({
tableRef,
transactions,
@@ -75,11 +140,9 @@ export function TransactionList({
showReconciled,
showCleared,
showAccount,
- headerContent,
isAdding,
isNew,
isMatched,
- isFiltered,
dateFormat,
hideFraction,
renderEmpty,
@@ -100,19 +163,19 @@ export function TransactionList({
onCreateRule,
onScheduleAction,
onMakeAsNonSplitTransactions,
-}) {
+}: TransactionListProps) {
const dispatch = useDispatch();
const navigate = useNavigate();
const [learnCategories = 'true'] = useSyncedPref('learn-categories');
const isLearnCategoriesEnabled = String(learnCategories) === 'true';
- const transactionsLatest = useRef();
+ const transactionsLatest = useRef<readonly TransactionEntity[]>([]);
useLayoutEffect(() => {
transactionsLatest.current = transactions;
}, [transactions]);
const onAdd = useCallback(
- async newTransactions => {
+ async (newTransactions: TransactionEntity[]) => {
newTransactions = realizeTempTransactions(newTransactions);
await saveDiff({ added: newTransactions }, isLearnCategoriesEnabled);
@@ -122,7 +185,7 @@ export function TransactionList({
);
const onSave = useCallback(
- async transaction => {
+ async (transaction: TransactionEntity) => {
const changes = updateTransaction(
transactionsLatest.current,
transaction,
@@ -152,7 +215,7 @@ export function TransactionList({
);
const onAddSplit = useCallback(
- id => {
+ (id: TransactionEntity['id']) => {
const changes = addSplitTransaction(transactionsLatest.current, id);
onChange(changes.newTransaction, changes.data);
saveDiffAndApply(
@@ -167,7 +230,7 @@ export function TransactionList({
);
const onSplit = useCallback(
- id => {
+ (id: TransactionEntity['id']) => {
const changes = splitTransaction(transactionsLatest.current, id);
onChange(changes.newTransaction, changes.data);
saveDiffAndApply(
@@ -182,11 +245,14 @@ export function TransactionList({
);
const onApplyRules = useCallback(
- async (transaction, updatedFieldName = null) => {
+ async (
+ transaction: TransactionEntity,
+ updatedFieldName: string | null = null,
+ ) => {
const afterRules = await send('rules-run', { transaction });
const diff = getChangedValues(transaction, afterRules);
- const newTransaction = { ...transaction };
+ const newTransaction: TransactionEntity = { ...transaction };
if (diff) {
Object.keys(diff).forEach(field => {
if (
@@ -207,7 +273,7 @@ export function TransactionList({
) {
newTransaction.subtransactions = diff.subtransactions.map(
(st, idx) => ({
- ...(newTransaction.subtransactions[idx] || st),
+ ...(newTransaction.subtransactions?.[idx] || st),
...(st[updatedFieldName] != null && {
[updatedFieldName]: st[updatedFieldName],
}),
@@ -221,21 +287,21 @@ export function TransactionList({
);
const onManagePayees = useCallback(
- id => {
- navigate('/payees', id && { state: { selectedPayee: id } });
+ (id: PayeeEntity['id']) => {
+ navigate('/payees', id ? { state: { selectedPayee: id } } : undefined);
},
[navigate],
);
const onNavigateToTransferAccount = useCallback(
- accountId => {
+ (accountId: AccountEntity['id']) => {
navigate(`/accounts/${accountId}`);
},
[navigate],
);
const onNavigateToSchedule = useCallback(
- scheduleId => {
+ (scheduleId: ScheduleEntity['id']) => {
dispatch(
pushModal({
modal: { name: 'schedule-edit', options: { id: scheduleId } },
@@ -246,7 +312,7 @@ export function TransactionList({
);
const onNotesTagClick = useCallback(
- tag => {
+ (tag: string) => {
onApplyFilter({
field: 'notes',
op: 'hasTags',
@@ -276,10 +342,8 @@ export function TransactionList({
isAdding={isAdding}
isNew={isNew}
isMatched={isMatched}
- isFiltered={isFiltered}
dateFormat={dateFormat}
hideFraction={hideFraction}
- headerContent={headerContent}
renderEmpty={renderEmpty}
onSave={onSave}
onApplyRules={onApplyRules}
diff --git a/packages/desktop-client/src/components/transactions/TransactionMenu.tsx b/packages/desktop-client/src/components/transactions/TransactionMenu.tsx
index f4fa5b16bf..95cd9cc493 100644
--- a/packages/desktop-client/src/components/transactions/TransactionMenu.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionMenu.tsx
@@ -25,7 +25,10 @@ type BalanceMenuProps = Omit<
onLinkSchedule: (id: string) => void;
onUnlinkSchedule: (id: string) => void;
onCreateRule: (id: string) => void;
- onScheduleAction: (action: string, id: string) => void;
+ onScheduleAction: (
+ name: 'skip' | 'post-transaction' | 'complete',
+ id: TransactionEntity['id'],
+ ) => void;
onMakeAsNonSplitTransactions: (id: string) => void;
closeMenu: () => void;
};
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
index b1f03dbe4f..daadc3c17f 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
@@ -70,8 +70,9 @@ const payees: PayeeEntity[] = [
},
];
vi.mock('../../hooks/usePayees', async importOriginal => {
- // eslint-disable-next-line @typescript-eslint/consistent-type-imports
- const actual = await importOriginal<typeof import('../../hooks/usePayees')>();
+ const actual =
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
+ await importOriginal<typeof import('../../hooks/usePayees')>();
return {
...actual,
usePayees: () => payees,
@@ -181,7 +182,7 @@ function LiveTransactionTable(props: LiveTransactionTableProps) {
return diff.added[0].id;
};
- const onCreatePayee = () => 'id';
+ const onCreatePayee = async () => 'id';
// It's important that these functions are they same instances
// across renders. Doing so tests that the transaction table
@@ -200,9 +201,9 @@ function LiveTransactionTable(props: LiveTransactionTableProps) {
<SplitsExpandedProvider>
<TransactionTable
{...props}
- // @ts-expect-error this will be auto-patched once TransactionTable is moved to TS
transactions={transactions}
loadMoreTransactions={() => {}}
+ // @ts-ignore TODO:
commonPayees={[]}
payees={payees}
addNotification={console.log}
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.jsx b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
similarity index 63%
rename from packages/desktop-client/src/components/transactions/TransactionsTable.jsx
rename to packages/desktop-client/src/components/transactions/TransactionsTable.tsx
index 9ebcc9874a..ebadb6d112 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.jsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
@@ -1,13 +1,19 @@
-import React, {
+import {
createElement,
createRef,
+ type CSSProperties,
+ type ForwardedRef,
forwardRef,
+ type KeyboardEvent,
memo,
- useState,
- useRef,
- useMemo,
+ type ReactNode,
+ type Ref,
+ type RefObject,
useCallback,
useEffect,
+ useMemo,
+ useRef,
+ useState,
} from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import { Trans, useTranslation } from 'react-i18next';
@@ -35,149 +41,101 @@ import { theme } from '@actual-app/components/theme';
import { Tooltip } from '@actual-app/components/tooltip';
import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
-import {
- format as formatDate,
- parseISO,
- isValid as isDateValid,
-} from 'date-fns';
+import { format as formatDate, parseISO } from 'date-fns';
import { useCachedSchedules } from 'loot-core/client/data-hooks/schedules';
-import { evalArithmetic } from 'loot-core/shared/arithmetic';
-import { currentDay } from 'loot-core/shared/months';
import * as monthUtils from 'loot-core/shared/months';
import {
- splitTransaction,
- updateTransaction,
- deleteTransaction,
addSplitTransaction,
+ deleteTransaction,
groupTransaction,
- ungroupTransactions,
- isTemporaryId,
isPreviewId,
+ isTemporaryId,
+ splitTransaction,
+ ungroupTransactions,
+ updateTransaction,
} from 'loot-core/shared/transactions';
import {
+ amountToCurrency,
integerToCurrency,
- amountToInteger,
titleFirst,
- amountToCurrency,
} from 'loot-core/shared/util';
-
-import { pushModal } from '../../modals/modalsSlice';
-import { addNotification } from '../../notifications/notificationsSlice';
import {
- getAccountsById,
- getPayeesById,
- getCategoriesById,
-} from '../../queries/queriesSlice';
+ type AccountEntity,
+ type CategoryEntity,
+ type CategoryGroupEntity,
+ type PayeeEntity,
+ type RuleEntity,
+ type ScheduleEntity,
+ type TransactionEntity,
+} from 'loot-core/types/models';
+
+import { useContextMenu } from '../../hooks/useContextMenu';
+import { useDisplayPayee } from '../../hooks/useDisplayPayee';
+import { useMergedRefs } from '../../hooks/useMergedRefs';
+import { usePrevious } from '../../hooks/usePrevious';
+import { useProperFocus } from '../../hooks/useProperFocus';
+import { useSelectedDispatch, useSelectedItems } from '../../hooks/useSelected';
+import {
+ type SplitsExpandedContextValue,
+ useSplitsExpanded,
+} from '../../hooks/useSplitsExpanded';
import { useDispatch } from '../../redux';
import { AccountAutocomplete } from '../autocomplete/AccountAutocomplete';
import { CategoryAutocomplete } from '../autocomplete/CategoryAutocomplete';
import { PayeeAutocomplete } from '../autocomplete/PayeeAutocomplete';
-import { getStatusProps } from '../schedules/StatusBadge';
+import { getStatusProps, type StatusTypes } from '../schedules/StatusBadge';
import { DateSelect } from '../select/DateSelect';
import { NamespaceContext } from '../spreadsheet/NamespaceContext';
import {
Cell,
+ CellButton,
+ CustomCell,
+ DeleteCell,
Field,
- Row,
InputCell,
+ Row,
SelectCell,
- DeleteCell,
- CustomCell,
- CellButton,
- useTableNavigator,
Table,
+ type TableHandleRef,
+ type TableNavigator,
+ type TableProps,
UnexposedCellContent,
+ useTableNavigator,
} from '../table';
+import {
+ deserializeTransaction,
+ isLastChild,
+ makeTemporaryTransactions,
+ selectAscDesc,
+ type SerializedTransaction,
+ serializeTransaction,
+ type TransactionEditFunction,
+ type TransactionUpdateFunction,
+} from './table/utils';
import { TransactionMenu } from './TransactionMenu';
-import { useContextMenu } from '@desktop-client/hooks/useContextMenu';
-import { useDisplayPayee } from '@desktop-client/hooks/useDisplayPayee';
-import { useMergedRefs } from '@desktop-client/hooks/useMergedRefs';
-import { usePrevious } from '@desktop-client/hooks/usePrevious';
-import { useProperFocus } from '@desktop-client/hooks/useProperFocus';
+import { pushModal } from '@desktop-client/modals/modalsSlice';
+import { addNotification } from '@desktop-client/notifications/notificationsSlice';
import {
- useSelectedDispatch,
- useSelectedItems,
-} from '@desktop-client/hooks/useSelected';
-import { useSplitsExpanded } from '@desktop-client/hooks/useSplitsExpanded';
-
-function getDisplayValue(obj, name) {
- return obj ? obj[name] : '';
-}
-
-function serializeTransaction(transaction, showZeroInDeposit) {
- const { amount, date: originalDate } = transaction;
-
- let debit = amount < 0 ? -amount : null;
- let credit = amount > 0 ? amount : null;
-
- if (amount === 0) {
- if (showZeroInDeposit) {
- credit = 0;
- } else {
- debit = 0;
- }
- }
-
- let date = originalDate;
- // Validate the date format
- if (!isDateValid(parseISO(date))) {
- // Be a little forgiving if the date isn't valid. This at least
- // stops the UI from crashing, but this is a serious problem with
- // the data. This allows the user to go through and see empty
- // dates and manually fix them.
- date = null;
- }
-
- return {
- ...transaction,
- date,
- debit: debit != null ? integerToCurrency(debit) : '',
- credit: credit != null ? integerToCurrency(credit) : '',
- };
-}
-
-function deserializeTransaction(transaction, originalTransaction) {
- const { debit, credit, date: originalDate, ...realTransaction } = transaction;
-
- let amount;
- if (debit !== '') {
- const parsed = evalArithmetic(debit, null);
- amount = parsed != null ? -parsed : null;
- } else {
- amount = evalArithmetic(credit, null);
- }
-
- amount =
- amount != null ? amountToInteger(amount) : originalTransaction.amount;
-
- let date = originalDate;
- if (date == null) {
- date = originalTransaction.date || currentDay();
- }
-
- return { ...realTransaction, date, amount };
-}
-
-function isLastChild(transactions, index) {
- const trans = transactions[index];
- return (
- trans &&
- trans.is_child &&
- (transactions[index + 1] == null ||
- transactions[index + 1].parent_id !== trans.parent_id)
- );
-}
-
-function selectAscDesc(field, ascDesc, clicked, defaultAscDesc = 'asc') {
- return field === clicked
- ? ascDesc === 'asc'
- ? 'desc'
- : 'asc'
- : defaultAscDesc;
-}
+ getAccountsById,
+ getPayeesById,
+ getCategoriesById,
+} from '@desktop-client/queries/queriesSlice';
+
+type TransactionHeaderProps = {
+ hasSelected: boolean;
+ showAccount: boolean;
+ showCategory: boolean;
+ showBalance: boolean;
+ showCleared: boolean;
+ scrollWidth: number;
+ showSelection: boolean;
+ onSort: (field: string, ascDesc: 'asc' | 'desc') => void;
+ ascDesc: 'asc' | 'desc';
+ field: string;
+};
const TransactionHeader = memo(
({
@@ -191,13 +149,13 @@ const TransactionHeader = memo(
ascDesc,
field,
showSelection,
- }) => {
+ }: TransactionHeaderProps) => {
const dispatchSelected = useSelectedDispatch();
const { t } = useTranslation();
useHotkeys(
'ctrl+a, cmd+a, meta+a',
- e => dispatchSelected({ type: 'select-all', event: e }),
+ () => dispatchSelected({ type: 'select-all' }),
{
preventDefault: true,
scopes: ['app'],
@@ -228,7 +186,7 @@ const TransactionHeader = memo(
borderTopWidth: 0,
borderBottomWidth: 0,
}}
- onSelect={e =>
+ onSelect={(e: KeyboardEvent<HTMLDivElement>) =>
dispatchSelected({
type: 'select-all',
isRangeSelect: e.shiftKey,
@@ -359,6 +317,17 @@ const TransactionHeader = memo(
TransactionHeader.displayName = 'TransactionHeader';
+type StatusCellProps = {
+ id: TransactionEntity['id'];
+ status?: StatusTypes | null;
+ focused?: boolean;
+ selected?: boolean;
+ isChild?: boolean;
+ isPreview?: boolean;
+ onEdit: TransactionEditFunction;
+ onUpdate: TransactionUpdateFunction;
+};
+
function StatusCell({
id,
focused,
@@ -368,7 +337,7 @@ function StatusCell({
isPreview,
onEdit,
onUpdate,
-}) {
+}: StatusCellProps) {
const isClearedField =
status === 'cleared' || status === 'reconciled' || status == null;
const statusProps = getStatusProps(status);
@@ -437,6 +406,13 @@ function StatusCell({
);
}
+type HeaderCellProps = {
+ value: string;
+ id: string;
+ icon?: 'asc' | 'desc' | 'clickable';
+ onClick?: () => void;
+} & Pick<CSSProperties, 'width' | 'alignItems' | 'marginLeft' | 'marginRight'>;
+
function HeaderCell({
value,
id,
@@ -446,9 +422,9 @@ function HeaderCell({
marginRight,
icon,
onClick,
-}) {
+}: HeaderCellProps) {
const style = {
- whiteSpace: 'nowrap',
+ whiteSpace: 'nowrap' as CSSProperties['whiteSpace'],
overflow: 'hidden',
textOverflow: 'ellipsis',
color: theme.tableHeaderText,
@@ -486,6 +462,27 @@ function HeaderCell({
);
}
+type PayeeCellProps = {
+ id: TransactionEntity['id'];
+ payee?: PayeeEntity;
+ focused: boolean;
+ payees: PayeeEntity[];
+ accounts: AccountEntity[];
+ transferAccountsByTransaction: {
+ [id: TransactionEntity['id']]: AccountEntity | null;
+ };
+ valueStyle: CSSProperties | null;
+ transaction: SerializedTransaction;
+ importedPayee?: PayeeEntity['id'];
+ isPreview: boolean;
+ onEdit: TransactionEditFunction;
+ onUpdate: TransactionUpdateFunction;
+ onCreatePayee: (name: string) => Promise<null | PayeeEntity['id']>;
+ onManagePayees: (id: PayeeEntity['id'] | undefined) => void;
+ onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
+};
+
function PayeeCell({
id,
payee,
@@ -503,7 +500,7 @@ function PayeeCell({
onManagePayees,
onNavigateToTransferAccount,
onNavigateToSchedule,
-}) {
+}: PayeeCellProps) {
const isCreatingPayee = useRef(false);
const dispatch = useDispatch();
@@ -539,7 +536,7 @@ function PayeeCell({
modal: {
name: 'payee-autocomplete',
options: {
- onSelect: payeeId => {
+ onSelect: (payeeId: PayeeEntity['id']) => {
onUpdate('payee', payeeId);
},
},
@@ -621,7 +618,7 @@ function PayeeCell({
if (value && value.startsWith('new:') && !isCreatingPayee.current) {
isCreatingPayee.current = true;
const id = await onCreatePayee(value.slice('new:'.length));
- onUpdate('payee', id);
+ onUpdate('payee', id ?? undefined);
isCreatingPayee.current = false;
}
}}
@@ -694,7 +691,7 @@ function PayeeCell({
<PayeeAutocomplete
payees={payees}
accounts={accounts}
- value={payee?.id}
+ value={payee?.id ?? null}
shouldSaveFromKey={shouldSaveFromKey}
inputProps={{
onBlur,
@@ -704,7 +701,7 @@ function PayeeCell({
showManagePayees={true}
clearOnBlur={false}
focused={true}
- onUpdate={(id, value) => onUpdate?.(value)}
+ onUpdate={(_, value) => onUpdate?.(value)}
onSelect={onSave}
onManagePayees={() => onManagePayees(payee?.id)}
/>
@@ -723,12 +720,19 @@ const payeeIconButtonStyle = {
const scheduleIconStyle = { width: 13, height: 13 };
const transferIconStyle = { width: 10, height: 10 };
+type PayeeIconsProps = {
+ transaction: SerializedTransaction;
+ transferAccount: AccountEntity | null;
+ onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
+};
+
function PayeeIcons({
transaction,
transferAccount,
onNavigateToTransferAccount,
onNavigateToSchedule,
-}) {
+}: PayeeIconsProps) {
const scheduleId = transaction.schedule;
const { isLoading, schedules = [] } = useCachedSchedules();
@@ -755,7 +759,9 @@ function PayeeIcons({
aria-label="See schedule details"
style={payeeIconButtonStyle}
onPress={() => {
- onNavigateToSchedule(scheduleId);
+ if (scheduleId) {
+ onNavigateToSchedule(scheduleId);
+ }
}}
>
{recurring ? (
@@ -788,6 +794,60 @@ function PayeeIcons({
);
}
+type TransactionProps = {
+ allTransactions?: TransactionEntity[];
+ transaction: TransactionEntity;
+ subtransactions: TransactionEntity[] | null;
+ transferAccountsByTransaction: {
+ [id: TransactionEntity['id']]: AccountEntity | null;
+ };
+ editing: boolean;
+ showAccount?: boolean;
+ showBalance?: boolean;
+ showCleared?: boolean;
+ showZeroInDeposit?: boolean;
+ style?: CSSProperties;
+ selected?: boolean;
+ highlighted?: boolean;
+ added?: boolean;
+ matched?: boolean;
+ expanded?: boolean;
+ focusedField?: string;
+ categoryGroups: CategoryGroupEntity[];
+ payees: PayeeEntity[];
+ accounts: AccountEntity[];
+ balance: number;
+ dateFormat: string;
+ hideFraction: boolean;
+ onSave: (
+ tx: TransactionEntity,
+ subTxs: TransactionEntity[] | null,
+ name: string,
+ ) => void;
+ onEdit: (id: TransactionEntity['id'], field: string) => void;
+ onDelete: (id: TransactionEntity['id']) => void;
+ onDuplicate?: (id: TransactionEntity['id']) => void;
+ onLinkSchedule?: (id: TransactionEntity['id']) => void;
+ onUnlinkSchedule?: (id: TransactionEntity['id']) => void;
+ onCreateRule?: (id: TransactionEntity['id']) => void;
+ onScheduleAction?: (
+ name: 'skip' | 'post-transaction' | 'complete',
+ id: TransactionEntity['id'],
+ ) => void;
+ onMakeAsNonSplitTransactions?: (id: TransactionEntity['id']) => void;
+ onSplit: (id: TransactionEntity['id']) => void;
+ onToggleSplit: (id: TransactionEntity['id']) => void;
+ onCreatePayee: (name: string) => Promise<null | PayeeEntity['id']>;
+ onManagePayees: (id: PayeeEntity['id'] | undefined) => void;
+ onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
+ onNotesTagClick: (tag: string) => void;
+ splitError?: ReactNode;
+ listContainerRef?: RefObject<HTMLDivElement>;
+ showSelection?: boolean;
+ allowSplitTransaction?: boolean;
+};
+
const Transaction = memo(function Transaction({
allTransactions,
transaction: originalTransaction,
@@ -831,7 +891,7 @@ const Transaction = memo(function Transaction({
listContainerRef,
showSelection,
allowSplitTransaction,
-}) {
+}: TransactionProps) {
const dispatch = useDispatch();
const dispatchSelected = useSelectedDispatch();
const triggerRef = useRef(null);
@@ -857,7 +917,7 @@ const Transaction = memo(function Transaction({
const [showReconciliationWarning, setShowReconciliationWarning] =
useState(false);
- function onUpdate(name, value) {
+ const onUpdate: TransactionUpdateFunction = (name, value) => {
// Had some issues with this is called twice which is a problem now that we are showing a warning
// modal if the transaction is locked. I added a boolean to guard against showing the modal twice.
// I'm still not completely happy with how the cells update pre/post modal. Sometimes you have to
@@ -915,13 +975,13 @@ const Transaction = memo(function Transaction({
}),
);
}
- }
+ };
- function onUpdateAfterConfirm(name, value) {
+ const onUpdateAfterConfirm: TransactionUpdateFunction = (name, value) => {
const newTransaction = { ...transaction, [name]: value };
// Don't change the note to an empty string if it's null (since they are both rendered the same)
- if (name === 'note' && value === '' && transaction.note == null) {
+ if (name === 'notes' && value === '' && transaction.notes == null) {
return;
}
@@ -930,7 +990,7 @@ const Transaction = memo(function Transaction({
value &&
getAccountsById(accounts)[value].offbudget
) {
- newTransaction.category = null;
+ newTransaction.category = undefined;
}
// If entering an amount in either of the credit/debit fields, we
@@ -949,7 +1009,11 @@ const Transaction = memo(function Transaction({
// Don't save a temporary value (a new payee) which will be
// filled in with a real id later
- if (name === 'payee' && value && value.startsWith('new:')) {
+ if (
+ name === 'payee' &&
+ value &&
+ (value as TransactionEntity['payee'])?.startsWith('new:')
+ ) {
setTransaction(newTransaction);
} else {
const deserialized = deserializeTransaction(
@@ -965,7 +1029,7 @@ const Transaction = memo(function Transaction({
: name;
onSave(deserialized, subtransactions, deserializedName);
}
- }
+ };
const {
id,
@@ -988,13 +1052,15 @@ const Transaction = memo(function Transaction({
const previewStatus = forceUpcoming ? 'upcoming' : categoryId;
// Join in some data
- const payee = payees && payeeId && getPayeesById(payees)[payeeId];
+ const payee =
+ (payees && payeeId && getPayeesById(payees)[payeeId]) || undefined;
const account = accounts && accountId && getAccountsById(accounts)[accountId];
const isChild = transaction.is_child;
- const transferAcct = isTemporaryId(id)
- ? getAccountsById(accounts)[payee?.transfer_acct]
- : transferAccountsByTransaction[id];
+ const transferAcct =
+ isTemporaryId(id) && payee?.transfer_acct
+ ? getAccountsById(accounts)[payee.transfer_acct]
+ : transferAccountsByTransaction[id];
const isBudgetTransfer = transferAcct && transferAcct.offbudget === 0;
const isOffBudget = account && account.offbudget === 1;
@@ -1014,7 +1080,7 @@ const Transaction = memo(function Transaction({
// a variable (with a small delay in order for the next render cycle to pick up
// the change instead of the current). We pass the integer to the Popover which
// causes it to re-calculate the positioning. Thus fixing the problem.
- const [updateId, setUpdateId] = useState(1);
+ const [_, setUpdateId] = useState(1);
useEffect(() => {
// The hack applies to only transactions with split errors
if (!splitError) {
@@ -1085,9 +1151,8 @@ const Transaction = memo(function Transaction({
/>
</Popover>
- {splitError && listContainerRef.current && (
+ {splitError && listContainerRef?.current && (
<Popover
- arrowSize={updateId}
triggerRef={triggerRef}
isOpen
isNonModal
@@ -1142,10 +1207,10 @@ const Transaction = memo(function Transaction({
/* Checkmark field for non-child transaction */
exposed
buttonProps={{
- className: selected || editing ? null : 'hover-visible',
+ className: selected || editing ? undefined : 'hover-visible',
}}
focused={focusedField === 'select'}
- onSelect={e => {
+ onSelect={(e: KeyboardEvent<HTMLDivElement>) => {
dispatchSelected({
type: 'select',
id: transaction.id,
@@ -1156,11 +1221,14 @@ const Transaction = memo(function Transaction({
selected={selected}
style={{ ...(isChild && { borderLeftWidth: 1 }) }}
value={
- matched && (
- <SvgHyperlink2
- style={{ width: 13, height: 13, color: 'inherit' }}
- />
- )
+ matched
+ ? // TODO: this will require changes in table.tsx
+ ((
+ <SvgHyperlink2
+ style={{ width: 13, height: 13, color: 'inherit' }}
+ />
+ ) as unknown as string)
+ : undefined
}
/>
)}
@@ -1237,14 +1305,12 @@ const Transaction = memo(function Transaction({
<AccountAutocomplete
includeClosedAccounts={false}
value={accountId}
- accounts={accounts}
shouldSaveFromKey={shouldSaveFromKey}
clearOnBlur={false}
focused={true}
inputProps={{ onBlur, onKeyDown, style: inputStyle }}
onUpdate={onUpdate}
onSelect={onSave}
- menuPortalTarget={undefined}
/>
)}
</CustomCell>
@@ -1332,7 +1398,7 @@ const Transaction = memo(function Transaction({
display: 'inline-block',
}}
>
- {titleFirst(previewStatus)}
+ {titleFirst(previewStatus ?? '')}
</View>
)}
<CellButton
@@ -1424,10 +1490,7 @@ const Transaction = memo(function Transaction({
value={categoryId}
formatter={value =>
value
- ? getDisplayValue(
- getCategoriesById(categoryGroups)[value],
- 'name',
- )
+ ? (getCategoriesById(categoryGroups)[value]?.name ?? '')
: transaction.id
? 'Categorize'
: ''
@@ -1467,7 +1530,7 @@ const Transaction = memo(function Transaction({
>
<CategoryAutocomplete
categoryGroups={categoryGroups}
- value={categoryId}
+ value={categoryId ?? null}
focused={true}
clearOnBlur={false}
showSplitOption={!isChild && !isParent && allowSplitTransaction}
@@ -1475,7 +1538,6 @@ const Transaction = memo(function Transaction({
inputProps={{ onBlur, onKeyDown, style: inputStyle }}
onUpdate={onUpdate}
onSelect={onSave}
- menuPortalTarget={undefined}
showHiddenCategories={false}
/>
</NamespaceContext.Provider>
@@ -1563,7 +1625,7 @@ const Transaction = memo(function Transaction({
isPreview={isPreview}
status={
isPreview
- ? previewStatus
+ ? (previewStatus as StatusTypes)
: reconciled
? 'reconciled'
: cleared
@@ -1581,6 +1643,15 @@ const Transaction = memo(function Transaction({
);
});
+type TransactionErrorProps = {
+ error: NonNullable<TransactionEntity['error']>;
+ isDeposit: boolean;
+ onAddSplit: () => void;
+ onDistributeRemainder: () => void;
+ style?: CSSProperties;
+ canDistributeRemainder: boolean;
+};
+
function TransactionError({
error,
isDeposit,
@@ -1588,7 +1659,7 @@ function TransactionError({
onDistributeRemainder,
style,
canDistributeRemainder,
-}) {
+}: TransactionErrorProps) {
switch (error.type) {
case 'SplitTransactionError':
if (error.version === 1) {
@@ -1637,23 +1708,41 @@ function TransactionError({
}
}
-function makeTemporaryTransactions(
- currentAccountId,
- currentCategoryId,
- lastDate,
-) {
- return [
- {
- id: 'temp',
- date: lastDate || currentDay(),
- account: currentAccountId || null,
- category: currentCategoryId || null,
- cleared: false,
- amount: null,
- },
- ];
-}
-
+type NewTransactionProps = {
+ accounts: AccountEntity[];
+ balance: number;
+ categoryGroups: CategoryGroupEntity[];
+ dateFormat: string;
+ editingTransaction: TransactionEntity['id'];
+ focusedField: string;
+ hideFraction: boolean;
+ onAdd: () => void;
+ onAddSplit: (id: TransactionEntity['id']) => void;
+ onToggleSplit: (id: TransactionEntity['id']) => void;
+ onClose: () => void;
+ onCreatePayee: (name: string) => Promise<null | PayeeEntity['id']>;
+ onDelete: (id: TransactionEntity['id']) => void;
+ onDistributeRemainder: (id: TransactionEntity['id']) => void;
+ onEdit: (id: TransactionEntity['id'], field: string) => void;
+ onManagePayees: (id: PayeeEntity['id'] | undefined) => void;
+ onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
+ onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNotesTagClick: (tag: string) => void;
+ onSave: (
+ tx: TransactionEntity,
+ subTxs: TransactionEntity[] | null,
+ name: string,
+ ) => void;
+ onSplit: (id: TransactionEntity['id']) => void;
+ payees: PayeeEntity[];
+ showAccount?: boolean;
+ showBalance?: boolean;
+ showCleared?: boolean;
+ transactions: TransactionEntity[];
+ transferAccountsByTransaction: {
+ [id: TransactionEntity['id']]: AccountEntity | null;
+ };
+};
function NewTransaction({
transactions,
accounts,
@@ -1663,13 +1752,13 @@ function NewTransaction({
editingTransaction,
focusedField,
showAccount,
- showCategory,
showBalance,
showCleared,
dateFormat,
hideFraction,
onClose,
onSplit,
+ onToggleSplit,
onEdit,
onDelete,
onSave,
@@ -1682,7 +1771,7 @@ function NewTransaction({
onNavigateToSchedule,
onNotesTagClick,
balance,
-}) {
+}: NewTransactionProps) {
const error = transactions[0].error;
const isDeposit = transactions[0].amount > 0;
@@ -1712,29 +1801,29 @@ function NewTransaction({
>
{transactions.map(transaction => (
<Transaction
- isNew
key={transaction.id}
editing={editingTransaction === transaction.id}
transaction={transaction}
subtransactions={transaction.is_parent ? childTransactions : null}
transferAccountsByTransaction={transferAccountsByTransaction}
showAccount={showAccount}
- showCategory={showCategory}
showBalance={showBalance}
showCleared={showCleared}
- focusedField={editingTransaction === transaction.id && focusedField}
+ focusedField={
+ editingTransaction === transaction.id ? focusedField : undefined
+ }
showZeroInDeposit={isDeposit}
accounts={accounts}
categoryGroups={categoryGroups}
payees={payees}
dateFormat={dateFormat}
- hideFraction={hideFraction}
+ hideFraction={!!hideFraction}
expanded={true}
onEdit={onEdit}
onSave={onSave}
onSplit={onSplit}
+ onToggleSplit={onToggleSplit}
onDelete={onDelete}
- onAdd={onAdd}
onManagePayees={onManagePayees}
onCreatePayee={onCreatePayee}
style={{ marginTop: -1 }}
@@ -1789,6 +1878,80 @@ function NewTransaction({
);
}
+type TransactionTableInnerProps = {
+ tableRef: Ref<TableHandleRef<TransactionEntity>>;
+ listContainerRef: RefObject<HTMLDivElement>;
+ tableNavigator: TableNavigator<TransactionEntity>;
+ newNavigator: TableNavigator<TransactionEntity>;
+ selectedItems: Set<string>;
+ isExpanded: (id: string) => boolean;
+ transactionMap: Map<TransactionEntity['id'], TransactionEntity>;
+ transactionsByParent: {
+ [parentId: TransactionEntity['id']]: TransactionEntity[];
+ };
+ transferAccountsByTransaction: {
+ [id: TransactionEntity['id']]: AccountEntity | null;
+ };
+ newTransactions: TransactionEntity[];
+
+ transactions: TransactionEntity[];
+ loadMoreTransactions: () => void;
+ accounts: AccountEntity[];
+ categoryGroups: CategoryGroupEntity[];
+ payees: PayeeEntity[];
+ balances: Record<TransactionEntity['id'], { balance: number }> | null;
+ showBalances: boolean;
+ showReconciled: boolean;
+ showCleared: boolean;
+ showAccount: boolean;
+ showCategory: boolean;
+ currentAccountId: AccountEntity['id'];
+ currentCategoryId: CategoryEntity['id'];
+ isAdding: boolean;
+ isNew: (id: TransactionEntity['id']) => boolean;
+ isMatched: (id: TransactionEntity['id']) => boolean;
+ dateFormat: string | undefined;
+ hideFraction: boolean;
+ renderEmpty: ReactNode | (() => ReactNode);
+ onSave: (transaction: TransactionEntity) => void;
+ onApplyRules: (
+ transaction: TransactionEntity,
+ field: string,
+ ) => Promise<TransactionEntity>;
+ onSplit: (id: TransactionEntity['id']) => void;
+ onAddSplit: (id: TransactionEntity['id']) => void;
+ onCloseAddTransaction: () => void;
+ onAdd: (transactions: TransactionEntity[]) => void;
+ onCreatePayee: (name: string) => Promise<null | PayeeEntity['id']>;
+ style?: CSSProperties;
+ onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
+ onNotesTagClick: (tag: string) => void;
+ sortField: string;
+ ascDesc: 'asc' | 'desc';
+ onCreateRule: (id: RuleEntity['id']) => void;
+ onScheduleAction: (
+ name: 'skip' | 'post-transaction' | 'complete',
+ id: TransactionEntity['id'],
+ ) => void;
+ onMakeAsNonSplitTransactions: (id: string) => void;
+ showSelection: boolean;
+ allowSplitTransaction?: boolean;
+
+ onDelete: (id: TransactionEntity['id']) => void;
+ onDuplicate: (id: TransactionEntity['id']) => void;
+ onLinkSchedule: (id: TransactionEntity['id']) => void;
+ onUnlinkSchedule: (id: TransactionEntity['id']) => void;
+ onCheckNewEnter: (e: KeyboardEvent) => void;
+ onCheckEnter: (e: KeyboardEvent) => void;
+ onAddTemporary: (id?: TransactionEntity['id']) => void;
+ onDistributeRemainder: (id: TransactionEntity['id']) => void;
+ onToggleSplit: (id: TransactionEntity['id']) => void;
+ onManagePayees: (id?: PayeeEntity['id']) => void;
+
+ onSort: (field: string, ascDesc: 'asc' | 'desc') => void;
+};
+
function TransactionTableInner({
tableNavigator,
tableRef,
@@ -1796,14 +1959,13 @@ function TransactionTableInner({
dateFormat = 'MM/dd/yyyy',
newNavigator,
renderEmpty,
- onScroll,
...props
-}) {
- const containerRef = createRef();
+}: TransactionTableInnerProps) {
+ const containerRef = createRef<HTMLDivElement>();
const isAddingPrev = usePrevious(props.isAdding);
const [scrollWidth, setScrollWidth] = useState(0);
- function saveScrollWidth(parent, child) {
+ function saveScrollWidth(parent: number, child: number) {
const width = parent > 0 && child > 0 && parent - child;
setScrollWidth(!width ? 0 : width);
@@ -1817,7 +1979,7 @@ function TransactionTableInner({
} = props;
const onNavigateToTransferAccount = useCallback(
- accountId => {
+ (accountId: AccountEntity['id']) => {
onCloseAddTransactionProp();
onNavigateToTransferAccountProp(accountId);
},
@@ -1825,7 +1987,7 @@ function TransactionTableInner({
);
const onNavigateToSchedule = useCallback(
- scheduleId => {
+ (scheduleId: ScheduleEntity['id']) => {
onCloseAddTransactionProp();
onNavigateToScheduleProp(scheduleId);
},
@@ -1833,7 +1995,7 @@ function TransactionTableInner({
);
const onNotesTagClick = useCallback(
- noteTag => {
+ (noteTag: string) => {
onCloseAddTransactionProp();
onNotesTagClickProp(noteTag);
},
@@ -1855,7 +2017,11 @@ function TransactionTableInner({
[props.transactions, props.showReconciled],
);
- const renderRow = ({ item, index, editing }) => {
+ const renderRow: TableProps<TransactionEntity>['renderItem'] = ({
+ item,
+ index,
+ editing,
+ }) => {
const {
transactions,
selectedItems,
@@ -1864,7 +2030,6 @@ function TransactionTableInner({
payees,
showCleared,
showAccount,
- showCategory,
showBalances,
balances,
hideFraction,
@@ -1878,8 +2043,8 @@ function TransactionTableInner({
const trans = item;
const selected = selectedItems.has(trans.id);
- const parent = props.transactionMap.get(trans.parent_id);
- const isChildDeposit = parent && parent.amount > 0;
+ const parent = trans.parent_id && props.transactionMap.get(trans.parent_id);
+ const isChildDeposit = parent ? parent.amount > 0 : undefined;
const expanded = isExpanded && isExpanded((parent || trans).id);
// For backwards compatibility, read the error of the transaction
@@ -1899,7 +2064,7 @@ function TransactionTableInner({
? props.transactionsByParent[trans.id]
: null;
const emptyChildTransactions = props.transactionsByParent[
- trans.is_parent ? trans.id : trans.parent_id
+ (trans.is_parent ? trans.id : trans.parent_id) || ''
]?.filter(t => t.amount === 0);
return (
@@ -1910,7 +2075,6 @@ function TransactionTableInner({
transferAccountsByTransaction={props.transferAccountsByTransaction}
subtransactions={childTransactions}
showAccount={showAccount}
- showCategory={showCategory}
showBalance={showBalances}
showCleared={showCleared}
selected={selected}
@@ -1919,8 +2083,8 @@ function TransactionTableInner({
expanded={isExpanded?.(trans.id)}
matched={isMatched?.(trans.id)}
showZeroInDeposit={isChildDeposit}
- balance={balances?.[trans.id]?.balance}
- focusedField={editing && tableNavigator.focusedField}
+ balance={balances?.[trans.id]?.balance ?? 0}
+ focusedField={editing ? tableNavigator.focusedField : undefined}
accounts={accounts}
categoryGroups={categoryGroups}
payees={payees}
@@ -1946,7 +2110,7 @@ function TransactionTableInner({
hasSplitError && (
<TransactionError
error={error}
- isDeposit={isChildDeposit}
+ isDeposit={!!isChildDeposit}
onAddSplit={() => props.onAddSplit(trans.id)}
onDistributeRemainder={() =>
props.onDistributeRemainder(trans.id)
@@ -1988,7 +2152,7 @@ function TransactionTableInner({
{props.isAdding && (
<View
{...newNavigator.getNavigatorProps({
- onKeyDown: e => props.onCheckNewEnter(e),
+ onKeyDown: (e: KeyboardEvent) => props.onCheckNewEnter(e),
})}
>
<NewTransaction
@@ -2002,7 +2166,6 @@ function TransactionTableInner({
categoryGroups={props.categoryGroups}
payees={props.payees || []}
showAccount={props.showAccount}
- showCategory={props.showCategory}
showBalance={props.showBalances}
showCleared={props.showCleared}
dateFormat={dateFormat}
@@ -2010,6 +2173,7 @@ function TransactionTableInner({
onClose={props.onCloseAddTransaction}
onAdd={props.onAddTemporary}
onAddSplit={props.onAddSplit}
+ onToggleSplit={props.onToggleSplit}
onSplit={props.onSplit}
onEdit={newNavigator.onEdit}
onSave={props.onSave}
@@ -2046,7 +2210,6 @@ function TransactionTableInner({
loadMore={props.loadMoreTransactions}
isSelected={id => props.selectedItems.has(id)}
onKeyDown={e => props.onCheckEnter(e)}
- onScroll={onScroll}
saveScrollWidth={saveScrollWidth}
/>
@@ -2069,589 +2232,691 @@ function TransactionTableInner({
);
}
-export const TransactionTable = forwardRef((props, ref) => {
- const dispatch = useDispatch();
- const [newTransactions, setNewTransactions] = useState(null);
- const [prevIsAdding, setPrevIsAdding] = useState(false);
- const splitsExpanded = useSplitsExpanded();
- const splitsExpandedDispatch = splitsExpanded.dispatch;
- const prevSplitsExpanded = useRef(null);
-
- const tableRef = useRef(null);
- const listContainerRef = useRef(null);
- const mergedRef = useMergedRefs(tableRef, ref);
-
- const transactionsWithExpandedSplits = useMemo(() => {
- let result;
- if (splitsExpanded.state.transitionId != null) {
- const index = props.transactions.findIndex(
- t => t.id === splitsExpanded.state.transitionId,
- );
- result = props.transactions.filter((t, idx) => {
- if (t.parent_id) {
- if (idx >= index) {
- return splitsExpanded.isExpanded(t.parent_id);
- } else if (prevSplitsExpanded.current) {
- return prevSplitsExpanded.current.isExpanded(t.parent_id);
+type TableState = {
+ newTransactions: TransactionEntity[];
+ newNavigator: TableNavigator<TransactionEntity>;
+ tableNavigator: TableNavigator<TransactionEntity>;
+ transactions: readonly TransactionEntity[];
+};
+
+export type TransactionTableProps = {
+ transactions: readonly TransactionEntity[];
+ loadMoreTransactions: () => void;
+ accounts: AccountEntity[];
+ categoryGroups: CategoryGroupEntity[];
+ payees: PayeeEntity[];
+ balances: Record<TransactionEntity['id'], { balance: number }> | null;
+ showBalances: boolean;
+ showReconciled: boolean;
+ showCleared: boolean;
+ showAccount: boolean;
+ showCategory: boolean;
+ currentAccountId: AccountEntity['id'];
+ currentCategoryId: CategoryEntity['id'];
+ isAdding: boolean;
+ isNew: (id: TransactionEntity['id']) => boolean;
+ isMatched: (id: TransactionEntity['id']) => boolean;
+ dateFormat: string | undefined;
+ hideFraction: boolean;
+ renderEmpty: ReactNode | (() => ReactNode);
+ onSave: (transaction: TransactionEntity) => void;
+ onApplyRules: (
+ transaction: TransactionEntity,
+ field: string | null,
+ ) => Promise<TransactionEntity>;
+ onSplit: (id: TransactionEntity['id']) => TransactionEntity['id'];
+ onAddSplit: (id: TransactionEntity['id']) => TransactionEntity['id'];
+ onCloseAddTransaction: () => void;
+ onAdd: (transactions: TransactionEntity[]) => void;
+ onCreatePayee: (name: string) => Promise<null | PayeeEntity['id']>;
+ style?: CSSProperties;
+ onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
+ onNotesTagClick: (tag: string) => void;
+ onSort: (field: string, ascDesc: 'asc' | 'desc') => void;
+ sortField: string;
+ ascDesc: 'asc' | 'desc';
+ onBatchDelete: (ids: TransactionEntity['id'][]) => void;
+ onBatchDuplicate: (ids: TransactionEntity['id'][]) => void;
+ onBatchLinkSchedule: (ids: TransactionEntity['id'][]) => void;
+ onBatchUnlinkSchedule: (ids: TransactionEntity['id'][]) => void;
+ onCreateRule: (ids: RuleEntity['id'][]) => void;
+ onScheduleAction: (
+ name: 'skip' | 'post-transaction' | 'complete',
+ ids: TransactionEntity['id'][],
+ ) => void;
+ onMakeAsNonSplitTransactions: (ids: string[]) => void;
+ showSelection: boolean;
+ allowSplitTransaction?: boolean;
+ onManagePayees: (id?: PayeeEntity['id']) => void;
+};
+
+export const TransactionTable = forwardRef(
+ (
+ props: TransactionTableProps,
+ ref: ForwardedRef<TableHandleRef<TransactionEntity>>,
+ ) => {
+ const dispatch = useDispatch();
+ const [newTransactions, setNewTransactions] = useState<
+ TransactionEntity[] | null
+ >(null);
+ const [prevIsAdding, setPrevIsAdding] = useState(false);
+ const splitsExpanded = useSplitsExpanded();
+ const splitsExpandedDispatch = splitsExpanded.dispatch;
+ const prevSplitsExpanded = useRef<SplitsExpandedContextValue | null>(null);
+
+ const tableRef = useRef<TableHandleRef<TransactionEntity>>(null);
+ const listContainerRef = useRef<HTMLDivElement>(
+ null,
+ ) as RefObject<HTMLDivElement>;
+ const mergedRef = useMergedRefs(tableRef, ref);
+
+ const transactionsWithExpandedSplits = useMemo(() => {
+ let result: TransactionEntity[];
+ if (splitsExpanded.state.transitionId != null) {
+ const index = props.transactions.findIndex(
+ t => t.id === splitsExpanded.state.transitionId,
+ );
+ result = props.transactions.filter((t, idx) => {
+ if (t.parent_id) {
+ if (idx >= index) {
+ return splitsExpanded.isExpanded(t.parent_id);
+ } else if (prevSplitsExpanded.current) {
+ return prevSplitsExpanded.current.isExpanded(t.parent_id);
+ }
}
+ return true;
+ });
+ } else {
+ if (
+ prevSplitsExpanded.current &&
+ prevSplitsExpanded.current.state.transitionId != null
+ ) {
+ tableRef.current?.anchor();
+ tableRef.current?.setRowAnimation(false);
}
- return true;
- });
- } else {
- if (
- prevSplitsExpanded.current &&
- prevSplitsExpanded.current.state.transitionId != null
- ) {
- tableRef.current.anchor();
- tableRef.current.setRowAnimation(false);
+ prevSplitsExpanded.current = splitsExpanded;
+
+ result = props.transactions.filter(t => {
+ if (t.parent_id) {
+ return splitsExpanded.isExpanded(t.parent_id);
+ }
+ return true;
+ });
}
- prevSplitsExpanded.current = splitsExpanded;
- result = props.transactions.filter(t => {
- if (t.parent_id) {
- return splitsExpanded.isExpanded(t.parent_id);
- }
- return true;
- });
- }
+ prevSplitsExpanded.current = splitsExpanded;
+ return result;
+ }, [props.transactions, splitsExpanded]);
+ const transactionMap = useMemo(() => {
+ return new Map(
+ transactionsWithExpandedSplits.map(trans => [trans.id, trans]),
+ );
+ }, [transactionsWithExpandedSplits]);
+ const transactionsByParent = useMemo(() => {
+ return props.transactions.reduce(
+ (acc, trans) => {
+ if (trans.is_child && trans.parent_id) {
+ acc[trans.parent_id] = [...(acc[trans.parent_id] ?? []), trans];
+ }
+ return acc;
+ },
+ {} as { [parentId: TransactionEntity['id']]: TransactionEntity[] },
+ );
+ }, [props.transactions]);
- prevSplitsExpanded.current = splitsExpanded;
- return result;
- }, [props.transactions, splitsExpanded]);
- const transactionMap = useMemo(() => {
- return new Map(
- transactionsWithExpandedSplits.map(trans => [trans.id, trans]),
- );
- }, [transactionsWithExpandedSplits]);
- const transactionsByParent = useMemo(() => {
- return props.transactions.reduce((acc, trans) => {
- if (trans.is_child) {
- acc[trans.parent_id] = [...(acc[trans.parent_id] ?? []), trans];
+ const transferAccountsByTransaction = useMemo(() => {
+ if (!props.accounts) {
+ return {};
}
- return acc;
- }, {});
- }, [props.transactions]);
+ const accounts = getAccountsById(props.accounts);
+ const payees = getPayeesById(props.payees);
- const transferAccountsByTransaction = useMemo(() => {
- if (!props.accounts) {
- return {};
- }
- const accounts = getAccountsById(props.accounts);
- const payees = getPayeesById(props.payees);
-
- return Object.fromEntries(
- props.transactions.map(t => {
- if (!props.accounts) {
- return [t.id, null];
- }
+ return Object.fromEntries(
+ props.transactions.map(t => {
+ if (!props.accounts) {
+ return [t.id, null];
+ }
- const payee = t.payee && payees[t.payee];
- const transferAccount =
- payee?.transfer_acct && accounts[payee.transfer_acct];
- return [t.id, transferAccount || null];
- }),
- );
- }, [props.transactions, props.payees, props.accounts]);
+ const payee = (t.payee && payees[t.payee]) || undefined;
+ const transferAccount =
+ payee?.transfer_acct && accounts[payee.transfer_acct];
+ return [t.id, transferAccount || null];
+ }),
+ );
+ }, [props.transactions, props.payees, props.accounts]);
- const hasPrevSplitsExpanded = prevSplitsExpanded.current;
+ const hasPrevSplitsExpanded = prevSplitsExpanded.current;
- useEffect(() => {
- // If it's anchored that means we've also disabled animations. To
- // reduce the chance for side effect collision, only do this if
- // we've actually anchored it
- if (tableRef.current.isAnchored()) {
- tableRef.current.unanchor();
- tableRef.current.setRowAnimation(true);
- }
- }, [hasPrevSplitsExpanded]);
+ useEffect(() => {
+ // If it's anchored that means we've also disabled animations. To
+ // reduce the chance for side effect collision, only do this if
+ // we've actually anchored it
+ if (tableRef.current?.isAnchored()) {
+ tableRef.current.unanchor();
+ tableRef.current.setRowAnimation(true);
+ }
+ }, [hasPrevSplitsExpanded]);
- const newNavigator = useTableNavigator(
- newTransactions,
- getFieldsNewTransaction,
- );
+ const newNavigator = useTableNavigator(
+ newTransactions ?? [],
+ getFieldsNewTransaction,
+ );
- const tableNavigator = useTableNavigator(
- transactionsWithExpandedSplits,
- getFieldsTableTransaction,
- );
- const shouldAdd = useRef(false);
- const latestState = useRef({ newTransactions, newNavigator, tableNavigator });
- const savePending = useRef(false);
- const afterSaveFunc = useRef(false);
- const [_, forceRerender] = useState({});
- const selectedItems = useSelectedItems();
-
- latestState.current = {
- newTransactions,
- newNavigator,
- tableNavigator,
- transactions: props.transactions,
- };
+ const tableNavigator = useTableNavigator(
+ transactionsWithExpandedSplits,
+ getFieldsTableTransaction,
+ );
+ const shouldAdd = useRef(false);
+ const latestState = useRef<TableState>({
+ newTransactions: newTransactions ?? [],
+ newNavigator,
+ tableNavigator,
+ transactions: [],
+ });
+ const savePending = useRef(false);
+ const afterSaveFunc = useRef<null | (() => void)>(null);
+ const [_, forceRerender] = useState({});
+ const selectedItems = useSelectedItems();
+
+ latestState.current = {
+ newTransactions: newTransactions ?? [],
+ newNavigator,
+ tableNavigator,
+ transactions: props.transactions,
+ };
- // Derive new transactions from the `isAdding` prop
- if (prevIsAdding !== props.isAdding) {
- if (!prevIsAdding && props.isAdding) {
- setNewTransactions(
- makeTemporaryTransactions(
- props.currentAccountId,
- props.currentCategoryId,
- ),
- );
+ // Derive new transactions from the `isAdding` prop
+ if (prevIsAdding !== props.isAdding) {
+ if (!prevIsAdding && props.isAdding) {
+ setNewTransactions(
+ makeTemporaryTransactions(
+ props.currentAccountId,
+ props.currentCategoryId,
+ ),
+ );
+ }
+ setPrevIsAdding(props.isAdding);
}
- setPrevIsAdding(props.isAdding);
- }
- if (shouldAdd.current) {
- if (newTransactions[0].account == null) {
- dispatch(
- addNotification({
- notification: {
- type: 'error',
- message: 'Account is a required field',
- },
- }),
- );
- newNavigator.onEdit('temp', 'account');
- } else {
- const transactions = latestState.current.newTransactions;
- const lastDate = transactions.length > 0 ? transactions[0].date : null;
- setNewTransactions(
- makeTemporaryTransactions(
- props.currentAccountId,
- props.currentCategoryId,
- lastDate,
- ),
- );
- newNavigator.onEdit('temp', 'date');
- props.onAdd(transactions);
+ if (shouldAdd.current) {
+ if (newTransactions?.[0] && newTransactions[0].account == null) {
+ dispatch(
+ addNotification({
+ notification: {
+ type: 'error',
+ message: 'Account is a required field',
+ },
+ }),
+ );
+ newNavigator.onEdit('temp', 'account');
+ } else {
+ const transactions = latestState.current.newTransactions;
+ const lastDate = transactions.length > 0 ? transactions[0].date : null;
+ setNewTransactions(
+ makeTemporaryTransactions(
+ props.currentAccountId,
+ props.currentCategoryId,
+ lastDate,
+ ),
+ );
+ newNavigator.onEdit('temp', 'date');
+ props.onAdd(transactions);
+ }
+ shouldAdd.current = false;
}
- shouldAdd.current = false;
- }
- useEffect(() => {
- if (savePending.current && afterSaveFunc.current) {
- afterSaveFunc.current(props);
- afterSaveFunc.current = null;
+ useEffect(() => {
+ if (savePending.current && afterSaveFunc.current) {
+ afterSaveFunc.current();
+ afterSaveFunc.current = null;
+ }
+
+ savePending.current = false;
+ }, [newTransactions, props, props.transactions]);
+
+ function getFieldsNewTransaction(item?: TransactionEntity) {
+ const fields = [
+ 'select',
+ 'date',
+ 'account',
+ 'payee',
+ 'notes',
+ 'category',
+ 'debit',
+ 'credit',
+ 'cleared',
+ 'cancel',
+ 'add',
+ ];
+
+ return getFields(item, fields);
}
- savePending.current = false;
- }, [newTransactions, props, props.transactions]);
-
- function getFieldsNewTransaction(item) {
- const fields = [
- 'select',
- 'date',
- 'account',
- 'payee',
- 'notes',
- 'category',
- 'debit',
- 'credit',
- 'cleared',
- 'cancel',
- 'add',
- ];
-
- return getFields(item, fields);
- }
+ function getFieldsTableTransaction(item?: TransactionEntity) {
+ const fields = [
+ 'select',
+ 'date',
+ 'account',
+ 'payee',
+ 'notes',
+ 'category',
+ 'debit',
+ 'credit',
+ 'cleared',
+ ];
+
+ return getFields(item, fields);
+ }
- function getFieldsTableTransaction(item) {
- const fields = [
- 'select',
- 'date',
- 'account',
- 'payee',
- 'notes',
- 'category',
- 'debit',
- 'credit',
- 'cleared',
- ];
-
- return getFields(item, fields);
- }
+ function getFields(item: TransactionEntity | undefined, fields: string[]) {
+ fields = item?.is_child
+ ? ['select', 'payee', 'notes', 'category', 'debit', 'credit']
+ : fields.filter(
+ f =>
+ (props.showAccount || f !== 'account') &&
+ (props.showCategory || f !== 'category'),
+ );
- function getFields(item, fields) {
- fields = item.is_child
- ? ['select', 'payee', 'notes', 'category', 'debit', 'credit']
- : fields.filter(
- f =>
- (props.showAccount || f !== 'account') &&
- (props.showCategory || f !== 'category'),
- );
+ if (item?.id && isPreviewId(item.id)) {
+ fields = ['select'];
+ }
+ if (item?.id && isTemporaryId(item.id)) {
+ // You can't focus the select/delete button of temporary
+ // transactions
+ fields = fields.slice(1);
+ }
- if (isPreviewId(item.id)) {
- fields = ['select'];
+ return fields;
}
- if (isTemporaryId(item.id)) {
- // You can't focus the select/delete button of temporary
- // transactions
- fields = fields.slice(1);
+
+ function afterSave(func: () => void) {
+ if (savePending.current) {
+ afterSaveFunc.current = func;
+ } else {
+ func();
+ }
}
- return fields;
- }
+ function onCheckNewEnter(e: KeyboardEvent) {
+ if (e.key === 'Enter') {
+ if (e.metaKey) {
+ e.stopPropagation();
+ onAddTemporary();
+ } else if (!e.shiftKey) {
+ function getLastTransaction(state: RefObject<TableState>) {
+ const { newTransactions } = state.current;
+ return newTransactions[newTransactions.length - 1];
+ }
- function afterSave(func) {
- if (savePending.current) {
- afterSaveFunc.current = func;
- } else {
- func(props);
- }
- }
+ // Right now, the table navigator does some funky stuff with
+ // focus, so we want to stop it from handling this event. We
+ // still want enter to move up/down normally, so we only stop
+ // it if we are on the last transaction (where we are about to
+ // do some logic). I don't like this.
+ if (newNavigator.editingId === getLastTransaction(latestState).id) {
+ e.stopPropagation();
+ }
- function onCheckNewEnter(e) {
- if (e.key === 'Enter') {
- if (e.metaKey) {
- e.stopPropagation();
- onAddTemporary();
- } else if (!e.shiftKey) {
- function getLastTransaction(state) {
- const { newTransactions } = state.current;
- return newTransactions[newTransactions.length - 1];
+ afterSave(() => {
+ const lastTransaction = getLastTransaction(latestState);
+ const isSplit =
+ lastTransaction.parent_id || lastTransaction.is_parent;
+
+ if (
+ latestState.current.newTransactions[0].error &&
+ newNavigator.editingId === lastTransaction.id
+ ) {
+ // add split
+ onAddSplit(lastTransaction.id);
+ } else if (
+ newNavigator.editingId === lastTransaction.id &&
+ (!isSplit || !lastTransaction.error)
+ ) {
+ onAddTemporary();
+ }
+ });
}
+ }
+ }
- // Right now, the table navigator does some funky stuff with
- // focus, so we want to stop it from handling this event. We
- // still want enter to move up/down normally, so we only stop
- // it if we are on the last transaction (where we are about to
- // do some logic). I don't like this.
- if (newNavigator.editingId === getLastTransaction(latestState).id) {
- e.stopPropagation();
- }
+ function onCheckEnter(e: KeyboardEvent) {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ const { editingId: id, focusedField } = tableNavigator;
afterSave(() => {
- const lastTransaction = getLastTransaction(latestState);
- const isSplit =
- lastTransaction.parent_id || lastTransaction.is_parent;
+ const transactions = latestState.current.transactions;
+ const idx = transactions.findIndex(t => t.id === id);
+ const parent = transactions.find(
+ t => t.id === transactions[idx]?.parent_id,
+ );
if (
- latestState.current.newTransactions[0].error &&
- newNavigator.editingId === lastTransaction.id
- ) {
- // add split
- onAddSplit(lastTransaction.id);
- } else if (
- newNavigator.editingId === lastTransaction.id &&
- (!isSplit || !lastTransaction.error)
+ isLastChild(transactions, idx) &&
+ parent &&
+ parent.error &&
+ focusedField !== 'select'
) {
- onAddTemporary();
+ e.stopPropagation();
+ onAddSplit(id);
}
});
}
}
- }
-
- function onCheckEnter(e) {
- if (e.key === 'Enter' && !e.shiftKey) {
- const { editingId: id, focusedField } = tableNavigator;
-
- afterSave(() => {
- const transactions = latestState.current.transactions;
- const idx = transactions.findIndex(t => t.id === id);
- const parent = transactions.find(
- t => t.id === transactions[idx]?.parent_id,
- );
-
- if (
- isLastChild(transactions, idx) &&
- parent &&
- parent.error &&
- focusedField !== 'select'
- ) {
- e.stopPropagation();
- onAddSplit(id);
- }
- });
- }
- }
-
- const onAddTemporary = useCallback(() => {
- shouldAdd.current = true;
- // A little hacky - this forces a rerender which will cause the
- // effect we want to run. We have to wait for all updates to be
- // committed (the input could still be saving a value).
- forceRerender({});
- }, []);
- const {
- onSave: onSaveProp,
- onApplyRules: onApplyRulesProp,
- onBatchDelete,
- onBatchDuplicate,
- onBatchLinkSchedule,
- onBatchUnlinkSchedule,
- onCreateRule: onCreateRuleProp,
- onScheduleAction: onScheduleActionProp,
- onMakeAsNonSplitTransactions: onMakeAsNonSplitTransactionsProp,
- onSplit: onSplitProp,
- } = props;
+ const onAddTemporary = useCallback(() => {
+ shouldAdd.current = true;
+ // A little hacky - this forces a rerender which will cause the
+ // effect we want to run. We have to wait for all updates to be
+ // committed (the input could still be saving a value).
+ forceRerender({});
+ }, []);
- const onSave = useCallback(
- async (transaction, subtransactions = null, updatedFieldName = null) => {
- savePending.current = true;
+ const {
+ onSave: onSaveProp,
+ onApplyRules: onApplyRulesProp,
+ onBatchDelete,
+ onBatchDuplicate,
+ onBatchLinkSchedule,
+ onBatchUnlinkSchedule,
+ onCreateRule: onCreateRuleProp,
+ onScheduleAction: onScheduleActionProp,
+ onMakeAsNonSplitTransactions: onMakeAsNonSplitTransactionsProp,
+ onSplit: onSplitProp,
+ } = props;
- let groupedTransaction = subtransactions
- ? groupTransaction([transaction, ...subtransactions])
- : transaction;
+ const onSave = useCallback(
+ async (
+ transaction: TransactionEntity,
+ subtransactions: TransactionEntity[] | null = null,
+ updatedFieldName: keyof TransactionEntity | null = null,
+ ) => {
+ savePending.current = true;
+
+ let groupedTransaction = subtransactions
+ ? groupTransaction([transaction, ...subtransactions])
+ : transaction;
+
+ if (isTemporaryId(transaction.id)) {
+ if (onApplyRulesProp) {
+ groupedTransaction = await onApplyRulesProp(
+ groupedTransaction,
+ updatedFieldName,
+ );
+ }
- if (isTemporaryId(transaction.id)) {
- if (onApplyRulesProp) {
- groupedTransaction = await onApplyRulesProp(
- groupedTransaction,
- updatedFieldName,
+ const newTrans = latestState.current.newTransactions;
+ // Future refactor: we shouldn't need to iterate through the entire
+ // transaction list to ungroup, just the new transactions.
+ setNewTransactions(
+ ungroupTransactions(
+ updateTransaction(newTrans, groupedTransaction).data,
+ ),
);
+ } else {
+ onSaveProp(groupedTransaction);
}
+ },
+ [onSaveProp, onApplyRulesProp],
+ );
- const newTrans = latestState.current.newTransactions;
- // Future refactor: we shouldn't need to iterate through the entire
- // transaction list to ungroup, just the new transactions.
- setNewTransactions(
- ungroupTransactions(
- updateTransaction(newTrans, groupedTransaction).data,
- ),
- );
- } else {
- onSaveProp(groupedTransaction);
- }
- },
- [onSaveProp, onApplyRulesProp],
- );
+ const onDelete = useCallback(
+ (id: TransactionEntity['id']) => {
+ const temporary = isTemporaryId(id);
- const onDelete = useCallback(
- id => {
- const temporary = isTemporaryId(id);
+ if (temporary) {
+ const newTrans = latestState.current.newTransactions;
- if (temporary) {
- const newTrans = latestState.current.newTransactions;
+ if (id === newTrans[0].id) {
+ // You can never delete the parent new transaction
+ return;
+ }
- if (id === newTrans[0].id) {
- // You can never delete the parent new transaction
- return;
+ setNewTransactions(deleteTransaction(newTrans, id).data);
+ } else {
+ onBatchDelete([id]);
}
+ },
+ [onBatchDelete],
+ );
- setNewTransactions(deleteTransaction(newTrans, id).data);
- } else {
- onBatchDelete([id]);
- }
- },
- [onBatchDelete],
- );
-
- const onDuplicate = useCallback(
- id => {
- onBatchDuplicate([id]);
- },
- [onBatchDuplicate],
- );
+ const onDuplicate = useCallback(
+ (id: TransactionEntity['id']) => {
+ onBatchDuplicate([id]);
+ },
+ [onBatchDuplicate],
+ );
- const onLinkSchedule = useCallback(
- id => {
- onBatchLinkSchedule([id]);
- },
- [onBatchLinkSchedule],
- );
- const onUnlinkSchedule = useCallback(
- id => {
- onBatchUnlinkSchedule([id]);
- },
- [onBatchUnlinkSchedule],
- );
- const onCreateRule = useCallback(
- id => {
- onCreateRuleProp([id]);
- },
- [onCreateRuleProp],
- );
- const onScheduleAction = useCallback(
- (action, id) => {
- onScheduleActionProp(action, [id]);
- },
- [onScheduleActionProp],
- );
- const onMakeAsNonSplitTransactions = useCallback(
- id => {
- onMakeAsNonSplitTransactionsProp([id]);
- },
- [onMakeAsNonSplitTransactionsProp],
- );
+ const onLinkSchedule = useCallback(
+ (id: TransactionEntity['id']) => {
+ onBatchLinkSchedule([id]);
+ },
+ [onBatchLinkSchedule],
+ );
+ const onUnlinkSchedule = useCallback(
+ (id: TransactionEntity['id']) => {
+ onBatchUnlinkSchedule([id]);
+ },
+ [onBatchUnlinkSchedule],
+ );
+ const onCreateRule = useCallback(
+ (id: TransactionEntity['id']) => {
+ onCreateRuleProp([id]);
+ },
+ [onCreateRuleProp],
+ );
+ const onScheduleAction = useCallback(
+ (
+ action: 'skip' | 'post-transaction' | 'complete',
+ id: TransactionEntity['id'],
+ ) => {
+ onScheduleActionProp(action, [id]);
+ },
+ [onScheduleActionProp],
+ );
+ const onMakeAsNonSplitTransactions = useCallback(
+ (id: TransactionEntity['id']) => {
+ onMakeAsNonSplitTransactionsProp([id]);
+ },
+ [onMakeAsNonSplitTransactionsProp],
+ );
- const onSplit = useMemo(() => {
- return id => {
- if (isTemporaryId(id)) {
- const { newNavigator } = latestState.current;
- const newTrans = latestState.current.newTransactions;
- const { data, diff } = splitTransaction(newTrans, id);
- setNewTransactions(data);
-
- // Jump next to "debit" field if it is empty
- // Otherwise jump to the same field as before, but downwards
- // to the added split transaction
- if (newTrans[0].amount === null) {
- newNavigator.onEdit(newTrans[0].id, 'debit');
+ const onSplit = useMemo(() => {
+ return (id: TransactionEntity['id']) => {
+ if (isTemporaryId(id)) {
+ const { newNavigator } = latestState.current;
+ const newTrans = latestState.current.newTransactions;
+ const { data, diff } = splitTransaction(newTrans, id);
+ setNewTransactions(data);
+
+ // Jump next to "debit" field if it is empty
+ // Otherwise jump to the same field as before, but downwards
+ // to the added split transaction
+ if (newTrans[0].amount === null) {
+ newNavigator.onEdit(newTrans[0].id, 'debit');
+ } else {
+ newNavigator.onEdit(
+ diff.added[0].id,
+ latestState.current.newNavigator.focusedField,
+ );
+ }
} else {
+ const trans = latestState.current.transactions.find(t => t.id === id);
+ const newId = onSplitProp(id);
+ if (!trans) {
+ return;
+ }
+
+ splitsExpandedDispatch({ type: 'open-split', id: trans.id });
+
+ const { tableNavigator } = latestState.current;
+ if (trans.amount === null) {
+ tableNavigator.onEdit(trans.id, 'debit');
+ } else {
+ tableNavigator.onEdit(newId, tableNavigator.focusedField);
+ }
+ }
+ };
+ }, [onSplitProp, splitsExpandedDispatch]);
+
+ const { onAddSplit: onAddSplitProp } = props;
+
+ const onAddSplit = useCallback(
+ (id: TransactionEntity['id']) => {
+ const {
+ tableNavigator,
+ newNavigator,
+ newTransactions: newTrans,
+ } = latestState.current;
+
+ if (isTemporaryId(id)) {
+ const { data, diff } = addSplitTransaction(newTrans, id);
+ setNewTransactions(data);
newNavigator.onEdit(
diff.added[0].id,
latestState.current.newNavigator.focusedField,
);
- }
- } else {
- const trans = latestState.current.transactions.find(t => t.id === id);
- const newId = onSplitProp(id);
-
- splitsExpandedDispatch({ type: 'open-split', id: trans.id });
-
- const { tableNavigator } = latestState.current;
- if (trans.amount === null) {
- tableNavigator.onEdit(trans.id, 'debit');
} else {
- tableNavigator.onEdit(newId, tableNavigator.focusedField);
+ const newId = onAddSplitProp(id);
+ tableNavigator.onEdit(
+ newId,
+ latestState.current.tableNavigator.focusedField,
+ );
}
- }
- };
- }, [onSplitProp, splitsExpandedDispatch]);
-
- const { onAddSplit: onAddSplitProp } = props;
-
- const onAddSplit = useCallback(
- id => {
- const {
- tableNavigator,
- newNavigator,
- newTransactions: newTrans,
- } = latestState.current;
-
- if (isTemporaryId(id)) {
- const { data, diff } = addSplitTransaction(newTrans, id);
- setNewTransactions(data);
- newNavigator.onEdit(
- diff.added[0].id,
- latestState.current.newNavigator.focusedField,
+ },
+ [onAddSplitProp],
+ );
+
+ const onDistributeRemainder = useCallback(
+ async (id: TransactionEntity['id']) => {
+ const { transactions, newNavigator, tableNavigator, newTransactions } =
+ latestState.current;
+
+ const targetTransactions = isTemporaryId(id)
+ ? newTransactions
+ : transactions;
+ const transaction = targetTransactions.find(t => t.id === id);
+
+ const parentTransaction = transaction?.is_parent
+ ? transaction
+ : targetTransactions.find(t => t.id === transaction?.parent_id);
+
+ const siblingTransactions = targetTransactions.filter(
+ t =>
+ t.parent_id &&
+ t.parent_id ===
+ (transaction?.is_parent
+ ? transaction?.id
+ : transaction?.parent_id),
);
- } else {
- const newId = onAddSplitProp(id);
- tableNavigator.onEdit(
- newId,
- latestState.current.tableNavigator.focusedField,
+
+ const emptyTransactions = siblingTransactions.filter(
+ t => t.amount === 0,
);
- }
- },
- [onAddSplitProp],
- );
+ if (!parentTransaction) {
+ console.error(
+ 'Parent transaction not found for transaction',
+ transaction,
+ );
+ return;
+ }
- const onDistributeRemainder = useCallback(
- async id => {
- const { transactions, newNavigator, tableNavigator, newTransactions } =
- latestState.current;
+ const remainingAmount =
+ parentTransaction.amount -
+ siblingTransactions.reduce((acc, t) => acc + t.amount, 0);
- const targetTransactions = isTemporaryId(id)
- ? newTransactions
- : transactions;
- const transaction = targetTransactions.find(t => t.id === id);
+ const amountPerTransaction = Math.floor(
+ remainingAmount / emptyTransactions.length,
+ );
+ let remainingCents =
+ remainingAmount - amountPerTransaction * emptyTransactions.length;
- const parentTransaction = transaction.is_parent
- ? transaction
- : targetTransactions.find(t => t.id === transaction.parent_id);
+ const amounts = new Array(emptyTransactions.length).fill(
+ amountPerTransaction,
+ );
- const siblingTransactions = targetTransactions.filter(
- t =>
- t.parent_id ===
- (transaction.is_parent ? transaction.id : transaction.parent_id),
- );
+ for (const amountIndex in amounts) {
+ if (remainingCents === 0) break;
- const emptyTransactions = siblingTransactions.filter(t => t.amount === 0);
+ amounts[amountIndex] += 1;
+ remainingCents--;
+ }
- const remainingAmount =
- parentTransaction.amount -
- siblingTransactions.reduce((acc, t) => acc + t.amount, 0);
+ if (isTemporaryId(id)) {
+ newNavigator.onEdit(null);
+ } else {
+ tableNavigator.onEdit(null);
+ }
- const amountPerTransaction = Math.floor(
- remainingAmount / emptyTransactions.length,
- );
- let remainingCents =
- remainingAmount - amountPerTransaction * emptyTransactions.length;
+ for (const transactionIndex in emptyTransactions) {
+ await onSave({
+ ...emptyTransactions[transactionIndex],
+ amount: amounts[transactionIndex],
+ });
+ }
+ },
+ [onSave],
+ );
- const amounts = new Array(emptyTransactions.length).fill(
- amountPerTransaction,
+ function onCloseAddTransaction() {
+ setNewTransactions(
+ makeTemporaryTransactions(
+ props.currentAccountId,
+ props.currentCategoryId,
+ ),
);
+ props.onCloseAddTransaction();
+ }
- for (const amountIndex in amounts) {
- if (remainingCents === 0) break;
-
- amounts[amountIndex] += 1;
- remainingCents--;
- }
-
- if (isTemporaryId(id)) {
- newNavigator.onEdit(null);
- } else {
- tableNavigator.onEdit(null);
- }
-
- for (const transactionIndex in emptyTransactions) {
- await onSave({
- ...emptyTransactions[transactionIndex],
- amount: amounts[transactionIndex],
- });
- }
- },
- [onSave],
- );
-
- function onCloseAddTransaction() {
- setNewTransactions(
- makeTemporaryTransactions(
- props.currentAccountId,
- props.currentCategoryId,
- ),
+ const onToggleSplit = useCallback(
+ (id: TransactionEntity['id']) =>
+ splitsExpandedDispatch({ type: 'toggle-split', id }),
+ [splitsExpandedDispatch],
);
- props.onCloseAddTransaction();
- }
- const onToggleSplit = useCallback(
- id => splitsExpandedDispatch({ type: 'toggle-split', id }),
- [splitsExpandedDispatch],
- );
-
- return (
- <TransactionTableInner
- tableRef={mergedRef}
- listContainerRef={listContainerRef}
- {...props}
- transactions={transactionsWithExpandedSplits}
- transactionMap={transactionMap}
- transactionsByParent={transactionsByParent}
- transferAccountsByTransaction={transferAccountsByTransaction}
- selectedItems={selectedItems}
- isExpanded={splitsExpanded.isExpanded}
- onSave={onSave}
- onDelete={onDelete}
- onDuplicate={onDuplicate}
- onLinkSchedule={onLinkSchedule}
- onUnlinkSchedule={onUnlinkSchedule}
- onCreateRule={onCreateRule}
- onScheduleAction={onScheduleAction}
- onMakeAsNonSplitTransactions={onMakeAsNonSplitTransactions}
- onSplit={onSplit}
- onCheckNewEnter={onCheckNewEnter}
- onCheckEnter={onCheckEnter}
- onAddTemporary={onAddTemporary}
- onAddSplit={onAddSplit}
- onDistributeRemainder={onDistributeRemainder}
- onCloseAddTransaction={onCloseAddTransaction}
- onToggleSplit={onToggleSplit}
- newTransactions={newTransactions}
- tableNavigator={tableNavigator}
- newNavigator={newNavigator}
- showSelection={props.showSelection}
- allowSplitTransaction={props.allowSplitTransaction}
- />
- );
-});
+ return (
+ <TransactionTableInner
+ tableRef={mergedRef}
+ listContainerRef={listContainerRef}
+ {...props}
+ transactions={transactionsWithExpandedSplits}
+ transactionMap={transactionMap}
+ transactionsByParent={transactionsByParent}
+ transferAccountsByTransaction={transferAccountsByTransaction}
+ selectedItems={selectedItems}
+ isExpanded={splitsExpanded.isExpanded}
+ onSave={onSave}
+ onDelete={onDelete}
+ onDuplicate={onDuplicate}
+ onLinkSchedule={onLinkSchedule}
+ onUnlinkSchedule={onUnlinkSchedule}
+ onCreateRule={onCreateRule}
+ onScheduleAction={onScheduleAction}
+ onMakeAsNonSplitTransactions={onMakeAsNonSplitTransactions}
+ onSplit={onSplit}
+ onCheckNewEnter={onCheckNewEnter}
+ onCheckEnter={onCheckEnter}
+ onAddTemporary={onAddTemporary}
+ onAddSplit={onAddSplit}
+ onDistributeRemainder={onDistributeRemainder}
+ onCloseAddTransaction={onCloseAddTransaction}
+ onToggleSplit={onToggleSplit}
+ newTransactions={newTransactions ?? []}
+ tableNavigator={tableNavigator}
+ newNavigator={newNavigator}
+ showSelection={props.showSelection}
+ allowSplitTransaction={props.allowSplitTransaction}
+ />
+ );
+ },
+);
TransactionTable.displayName = 'TransactionTable';
-function notesTagFormatter(notes, onNotesTagClick) {
+function notesTagFormatter(
+ notes: string,
+ onNotesTagClick: (tag: string) => void,
+) {
const words = notes.split(' ');
return (
<>
diff --git a/packages/desktop-client/src/components/transactions/table/utils.ts b/packages/desktop-client/src/components/transactions/table/utils.ts
new file mode 100644
index 0000000000..1e0e34dd5c
--- /dev/null
+++ b/packages/desktop-client/src/components/transactions/table/utils.ts
@@ -0,0 +1,140 @@
+import { parseISO, isValid as isDateValid } from 'date-fns';
+
+import { evalArithmetic } from 'loot-core/shared/arithmetic';
+import { currentDay } from 'loot-core/shared/months';
+import {
+ amountToInteger,
+ type CurrencyAmount,
+ integerToCurrency,
+} from 'loot-core/shared/util';
+import {
+ type AccountEntity,
+ type CategoryEntity,
+ type TransactionEntity,
+} from 'loot-core/types/models';
+
+export type SerializedTransaction = Omit<TransactionEntity, 'date'> & {
+ date: string;
+ debit: CurrencyAmount;
+ credit: CurrencyAmount;
+};
+
+export type TransactionEditFunction = (
+ id: TransactionEntity['id'],
+ name: string,
+) => void;
+
+export type TransactionUpdateFunction = <T extends keyof SerializedTransaction>(
+ name: T,
+ value: SerializedTransaction[T],
+) => void;
+
+export function serializeTransaction(
+ transaction: TransactionEntity,
+ showZeroInDeposit?: boolean,
+): SerializedTransaction {
+ const { amount, date: originalDate } = transaction;
+
+ let debit = amount < 0 ? -amount : null;
+ let credit = amount > 0 ? amount : null;
+
+ if (amount === 0) {
+ if (showZeroInDeposit) {
+ credit = 0;
+ } else {
+ debit = 0;
+ }
+ }
+
+ let date = originalDate;
+ // Validate the date format
+ if (!isDateValid(parseISO(date))) {
+ // Be a little forgiving if the date isn't valid. This at least
+ // stops the UI from crashing, but this is a serious problem with
+ // the data. This allows the user to go through and see empty
+ // dates and manually fix them.
+ console.error(`Date ‘${date}’ is not valid.`);
+ // TODO: the fact that the date type is not nullable but we are setting it to null needs to be changed
+ date = null as unknown as string;
+ }
+
+ return {
+ ...transaction,
+ date,
+ debit: debit != null ? integerToCurrency(debit) : '',
+ credit: credit != null ? integerToCurrency(credit) : '',
+ };
+}
+
+export function deserializeTransaction(
+ transaction: SerializedTransaction,
+ originalTransaction: TransactionEntity,
+) {
+ const { debit, credit, date: originalDate, ...realTransaction } = transaction;
+
+ let amount: number | null;
+ if (debit !== '') {
+ const parsed = evalArithmetic(debit, null);
+ amount = parsed != null ? -parsed : null;
+ } else {
+ amount = evalArithmetic(credit, null);
+ }
+
+ amount =
+ amount != null ? amountToInteger(amount) : originalTransaction.amount;
+ let date = originalDate;
+ if (date == null) {
+ date = originalTransaction.date || currentDay();
+ }
+
+ return { ...realTransaction, date, amount };
+}
+
+export function isLastChild(
+ transactions: readonly TransactionEntity[],
+ index: number,
+) {
+ const trans = transactions[index];
+ return (
+ trans &&
+ trans.is_child &&
+ (transactions[index + 1] == null ||
+ transactions[index + 1].parent_id !== trans.parent_id)
+ );
+}
+
+export function selectAscDesc(
+ field: string,
+ ascDesc: 'asc' | 'desc',
+ clicked: string,
+ defaultAscDesc: 'asc' | 'desc' = 'asc',
+) {
+ return field === clicked
+ ? ascDesc === 'asc'
+ ? 'desc'
+ : 'asc'
+ : defaultAscDesc;
+}
+
+export function getDisplayValue<T>(obj: T | null | undefined, name: keyof T) {
+ return obj ? obj[name] : '';
+}
+
+export function makeTemporaryTransactions(
+ currentAccountId: AccountEntity['id'] | null | undefined,
+ currentCategoryId: CategoryEntity['id'] | null | undefined,
+ lastDate?: string | null,
+): TransactionEntity[] {
+ return [
+ {
+ id: 'temp',
+ date: lastDate || currentDay(),
+ // TODO: consider making this default to an empty string
+ account: (currentAccountId || null) as string,
+ category: currentCategoryId || undefined,
+ cleared: false,
+ // TODO: either make this nullable or find a way to make this not null
+ amount: null as unknown as number,
+ },
+ ];
+}
diff --git a/packages/desktop-client/src/hooks/useProperFocus.tsx b/packages/desktop-client/src/hooks/useProperFocus.tsx
index f7036303cf..ffb7439a84 100644
--- a/packages/desktop-client/src/hooks/useProperFocus.tsx
+++ b/packages/desktop-client/src/hooks/useProperFocus.tsx
@@ -75,7 +75,7 @@ export function AvoidRefocusScrollProvider({
}
export function useProperFocus(
- ref: RefObject<HTMLElement>,
+ ref: RefObject<HTMLElement | null>,
shouldFocus = false,
): void {
const context = useContext(AvoidRefocusScrollContext);
diff --git a/packages/desktop-client/src/hooks/useSplitsExpanded.tsx b/packages/desktop-client/src/hooks/useSplitsExpanded.tsx
index 69c3675dec..8f3051bf27 100644
--- a/packages/desktop-client/src/hooks/useSplitsExpanded.tsx
+++ b/packages/desktop-client/src/hooks/useSplitsExpanded.tsx
@@ -69,11 +69,15 @@ const SplitsExpandedContext = createContext<SplitsStateContext>({
},
});
+export type SplitsExpandedContextValue = {
+ isExpanded: (id: string) => boolean;
+} & SplitsStateContext;
+
export function useSplitsExpanded() {
const data = useContext(SplitsExpandedContext);
return useMemo(
- () => ({
+ (): SplitsExpandedContextValue => ({
...data,
isExpanded: (id: string) => {
return data.state.mode === 'collapse'
diff --git a/packages/desktop-client/src/queries/queriesSlice.ts b/packages/desktop-client/src/queries/queriesSlice.ts
index bd47de26ca..17158bcd48 100644
--- a/packages/desktop-client/src/queries/queriesSlice.ts
+++ b/packages/desktop-client/src/queries/queriesSlice.ts
@@ -830,21 +830,23 @@ export const getActivePayees = memoizeOne(
},
);
-export const getAccountsById = memoizeOne((accounts: AccountEntity[]) =>
- groupById(accounts),
+export const getAccountsById = memoizeOne(
+ (accounts: AccountEntity[] | null | undefined) => groupById(accounts),
);
-export const getPayeesById = memoizeOne((payees: PayeeEntity[]) =>
- groupById(payees),
+export const getPayeesById = memoizeOne(
+ (payees: PayeeEntity[] | null | undefined) => groupById(payees),
);
-export const getCategoriesById = memoizeOne(categoryGroups => {
- const res = {};
- categoryGroups.forEach(group => {
- group.categories.forEach(cat => {
- res[cat.id] = cat;
+export const getCategoriesById = memoizeOne(
+ (categoryGroups: CategoryGroupEntity[] | null | undefined) => {
+ const res: { [id: CategoryGroupEntity['id']]: CategoryEntity } = {};
+ categoryGroups?.forEach(group => {
+ group.categories.forEach(cat => {
+ res[cat.id] = cat;
+ });
});
- });
- return res;
-});
+ return res;
+ },
+);
// Slice exports
diff --git a/packages/loot-core/src/shared/arithmetic.ts b/packages/loot-core/src/shared/arithmetic.ts
index 0d595d1b77..707244c06b 100644
--- a/packages/loot-core/src/shared/arithmetic.ts
+++ b/packages/loot-core/src/shared/arithmetic.ts
@@ -111,8 +111,8 @@ function evaluate(ast): number {
export function evalArithmetic(
expression: string,
- defaultValue: number = null,
-) {
+ defaultValue: number | null = null,
+): number {
// An empty expression always evals to the default
if (expression === '') {
return defaultValue;
diff --git a/packages/loot-core/src/shared/transactions.ts b/packages/loot-core/src/shared/transactions.ts
index afd3b7229c..bf5c4a5d1c 100644
--- a/packages/loot-core/src/shared/transactions.ts
+++ b/packages/loot-core/src/shared/transactions.ts
@@ -87,7 +87,10 @@ export function recalculateSplit(trans: TransactionEntity) {
} satisfies TransactionEntity;
}
-function findParentIndex(transactions: TransactionEntity[], idx: number) {
+function findParentIndex(
+ transactions: readonly TransactionEntity[],
+ idx: number,
+) {
// This relies on transactions being sorted in a way where parents
// are always before children, which is enforced in the db layer.
// Walk backwards and find the last parent;
@@ -101,7 +104,10 @@ function findParentIndex(transactions: TransactionEntity[], idx: number) {
return null;
}
-function getSplit(transactions: TransactionEntity[], parentIndex: number) {
+function getSplit(
+ transactions: readonly TransactionEntity[],
+ parentIndex: number,
+) {
const split = [transactions[parentIndex]];
let curr = parentIndex + 1;
while (curr < transactions.length && transactions[curr].is_child) {
@@ -125,7 +131,9 @@ export function ungroupTransactions(transactions: TransactionEntity[]) {
}, []);
}
-export function groupTransaction(split: TransactionEntity[]) {
+export function groupTransaction(
+ split: TransactionEntity[],
+): TransactionEntity {
return {
...split[0],
subtransactions: split.slice(1),
@@ -152,7 +160,7 @@ export function applyTransactionDiff(
}
function replaceTransactions(
- transactions: TransactionEntity[],
+ transactions: readonly TransactionEntity[],
id: string,
func: (transaction: TransactionEntity) => TransactionEntity | null,
): {
@@ -216,7 +224,7 @@ function replaceTransactions(
}
export function addSplitTransaction(
- transactions: TransactionEntity[],
+ transactions: readonly TransactionEntity[],
id: string,
) {
return replaceTransactions(transactions, id, trans => {
@@ -235,7 +243,7 @@ export function addSplitTransaction(
}
export function updateTransaction(
- transactions: TransactionEntity[],
+ transactions: readonly TransactionEntity[],
transaction: TransactionEntity,
) {
return replaceTransactions(transactions, transaction.id, trans => {
@@ -302,7 +310,7 @@ export function deleteTransaction(
}
export function splitTransaction(
- transactions: TransactionEntity[],
+ transactions: readonly TransactionEntity[],
id: string,
createSubtransactions?: (
parentTransaction: TransactionEntity,
diff --git a/packages/loot-core/src/shared/util.ts b/packages/loot-core/src/shared/util.ts
index 9b537a1ead..15220d6a3e 100644
--- a/packages/loot-core/src/shared/util.ts
+++ b/packages/loot-core/src/shared/util.ts
@@ -151,8 +151,11 @@ export function diffItems<T extends { id: string }>(
}
export function groupById<T extends { id: string }>(
- data: T[],
+ data: T[] | null | undefined,
): Record<string, T> {
+ if (!data) {
+ return {};
+ }
const res: { [key: string]: T } = {};
for (let i = 0; i < data.length; i++) {
const item = data[i];
diff --git a/upcoming-release-notes/4930.md b/upcoming-release-notes/4930.md
new file mode 100644
index 0000000000..53f8c6379b
--- /dev/null
+++ b/upcoming-release-notes/4930.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [alecbakholdin]
+---
+
+Beginning of transition of Transactions table to TS