Newer
Older
import React, {
useState,
useRef,
useMemo,
useCallback,
useLayoutEffect,
useEffect,
useContext,
} from 'react';
import { useSelector, useDispatch } from 'react-redux';
isValid as isDateValid,
import { useCachedSchedules } from 'loot-core/src/client/data-hooks/schedules';
getCategoriesById,
import evalArithmetic from 'loot-core/src/shared/arithmetic';
import { currentDay } from 'loot-core/src/shared/months';
import { getScheduledAmount } from 'loot-core/src/shared/schedules';
import {
splitTransaction,
updateTransaction,
deleteTransaction,
addSplitTransaction,
import {
integerToCurrency,
amountToInteger,
} from 'loot-core/src/shared/util';
import AccountAutocomplete from 'loot-design/src/components/AccountAutocomplete';
import CategoryAutocomplete from 'loot-design/src/components/CategorySelect';
import { View, Text, Tooltip, Button } from 'loot-design/src/components/common';
import DateSelect from 'loot-design/src/components/DateSelect';
import PayeeAutocomplete from 'loot-design/src/components/PayeeAutocomplete';
import {
Cell,
Field,
Row,
InputCell,
SelectCell,
DeleteCell,
CustomCell,
CellButton,
useTableNavigator,
import { useMergedRefs } from 'loot-design/src/components/useMergedRefs';
import { styles, colors } from 'loot-design/src/style';
import LeftArrow2 from 'loot-design/src/svg/v0/LeftArrow2';
import RightArrow2 from 'loot-design/src/svg/v0/RightArrow2';
import CheveronDown from 'loot-design/src/svg/v1/CheveronDown';
import ArrowsSynchronize from 'loot-design/src/svg/v2/ArrowsSynchronize';
import CalendarIcon from 'loot-design/src/svg/v2/Calendar';
import Hyperlink2 from 'loot-design/src/svg/v2/Hyperlink2';
import { getStatusProps } from '../schedules/StatusBadge';
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
function getDisplayValue(obj, name) {
return obj ? obj[name] : '';
}
function serializeTransaction(transaction, showZeroInDeposit, dateFormat) {
let { amount, date } = transaction;
if (isPreviewId(transaction.id)) {
amount = getScheduledAmount(amount);
}
let debit = amount < 0 ? -amount : null;
let credit = amount > 0 ? amount : null;
if (amount === 0) {
if (showZeroInDeposit) {
credit = 0;
} else {
debit = 0;
}
}
// 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) : '',
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
};
}
function deserializeTransaction(transaction, originalTransaction, dateFormat) {
let { debit, credit, date, ...realTransaction } = transaction;
let amount;
if (debit !== '') {
let parsed = evalArithmetic(debit, null);
amount = parsed != null ? -parsed : null;
} else {
amount = evalArithmetic(credit, null);
}
amount =
amount != null ? amountToInteger(amount) : originalTransaction.amount;
if (date == null) {
date = originalTransaction.date || currentDay();
}
return { ...realTransaction, date, amount };
}
function getParentTransaction(transactions, fromIndex) {
let trans = transactions[fromIndex];
let parentIdx = fromIndex;
while (parentIdx >= 0) {
if (transactions[parentIdx].id === trans.parent_id) {
// Found the parent
return transactions[parentIdx];
}
parentIdx--;
}
return null;
}
function isLastChild(transactions, index) {
let trans = transactions[index];
return (
trans &&
trans.is_child &&
(transactions[index + 1] == null ||
transactions[index + 1].parent_id !== trans.parent_id)
);
}
let SplitsExpandedContext = React.createContext(null);
export function useSplitsExpanded() {
let data = useContext(SplitsExpandedContext);
return useMemo(
() => ({
...data,
expanded: id =>
data.state.mode === 'collapse'
? !data.state.ids.has(id)
: data.state.ids.has(id),
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
);
}
export function SplitsExpandedProvider({ children, initialMode = 'expand' }) {
let cachedState = useSelector(state => state.app.lastSplitState);
let reduxDispatch = useDispatch();
let [state, dispatch] = useReducer((state, action) => {
switch (action.type) {
case 'toggle-split': {
let ids = new Set([...state.ids]);
let { id } = action;
if (ids.has(id)) {
ids.delete(id);
} else {
ids.add(id);
}
return { ...state, ids };
}
case 'open-split': {
let ids = new Set([...state.ids]);
let { id } = action;
if (state.mode === 'collapse') {
ids.delete(id);
} else {
ids.add(id);
}
return { ...state, ids };
}
case 'set-mode': {
return {
...state,
mode: action.mode,
ids: new Set(),
transitionId: null,
};
}
case 'switch-mode':
if (state.transitionId != null) {
// You can only transition once at a time
return state;
}
return {
...state,
mode: state.mode === 'expand' ? 'collapse' : 'expand',
transitionId: action.id,
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
};
case 'finish-switch-mode':
return { ...state, transitionId: null };
default:
throw new Error('Unknown action type: ' + action.type);
}
}, cachedState.current || { ids: new Set(), mode: initialMode });
useEffect(() => {
if (state.transitionId != null) {
// This timeout allows animations to finish
setTimeout(() => {
dispatch({ type: 'finish-switch-mode' });
}, 250);
}
}, [state.transitionId]);
useEffect(() => {
// In a finished state, cache the state
if (state.transitionId == null) {
reduxDispatch({ type: 'SET_LAST_SPLIT_STATE', splitState: state });
}
}, [state]);
let value = useMemo(() => ({ state, dispatch }), [state, dispatch]);
return (
<SplitsExpandedContext.Provider value={value}>
{children}
</SplitsExpandedContext.Provider>
);
}
export const TransactionHeader = React.memo(
({ hasSelected, showAccount, showCategory, showBalance, showCleared }) => {
let dispatchSelected = useSelectedDispatch();
return (
<Row
borderColor={colors.n9}
backgroundColor="white"
style={{
color: colors.n4,
fontWeight: 300,
}}
>
<SelectCell
exposed={true}
focused={false}
selected={hasSelected}
width={20}
onSelect={() => dispatchSelected({ type: 'select-all' })}
/>
<Cell value="Date" width={110} />
{showAccount && <Cell value="Account" width="flex" />}
<Cell value="Payee" width="flex" />
<Cell value="Notes" width="flex" />
{showCategory && <Cell value="Category" width="flex" />}
<Cell value="Payment" width={80} textAlign="right" />
<Cell value="Deposit" width={80} textAlign="right" />
{showBalance && <Cell value="Balance" width={85} textAlign="right" />}
{showCleared && <Field width={21} truncate={false} />}
<Cell value="" width={15 + styles.scrollbarWidth} />
</Row>
);
);
function getPayeePretty(transaction, payee, transferAcct) {
let { payee: payeeId } = transaction;
if (transferAcct) {
const Icon = transaction.amount > 0 ? LeftArrow2 : RightArrow2;
return (
<View
style={{
flexDirection: 'row',
alignItems: 'center',
}}
>
<Icon width={10} height={8} style={{ marginRight: 5, flexShrink: 0 }} />
<div
style={{
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{transferAcct.name}
</div>
</View>
);
} else if (payee && !payee.transfer_acct) {
// Check to make sure this isn't a transfer because in the rare
// occasion that the account has been deleted but the payee is
// still there, we don't want to show the name.
return payee.name;
} else if (payeeId && payeeId.startsWith('new:')) {
return payeeId.slice('new:'.length);
}
return '';
}
function StatusCell({
id,
focused,
selected,
status,
isChild,
onEdit,
}) {
let isClearedField = status === 'cleared' || status == null;
let statusProps = getStatusProps(status);
let props = {
color:
status === 'cleared'
? colors.g5
: status === 'missed'
? colors.r6
: status === 'due'
? colors.y5
: selected
? colors.b7
};
function onSelect() {
if (isClearedField) {
onUpdate('cleared', !(status === 'cleared'));
}
}
return (
<Cell
name="cleared"
width="auto"
focused={focused}
style={{ padding: 1 }}
plain
>
<CellButton
style={[
{
padding: 3,
border: '1px solid transparent',
borderRadius: 50,
':focus': {
border: '1px solid ' + props.color,
boxShadow: `0 1px 2px ${props.color}`,
cursor: isClearedField ? 'pointer' : 'default',
isChild && { visibility: 'hidden' },
]}
onEdit={() => onEdit(id, 'cleared')}
onSelect={onSelect}
>
{React.createElement(statusProps.Icon, {
style: {
width: 13,
height: 13,
color: props.color,
marginTop: status === 'due' ? -1 : 0,
},
})}
</CellButton>
</Cell>
);
}
function PayeeCell({
id,
payeeId,
focused,
inherited,
payees,
accounts,
valueStyle,
transaction,
payee,
transferAcct,
importedPayee,
isPreview,
onEdit,
onUpdate,
onCreatePayee,
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
}) {
let isCreatingPayee = useRef(false);
return (
<CustomCell
width="flex"
name="payee"
value={payeeId}
valueStyle={[valueStyle, inherited && { color: colors.n8 }]}
formatter={value => getPayeePretty(transaction, payee, transferAcct)}
exposed={focused}
onExpose={!isPreview && (name => onEdit(id, name))}
onUpdate={async value => {
onUpdate('payee', value);
if (value && value.startsWith('new:') && !isCreatingPayee.current) {
isCreatingPayee.current = true;
let id = await onCreatePayee(value.slice('new:'.length));
onUpdate('payee', id);
isCreatingPayee.current = false;
}
}}
>
{({
onBlur,
onKeyDown,
onUpdate,
onSave,
shouldSaveFromKey,
}) => {
return (
<>
<PayeeAutocomplete
payees={payees}
accounts={accounts}
value={payeeId}
shouldSaveFromKey={shouldSaveFromKey}
inputProps={{
onBlur,
onKeyDown,
style: inputStyle,
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
}}
showManagePayees={true}
tableBehavior={true}
defaultFocusTransferPayees={transaction.is_child}
focused={true}
onUpdate={onUpdate}
onSelect={onSave}
onManagePayees={() => onManagePayees(payeeId)}
/>
</>
);
}}
</CustomCell>
);
}
function CellWithScheduleIcon({ scheduleId, children }) {
let scheduleData = useCachedSchedules();
let schedule = scheduleData.schedules.find(s => s.id === scheduleId);
if (schedule == null) {
// This must be a deleted schedule
return children;
}
let recurring = schedule._date && !!schedule._date.frequency;
let style = {
width: 13,
height: 13,
marginLeft: 5,
marginRight: 3,
color: 'inherit',
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
};
return (
<View style={{ flex: 1, flexDirection: 'row', alignItems: 'stretch' }}>
<Cell exposed={true}>
{() =>
recurring ? (
<ArrowsSynchronize style={style} />
) : (
<CalendarIcon style={{ ...style, transform: 'translateY(-1px)' }} />
)
}
</Cell>
{children}
</View>
);
}
export const Transaction = React.memo(function Transaction(props) {
let {
transaction: originalTransaction,
editing,
backgroundColor = 'white',
showAccount,
showBalance,
showZeroInDeposit,
style,
hovered,
selected,
highlighted,
added,
matched,
expanded,
inheritedFields,
focusedField,
categoryGroups,
payees,
accounts,
balance,
dateFormat = 'MM/dd/yyyy',
onSave,
onEdit,
onHover,
onDelete,
onSplit,
onManagePayees,
onCreatePayee,
} = props;
let dispatchSelected = useSelectedDispatch();
let [prevShowZero, setPrevShowZero] = useState(showZeroInDeposit);
let [prevTransaction, setPrevTransaction] = useState(originalTransaction);
let [transaction, setTransaction] = useState(
serializeTransaction(originalTransaction, showZeroInDeposit, dateFormat),
);
let isPreview = isPreviewId(transaction.id);
if (
originalTransaction !== prevTransaction ||
showZeroInDeposit !== prevShowZero
) {
setTransaction(
serializeTransaction(originalTransaction, showZeroInDeposit, dateFormat),
);
setPrevTransaction(originalTransaction);
setPrevShowZero(showZeroInDeposit);
}
function onUpdate(name, value) {
if (transaction[name] !== value) {
let 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) {
return;
}
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
if (
name === 'account' &&
value &&
getAccountsById(accounts)[value].offbudget
) {
newTransaction.category = null;
}
// If entering an amount in either of the credit/debit fields, we
// need to clear out the other one so it's always properly
// translated into the desired amount (see
// `deserializeTransaction`)
if (name === 'credit') {
newTransaction['debit'] = '';
} else if (name === 'debit') {
newTransaction['credit'] = '';
}
// 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:')) {
setTransaction(newTransaction);
} else {
let deserialized = deserializeTransaction(
newTransaction,
originalTransaction,
);
// Run the transaction through the formatting so that we know
// it's always showing the formatted result
setTransaction(
serializeTransaction(deserialized, showZeroInDeposit, dateFormat),
);
onSave(deserialized);
}
}
}
let {
id,
debit,
credit,
payee: payeeId,
imported_payee: importedPayee,
notes,
date,
account: accountId,
category,
cleared,
is_parent: isParent,
_unmatched = false,
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
} = transaction;
// Join in some data
let payee = payees && payeeId && getPayeesById(payees)[payeeId];
let account = accounts && accountId && getAccountsById(accounts)[accountId];
let transferAcct =
payee &&
payee.transfer_acct &&
getAccountsById(accounts)[payee.transfer_acct];
let isChild = transaction.is_child;
let borderColor = selected ? colors.b8 : colors.border;
let isBudgetTransfer = transferAcct && transferAcct.offbudget === 0;
let isOffBudget = account && account.offbudget === 1;
let valueStyle = added ? { fontWeight: 600 } : null;
let backgroundFocus = hovered || focusedField === 'select';
return (
<Row
borderColor={borderColor}
backgroundColor={
selected
? colors.selected
: backgroundFocus
? colors.hover
: isPreview
? '#fcfcfc'
: backgroundColor
}
highlighted={highlighted}
style={[
style,
isPreview && { color: colors.n5, fontStyle: 'italic' },
_unmatched && { opacity: 0.5 },
]}
onMouseEnter={() => onHover && onHover(transaction.id)}
>
{isChild && (
<Field
borderColor="transparent"
width={110}
style={{
width: 110,
backgroundColor: colors.n11,
borderBottomWidth: 0,
}}
/>
)}
{isChild && showAccount && (
<Field
borderColor="transparent"
style={{
flex: 1,
backgroundColor: colors.n11,
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
}}
/>
)}
{isTemporaryId(transaction.id) ? (
isChild ? (
<DeleteCell
onDelete={() => onDelete && onDelete(transaction.id)}
exposed={hovered || editing}
style={[isChild && { borderLeftWidth: 1 }, { lineHeight: 0 }]}
/>
) : (
<Cell width={20} />
)
) : (
<SelectCell
exposed={hovered || selected || editing}
focused={focusedField === 'select'}
onSelect={() => {
dispatchSelected({ type: 'select', id: transaction.id });
}}
onEdit={() => onEdit(id, 'select')}
selected={selected}
style={[isChild && { borderLeftWidth: 1 }]}
value={
matched && (
<Hyperlink2 style={{ width: 13, height: 13, color: colors.n7 }} />
)
}
/>
)}
{!isChild && (
<CustomCell
name="date"
width={110}
exposed={focusedField === 'date'}
value={date}
valueStyle={valueStyle}
formatter={date =>
date ? formatDate(parseISO(date), dateFormat) : ''
}
onExpose={!isPreview && (name => onEdit(id, name))}
onUpdate={value => {
onUpdate('date', value);
}}
>
{({
onBlur,
onKeyDown,
onUpdate,
onSave,
shouldSaveFromKey,
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
}) => (
<DateSelect
value={date || ''}
dateFormat={dateFormat}
inputProps={{ onBlur, onKeyDown, style: inputStyle }}
shouldSaveFromKey={shouldSaveFromKey}
tableBehavior={true}
onUpdate={onUpdate}
onSelect={onSave}
/>
)}
</CustomCell>
)}
{!isChild && showAccount && (
<CustomCell
name="account"
width="flex"
value={accountId}
formatter={acctId => {
let acct = acctId && getAccountsById(accounts)[acctId];
if (acct) {
return acct.name;
}
return '';
}}
valueStyle={valueStyle}
exposed={focusedField === 'account'}
onExpose={!isPreview && (name => onEdit(id, name))}
onUpdate={async value => {
// Only ever allow non-null values
if (value) {
onUpdate('account', value);
}
}}
>
{({
onBlur,
onKeyDown,
onUpdate,
onSave,
shouldSaveFromKey,
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
}) => (
<AccountAutocomplete
value={accountId}
accounts={accounts}
shouldSaveFromKey={shouldSaveFromKey}
tableBehavior={true}
focused={true}
inputProps={{ onBlur, onKeyDown, style: inputStyle }}
onUpdate={onUpdate}
onSelect={onSave}
/>
)}
</CustomCell>
)}
{(() => {
let cell = (
<PayeeCell
id={id}
payeeId={payeeId}
focused={focusedField === 'payee'}
inherited={inheritedFields && inheritedFields.has('payee')}
payees={payees}
accounts={accounts}
valueStyle={valueStyle}
transaction={transaction}
payee={payee}
transferAcct={transferAcct}
importedPayee={importedPayee}
isPreview={isPreview}
onEdit={onEdit}
onUpdate={onUpdate}
onCreatePayee={onCreatePayee}
onManagePayees={onManagePayees}
/>
);
if (transaction.schedule) {
return (
<CellWithScheduleIcon scheduleId={transaction.schedule}>
{cell}
</CellWithScheduleIcon>
);
}
return cell;
})()}
{isPreview ? (
<Cell name="notes" width="flex" />
) : (
<InputCell
width="flex"
name="notes"
exposed={focusedField === 'notes'}
focused={focusedField === 'notes'}
value={notes || ''}
valueStyle={valueStyle}
onExpose={!isPreview && (name => onEdit(id, name))}
inputProps={{
value: notes || '',
onUpdate: onUpdate.bind(null, 'notes'),
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
}}
/>
)}
{isPreview ? (
<Cell width="flex" style={{ alignItems: 'flex-start' }} exposed={true}>
{() => (
<View
style={{
color:
notes === 'missed'
? colors.r6
: notes === 'due'
? colors.y4
: selected
? colors.b5
: colors.n6,
backgroundColor:
notes === 'missed'
? colors.r10
: notes === 'due'
? colors.y9
: selected
? colors.b8
: colors.n10,
margin: '0 5px',
padding: '3px 7px',
}}
>
{titleFirst(notes)}
</View>
)}
</Cell>
) : isParent ? (
<Cell
name="category"
width="flex"
focused={focusedField === 'category'}
style={{ padding: 0 }}
plain
>
<CellButton
style={{
alignSelf: 'flex-start',
color: colors.n6,
borderRadius: 4,
transition: 'none',
'&:hover': {
backgroundColor: 'rgba(100, 100, 100, .15)',
color: colors.n5,
},
}}
disabled={isTemporaryId(transaction.id)}
onEdit={() => onEdit(id, 'category')}
onSelect={() => onToggleSplit(id)}
>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
alignSelf: 'stretch',
borderRadius: 4,
flex: 1,
}}
>
{isParent && (
<CheveronDown
style={{
width: 14,
height: 14,
color: 'currentColor',
transition: 'transform .08s',
transform: expanded ? 'rotateZ(0)' : 'rotateZ(-90deg)',
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
}}
/>
)}
<Text style={{ fontStyle: 'italic', userSelect: 'none' }}>
Split
</Text>
</View>
</CellButton>
</Cell>
) : isBudgetTransfer || isOffBudget || isPreview ? (
<InputCell
name="category"
width="flex"
exposed={focusedField === 'category'}
focused={focusedField === 'category'}
onExpose={!isPreview && (name => onEdit(id, name))}
value={
isParent
? 'Split'
: isOffBudget
? 'Off Budget'
: isBudgetTransfer
? 'Transfer'
: ''
}
valueStyle={valueStyle}
style={{ fontStyle: 'italic', color: '#c0c0c0', fontWeight: 300 }}
inputProps={{
readOnly: true,
style: { fontStyle: 'italic' },
}}
/>
) : (
<CustomCell
name="category"
width="flex"
value={category}
formatter={value =>
value
? getDisplayValue(
getCategoriesById(categoryGroups)[value],
)
: transaction.id
? 'Categorize'
: ''
}
exposed={focusedField === 'category'}
onExpose={name => onEdit(id, name)}
valueStyle={
!category
? {
fontStyle: 'italic',
fontWeight: 300,
color: colors.p8,
}
: valueStyle
}
onUpdate={async value => {
if (value === 'split') {
onSplit(transaction.id);
} else {
onUpdate('category', value);
}
}}
>
{({
onBlur,
onKeyDown,
onUpdate,
onSave,
shouldSaveFromKey,
}) => (
<CategoryAutocomplete
categoryGroups={categoryGroups}
value={category}
focused={true}
tableBehavior={true}
showSplitOption={!isChild && !isParent}
shouldSaveFromKey={shouldSaveFromKey}
inputProps={{ onBlur, onKeyDown, style: inputStyle }}
onUpdate={onUpdate}
onSelect={onSave}
/>
)}
</CustomCell>
)}
<InputCell
type="input"
width={80}
name="debit"
exposed={focusedField === 'debit'}
focused={focusedField === 'debit'}
value={debit == null ? '' : debit}
valueStyle={valueStyle}