A local-first personal finance app
:recycle: split ImportTransactionsModal into smaller component files (#3552)
Matiss Janis Aboltins365da79783b5
diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/CheckboxOption.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/CheckboxOption.jsxnew file mode 100644index 0000000000..76e1e7fb91--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/CheckboxOption.jsx@@ -0,0 +1,43 @@+import React from 'react';++import { theme } from '../../../style';+import { View } from '../../common/View';+import { Checkbox } from '../../forms';++export function CheckboxOption({+ id,+ checked,+ disabled,+ onChange,+ children,+ style,+}) {+ return (+ <View+ style={{+ flex: 1,+ flexDirection: 'row',+ alignItems: 'center',+ userSelect: 'none',+ minHeight: 28,+ ...style,+ }}+ >+ <Checkbox+ id={id}+ checked={checked}+ disabled={disabled}+ onChange={onChange}+ />+ <label+ htmlFor={id}+ style={{+ userSelect: 'none',+ color: disabled ? theme.pageTextSubdued : null,+ }}+ >+ {children}+ </label>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/DateFormatSelect.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/DateFormatSelect.jsxnew file mode 100644index 0000000000..c911ea36c6--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/DateFormatSelect.jsx@@ -0,0 +1,39 @@+import React from 'react';++import { Select } from '../../common/Select';+import { View } from '../../common/View';+import { SectionLabel } from '../../forms';++import { dateFormats } from './utils';++export function DateFormatSelect({+ transactions,+ fieldMappings,+ parseDateFormat,+ onChange,+}) {+ // We don't actually care about the delimiter, but we try to render+ // it based on the data we have so far. Look in a transaction and+ // try to figure out what delimiter the date is using, and default+ // to space if we can't figure it out.+ let delimiter = '-';+ if (transactions.length > 0 && fieldMappings && fieldMappings.date != null) {+ const date = transactions[0][fieldMappings.date];+ const m = date && date.match(/[/.,-/\\]/);+ delimiter = m ? m[0] : ' ';+ }++ return (+ <View style={{ width: 120 }}>+ <SectionLabel title="Date format" />+ <Select+ options={dateFormats.map(f => [+ f.format,+ f.label.replace(/ /g, delimiter),+ ])}+ value={parseDateFormat || ''}+ onChange={onChange}+ />+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsxnew file mode 100644index 0000000000..b4de3f3261--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx@@ -0,0 +1,132 @@+import React from 'react';++import { Stack } from '../../common/Stack';+import { View } from '../../common/View';+import { SectionLabel } from '../../forms';++import { SelectField } from './SelectField';+import { SubLabel } from './SubLabel';++export function FieldMappings({+ transactions,+ mappings,+ onChange,+ splitMode,+ inOutMode,+ hasHeaderRow,+}) {+ if (transactions.length === 0) {+ return null;+ }++ const { existing, ignored, selected, selected_merge, trx_id, ...trans } =+ transactions[0];+ const options = Object.keys(trans);+ mappings = mappings || {};++ return (+ <View>+ <SectionLabel title="CSV FIELDS" />+ <Stack+ direction="row"+ align="flex-start"+ spacing={1}+ style={{ marginTop: 5 }}+ >+ <View style={{ flex: 1 }}>+ <SubLabel title="Date" />+ <SelectField+ options={options}+ value={mappings.date}+ style={{ marginRight: 5 }}+ onChange={name => onChange('date', name)}+ hasHeaderRow={hasHeaderRow}+ firstTransaction={transactions[0]}+ />+ </View>+ <View style={{ flex: 1 }}>+ <SubLabel title="Payee" />+ <SelectField+ options={options}+ value={mappings.payee}+ style={{ marginRight: 5 }}+ onChange={name => onChange('payee', name)}+ hasHeaderRow={hasHeaderRow}+ firstTransaction={transactions[0]}+ />+ </View>+ <View style={{ flex: 1 }}>+ <SubLabel title="Notes" />+ <SelectField+ options={options}+ value={mappings.notes}+ style={{ marginRight: 5 }}+ onChange={name => onChange('notes', name)}+ hasHeaderRow={hasHeaderRow}+ firstTransaction={transactions[0]}+ />+ </View>+ <View style={{ flex: 1 }}>+ <SubLabel title="Category" />+ <SelectField+ options={options}+ value={mappings.category}+ style={{ marginRight: 5 }}+ onChange={name => onChange('category', name)}+ hasHeaderRow={hasHeaderRow}+ firstTransaction={transactions[0]}+ />+ </View>+ {splitMode ? (+ <>+ <View style={{ flex: 0.5 }}>+ <SubLabel title="Outflow" />+ <SelectField+ options={options}+ value={mappings.outflow}+ onChange={name => onChange('outflow', name)}+ hasHeaderRow={hasHeaderRow}+ firstTransaction={transactions[0]}+ />+ </View>+ <View style={{ flex: 0.5 }}>+ <SubLabel title="Inflow" />+ <SelectField+ options={options}+ value={mappings.inflow}+ onChange={name => onChange('inflow', name)}+ hasHeaderRow={hasHeaderRow}+ firstTransaction={transactions[0]}+ />+ </View>+ </>+ ) : (+ <>+ {inOutMode && (+ <View style={{ flex: 1 }}>+ <SubLabel title="In/Out" />+ <SelectField+ options={options}+ value={mappings.inOut}+ onChange={name => onChange('inOut', name)}+ hasHeaderRow={hasHeaderRow}+ firstTransaction={transactions[0]}+ />+ </View>+ )}+ <View style={{ flex: 1 }}>+ <SubLabel title="Amount" />+ <SelectField+ options={options}+ value={mappings.amount}+ onChange={name => onChange('amount', name)}+ hasHeaderRow={hasHeaderRow}+ firstTransaction={transactions[0]}+ />+ </View>+ </>+ )}+ </Stack>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsxsimilarity index 59%rename from packages/desktop-client/src/components/modals/ImportTransactionsModal.jsxrename to packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsxindex 4a74a10b70..903957ed4e 100644--- a/packages/desktop-client/src/components/modals/ImportTransactionsModal.jsx+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx@@ -1,132 +1,35 @@-import React, { useState, useEffect, useMemo, useCallback } from 'react';+import React, { useState, useEffect, useCallback } from 'react';-import * as d from 'date-fns';import deepEqual from 'deep-equal';-import { format as formatDate_ } from 'loot-core/src/shared/months';+import { amountToInteger } from 'loot-core/src/shared/util';++import { useActions } from '../../../hooks/useActions';+import { useDateFormat } from '../../../hooks/useDateFormat';+import { useSyncedPrefs } from '../../../hooks/useSyncedPrefs';+import { theme } from '../../../style';+import { Button, ButtonWithLoading } from '../../common/Button2';+import { Input } from '../../common/Input';+import { Modal, ModalCloseButton, ModalHeader } from '../../common/Modal';+import { Select } from '../../common/Select';+import { Stack } from '../../common/Stack';+import { Text } from '../../common/Text';+import { View } from '../../common/View';+import { SectionLabel } from '../../forms';+import { TableHeader, TableWithNavigator } from '../../table';++import { CheckboxOption } from './CheckboxOption';+import { DateFormatSelect } from './DateFormatSelect';+import { FieldMappings } from './FieldMappings';+import { InOutOption } from './InOutOption';+import { MultiplierOption } from './MultiplierOption';+import { Transaction } from './Transaction';import {- amountToCurrency,- amountToInteger,- looselyParseAmount,-} from 'loot-core/src/shared/util';--import { useActions } from '../../hooks/useActions';-import { useDateFormat } from '../../hooks/useDateFormat';-import { useSyncedPrefs } from '../../hooks/useSyncedPrefs';-import { SvgDownAndRightArrow } from '../../icons/v2';-import { theme, styles } from '../../style';-import { Button, ButtonWithLoading } from '../common/Button2';-import { Input } from '../common/Input';-import { Modal, ModalCloseButton, ModalHeader } from '../common/Modal';-import { Select } from '../common/Select';-import { Stack } from '../common/Stack';-import { Text } from '../common/Text';-import { Tooltip } from '../common/Tooltip';-import { View } from '../common/View';-import { Checkbox, SectionLabel } from '../forms';-import { TableHeader, TableWithNavigator, Row, Field } from '../table';--const dateFormats = [- { format: 'yyyy mm dd', label: 'YYYY MM DD' },- { format: 'yy mm dd', label: 'YY MM DD' },- { format: 'mm dd yyyy', label: 'MM DD YYYY' },- { format: 'mm dd yy', label: 'MM DD YY' },- { format: 'dd mm yyyy', label: 'DD MM YYYY' },- { format: 'dd mm yy', label: 'DD MM YY' },-];--export function parseDate(str, order) {- if (typeof str !== 'string') {- return null;- }-- function pad(v) {- return v && v.length === 1 ? '0' + v : v;- }-- const dateGroups = (a, b) => str => {- const parts = str- .replace(/\bjan(\.|uary)?\b/i, '01')- .replace(/\bfeb(\.|ruary)?\b/i, '02')- .replace(/\bmar(\.|ch)?\b/i, '03')- .replace(/\bapr(\.|il)?\b/i, '04')- .replace(/\bmay\.?\b/i, '05')- .replace(/\bjun(\.|e)?\b/i, '06')- .replace(/\bjul(\.|y)?\b/i, '07')- .replace(/\baug(\.|ust)?\b/i, '08')- .replace(/\bsep(\.|tember)?\b/i, '09')- .replace(/\boct(\.|ober)?\b/i, '10')- .replace(/\bnov(\.|ember)?\b/i, '11')- .replace(/\bdec(\.|ember)?\b/i, '12')- .replace(/^[^\d]+/, '')- .replace(/[^\d]+$/, '')- .split(/[^\d]+/);- if (parts.length >= 3) {- return parts.slice(0, 3);- }-- const digits = str.replace(/[^\d]/g, '');- return [digits.slice(0, a), digits.slice(a, a + b), digits.slice(a + b)];- };- const yearFirst = dateGroups(4, 2);- const twoDig = dateGroups(2, 2);-- let parts, year, month, day;- switch (order) {- case 'dd mm yyyy':- parts = twoDig(str);- year = parts[2];- month = parts[1];- day = parts[0];- break;- case 'dd mm yy':- parts = twoDig(str);- year = `20${parts[2]}`;- month = parts[1];- day = parts[0];- break;- case 'yyyy mm dd':- parts = yearFirst(str);- year = parts[0];- month = parts[1];- day = parts[2];- break;- case 'yy mm dd':- parts = twoDig(str);- year = `20${parts[0]}`;- month = parts[1];- day = parts[2];- break;- case 'mm dd yy':- parts = twoDig(str);- year = `20${parts[2]}`;- month = parts[0];- day = parts[1];- break;- default:- case 'mm dd yyyy':- parts = twoDig(str);- year = parts[2];- month = parts[0];- day = parts[1];- }-- const parsed = `${year}-${pad(month)}-${pad(day)}`;- if (!d.isValid(d.parseISO(parsed))) {- return null;- }- return parsed;-}--function formatDate(date, format) {- if (!date) {- return null;- }- try {- return formatDate_(date, format);- } catch (e) {}- return null;-}+ applyFieldMappings,+ dateFormats,+ parseAmountFields,+ parseDate,+} from './utils';function getFileType(filepath) {const m = filepath.match(/\.([^.]*)$/);@@ -136,30 +39,6 @@ function getFileType(filepath) {return rawType;}-function ParsedDate({ parseDateFormat, dateFormat, date }) {- const parsed =- date &&- formatDate(- parseDateFormat ? parseDate(date, parseDateFormat) : date,- dateFormat,- );- return (- <Text>- <Text>- {date || (- <Text style={{ color: theme.pageTextLight, fontStyle: 'italic' }}>- Empty- </Text>- )}{' '}- →{' '}- </Text>- <Text style={{ color: parsed ? theme.noticeTextLight : theme.errorText }}>- {parsed || 'Invalid'}- </Text>- </Text>- );-}-function getInitialDateFormat(transactions, mappings) {if (transactions.length === 0 || mappings.date == null) {return 'yyyy mm dd';@@ -240,87 +119,6 @@ function getInitialMappings(transactions) {};}-function applyFieldMappings(transaction, mappings) {- const result = {};- for (const [originalField, target] of Object.entries(mappings)) {- let field = originalField;- if (field === 'payee') {- field = 'payee_name';- }-- result[field] = transaction[target || field];- }- // Keep preview fields on the mapped transactions- result.trx_id = transaction.trx_id;- result.existing = transaction.existing;- result.ignored = transaction.ignored;- result.selected = transaction.selected;- result.selected_merge = transaction.selected_merge;- return result;-}--function parseAmount(amount, mapper, multiplier) {- if (amount == null) {- return null;- }-- const parsed =- typeof amount === 'string' ? looselyParseAmount(amount) : amount;-- if (parsed === null) {- return null;- }-- return mapper(parsed) * multiplier;-}--function parseAmountFields(- trans,- splitMode,- inOutMode,- outValue,- flipAmount,- multiplierAmount,-) {- const multiplier = parseFloat(multiplierAmount) || 1.0;-- if (splitMode) {- // Split mode is a little weird; first we look for an outflow and- // if that has a value, we never want to show a number in the- // inflow. Same for `amount`; we choose outflow first and then inflow- const outflow = parseAmount(trans.outflow, n => -Math.abs(n), multiplier);- const inflow = outflow- ? 0- : parseAmount(trans.inflow, n => Math.abs(n), multiplier);-- return {- amount: outflow || inflow,- outflow,- inflow,- };- }- if (inOutMode) {- return {- amount: parseAmount(- trans.amount,- n => (trans.inOut === outValue ? Math.abs(n) * -1 : Math.abs(n)),- multiplier,- ),- outflow: null,- inflow: null,- };- }- return {- amount: parseAmount(- trans.amount,- n => (flipAmount ? n * -1 : n),- multiplier,- ),- outflow: null,- inflow: null,- };-}-function parseCategoryFields(trans, categories) {let match = null;categories.forEach(category => {@@ -334,511 +132,6 @@ function parseCategoryFields(trans, categories) {return match;}-function Transaction({- transaction: rawTransaction,- fieldMappings,- showParsed,- parseDateFormat,- dateFormat,- splitMode,- inOutMode,- outValue,- flipAmount,- multiplierAmount,- categories,- onCheckTransaction,- reconcile,-}) {- const categoryList = categories.map(category => category.name);- const transaction = useMemo(- () =>- fieldMappings && !rawTransaction.isMatchedTransaction- ? applyFieldMappings(rawTransaction, fieldMappings)- : rawTransaction,- [rawTransaction, fieldMappings],- );-- let amount, outflow, inflow;- if (rawTransaction.isMatchedTransaction) {- amount = rawTransaction.amount;- if (splitMode) {- outflow = amount < 0 ? -amount : 0;- inflow = amount > 0 ? amount : 0;- }- } else {- ({ amount, outflow, inflow } = parseAmountFields(- transaction,- splitMode,- inOutMode,- outValue,- flipAmount,- multiplierAmount,- ));- }-- return (- <Row- style={{- backgroundColor: theme.tableBackground,- color:- (transaction.isMatchedTransaction && !transaction.selected_merge) ||- !transaction.selected- ? theme.tableTextInactive- : theme.tableText,- }}- >- {reconcile && (- <Field width={31}>- {!transaction.isMatchedTransaction && (- <Tooltip- content={- !transaction.existing && !transaction.ignored- ? 'New transaction. You can import it, or skip it.'- : transaction.ignored- ? 'Already imported transaction. You can skip it, or import it again.'- : transaction.existing- ? 'Updated transaction. You can update it, import it again, or skip it.'- : ''- }- placement="right top"- >- <Checkbox- checked={transaction.selected}- onChange={() => onCheckTransaction(transaction.trx_id)}- style={- transaction.selected_merge- ? {- ':checked': {- '::after': {- background:- theme.checkboxBackgroundSelected +- // update sign from packages/desktop-client/src/icons/v1/layer.svg- // eslint-disable-next-line rulesdir/typography- ' url(\'data:image/svg+xml; utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path fill="white" d="M10 1l10 6-10 6L0 7l10-6zm6.67 10L20 13l-10 6-10-6 3.33-2L10 15l6.67-4z" /></svg>\') 9px 9px',- },- },- }- : {- '&': {- border:- '1px solid ' + theme.buttonNormalDisabledBorder,- backgroundColor: theme.buttonNormalDisabledBorder,- '::after': {- display: 'block',- background:- theme.buttonNormalDisabledBorder +- // minus sign adapted from packages/desktop-client/src/icons/v1/add.svg- // eslint-disable-next-line rulesdir/typography- ' url(\'data:image/svg+xml; utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="white" className="path" d="M23,11.5 L23,11.5 L23,11.5 C23,12.3284271 22.3284271,13 21.5,13 L1.5,13 L1.5,13 C0.671572875,13 1.01453063e-16,12.3284271 0,11.5 L0,11.5 L0,11.5 C-1.01453063e-16,10.6715729 0.671572875,10 1.5,10 L21.5,10 L21.5,10 C22.3284271,10 23,10.6715729 23,11.5 Z" /></svg>\') 9px 9px',- width: 9,- height: 9,- content: ' ',- },- },- ':checked': {- border: '1px solid ' + theme.checkboxBorderSelected,- backgroundColor: theme.checkboxBackgroundSelected,- '::after': {- background:- theme.checkboxBackgroundSelected +- // plus sign from packages/desktop-client/src/icons/v1/add.svg- // eslint-disable-next-line rulesdir/typography- ' url(\'data:image/svg+xml; utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="white" className="path" d="M23,11.5 L23,11.5 L23,11.5 C23,12.3284271 22.3284271,13 21.5,13 L1.5,13 L1.5,13 C0.671572875,13 1.01453063e-16,12.3284271 0,11.5 L0,11.5 L0,11.5 C-1.01453063e-16,10.6715729 0.671572875,10 1.5,10 L21.5,10 L21.5,10 C22.3284271,10 23,10.6715729 23,11.5 Z" /><path fill="white" className="path" d="M11.5,23 C10.6715729,23 10,22.3284271 10,21.5 L10,1.5 C10,0.671572875 10.6715729,1.52179594e-16 11.5,0 C12.3284271,-1.52179594e-16 13,0.671572875 13,1.5 L13,21.5 C13,22.3284271 12.3284271,23 11.5,23 Z" /></svg>\') 9px 9px',- },- },- }- }- />- </Tooltip>- )}- </Field>- )}- <Field width={200}>- {transaction.isMatchedTransaction ? (- <View>- <Stack direction="row" align="flex-start">- <View>- <SvgDownAndRightArrow width={16} height={16} />- </View>- <View>{formatDate(transaction.date, dateFormat)}</View>- </Stack>- </View>- ) : showParsed ? (- <ParsedDate- parseDateFormat={parseDateFormat}- dateFormat={dateFormat}- date={transaction.date}- />- ) : (- formatDate(transaction.date, dateFormat)- )}- </Field>- <Field- width="flex"- title={transaction.imported_payee || transaction.payee_name}- >- {transaction.payee_name}- </Field>- <Field width="flex" title={transaction.notes}>- {transaction.notes}- </Field>- <Field- width="flex"- title={- categoryList.includes(transaction.category)- ? transaction.category- : undefined- }- >- {categoryList.includes(transaction.category) && transaction.category}- </Field>- {splitMode ? (- <>- <Field- width={90}- contentStyle={{- textAlign: 'right',- ...styles.tnum,- ...(inflow === null && outflow === null- ? { color: theme.errorText }- : {}),- }}- title={- inflow === null && outflow === null- ? 'Invalid: unable to parse the value'- : amountToCurrency(outflow)- }- >- {amountToCurrency(outflow)}- </Field>- <Field- width={90}- contentStyle={{- textAlign: 'right',- ...styles.tnum,- ...(inflow === null && outflow === null- ? { color: theme.errorText }- : {}),- }}- title={- inflow === null && outflow === null- ? 'Invalid: unable to parse the value'- : amountToCurrency(inflow)- }- >- {amountToCurrency(inflow)}- </Field>- </>- ) : (- <>- {inOutMode && (- <Field- width={90}- contentStyle={{ textAlign: 'left', ...styles.tnum }}- title={transaction.inOut}- >- {transaction.inOut}- </Field>- )}- <Field- width={90}- contentStyle={{- textAlign: 'right',- ...styles.tnum,- ...(amount === null ? { color: theme.errorText } : {}),- }}- title={- amount === null- ? `Invalid: unable to parse the value (${transaction.amount})`- : amountToCurrency(amount)- }- >- {amountToCurrency(amount)}- </Field>- </>- )}- </Row>- );-}--function SubLabel({ title }) {- return (- <Text style={{ fontSize: 13, marginBottom: 3, color: theme.pageText }}>- {title}- </Text>- );-}--function SelectField({- style,- options,- value,- onChange,- hasHeaderRow,- firstTransaction,-}) {- return (- <Select- options={[- ['choose-field', 'Choose field...'],- ...options.map(option => [- option,- hasHeaderRow- ? option- : `Column ${parseInt(option) + 1} (${firstTransaction[option]})`,- ]),- ]}- value={value === null ? 'choose-field' : value}- onChange={onChange}- style={style}- />- );-}--function DateFormatSelect({- transactions,- fieldMappings,- parseDateFormat,- onChange,-}) {- // We don't actually care about the delimiter, but we try to render- // it based on the data we have so far. Look in a transaction and- // try to figure out what delimiter the date is using, and default- // to space if we can't figure it out.- let delimiter = '-';- if (transactions.length > 0 && fieldMappings && fieldMappings.date != null) {- const date = transactions[0][fieldMappings.date];- const m = date && date.match(/[/.,-/\\]/);- delimiter = m ? m[0] : ' ';- }-- return (- <View style={{ width: 120 }}>- <SectionLabel title="Date format" />- <Select- options={dateFormats.map(f => [- f.format,- f.label.replace(/ /g, delimiter),- ])}- value={parseDateFormat || ''}- onChange={onChange}- />- </View>- );-}--function CheckboxOption({ id, checked, disabled, onChange, children, style }) {- return (- <View- style={{- flex: 1,- flexDirection: 'row',- alignItems: 'center',- userSelect: 'none',- minHeight: 28,- ...style,- }}- >- <Checkbox- id={id}- checked={checked}- disabled={disabled}- onChange={onChange}- />- <label- htmlFor={id}- style={{- userSelect: 'none',- color: disabled ? theme.pageTextSubdued : null,- }}- >- {children}- </label>- </View>- );-}--function MultiplierOption({- multiplierEnabled,- multiplierAmount,- onToggle,- onChangeAmount,-}) {- return (- <View style={{ flexDirection: 'row', gap: 10, height: 28 }}>- <CheckboxOption- id="add_multiplier"- checked={multiplierEnabled}- onChange={onToggle}- >- Add multiplier- </CheckboxOption>- <Input- type="text"- style={{ display: multiplierEnabled ? 'inherit' : 'none' }}- value={multiplierAmount}- placeholder="Multiplier"- onChangeValue={onChangeAmount}- />- </View>- );-}--function InOutOption({- inOutMode,- outValue,- disabled,- onToggle,- onChangeText,-}) {- return (- <View style={{ flexDirection: 'row', gap: 10, height: 28 }}>- <CheckboxOption- id="form_inOut"- checked={inOutMode}- disabled={disabled}- onChange={onToggle}- >- {inOutMode- ? 'in/out identifier'- : 'Select column to specify if amount goes in/out'}- </CheckboxOption>- {inOutMode && (- <Input- type="text"- value={outValue}- onChangeValue={onChangeText}- placeholder="Value for out rows, i.e. Credit"- />- )}- </View>- );-}--function FieldMappings({- transactions,- mappings,- onChange,- splitMode,- inOutMode,- hasHeaderRow,-}) {- if (transactions.length === 0) {- return null;- }-- const { existing, ignored, selected, selected_merge, trx_id, ...trans } =- transactions[0];- const options = Object.keys(trans);- mappings = mappings || {};-- return (- <View>- <SectionLabel title="CSV FIELDS" />- <Stack- direction="row"- align="flex-start"- spacing={1}- style={{ marginTop: 5 }}- >- <View style={{ flex: 1 }}>- <SubLabel title="Date" />- <SelectField- options={options}- value={mappings.date}- style={{ marginRight: 5 }}- onChange={name => onChange('date', name)}- hasHeaderRow={hasHeaderRow}- firstTransaction={transactions[0]}- />- </View>- <View style={{ flex: 1 }}>- <SubLabel title="Payee" />- <SelectField- options={options}- value={mappings.payee}- style={{ marginRight: 5 }}- onChange={name => onChange('payee', name)}- hasHeaderRow={hasHeaderRow}- firstTransaction={transactions[0]}- />- </View>- <View style={{ flex: 1 }}>- <SubLabel title="Notes" />- <SelectField- options={options}- value={mappings.notes}- style={{ marginRight: 5 }}- onChange={name => onChange('notes', name)}- hasHeaderRow={hasHeaderRow}- firstTransaction={transactions[0]}- />- </View>- <View style={{ flex: 1 }}>- <SubLabel title="Category" />- <SelectField- options={options}- value={mappings.category}- style={{ marginRight: 5 }}- onChange={name => onChange('category', name)}- hasHeaderRow={hasHeaderRow}- firstTransaction={transactions[0]}- />- </View>- {splitMode ? (- <>- <View style={{ flex: 0.5 }}>- <SubLabel title="Outflow" />- <SelectField- options={options}- value={mappings.outflow}- onChange={name => onChange('outflow', name)}- hasHeaderRow={hasHeaderRow}- firstTransaction={transactions[0]}- />- </View>- <View style={{ flex: 0.5 }}>- <SubLabel title="Inflow" />- <SelectField- options={options}- value={mappings.inflow}- onChange={name => onChange('inflow', name)}- hasHeaderRow={hasHeaderRow}- firstTransaction={transactions[0]}- />- </View>- </>- ) : (- <>- {inOutMode && (- <View style={{ flex: 1 }}>- <SubLabel title="In/Out" />- <SelectField- options={options}- value={mappings.inOut}- onChange={name => onChange('inOut', name)}- hasHeaderRow={hasHeaderRow}- firstTransaction={transactions[0]}- />- </View>- )}- <View style={{ flex: 1 }}>- <SubLabel title="Amount" />- <SelectField- options={options}- value={mappings.amount}- onChange={name => onChange('amount', name)}- hasHeaderRow={hasHeaderRow}- firstTransaction={transactions[0]}- />- </View>- </>- )}- </Stack>- </View>- );-}-export function ImportTransactionsModal({ options }) {const dateFormat = useDateFormat() || 'MM/dd/yyyy';const [prefs, savePrefs] = useSyncedPrefs();diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/InOutOption.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/InOutOption.jsxnew file mode 100644index 0000000000..5bd36a8f42--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/InOutOption.jsx@@ -0,0 +1,37 @@+import React from 'react';++import { Input } from '../../common/Input';+import { View } from '../../common/View';++import { CheckboxOption } from './CheckboxOption';++export function InOutOption({+ inOutMode,+ outValue,+ disabled,+ onToggle,+ onChangeText,+}) {+ return (+ <View style={{ flexDirection: 'row', gap: 10, height: 28 }}>+ <CheckboxOption+ id="form_inOut"+ checked={inOutMode}+ disabled={disabled}+ onChange={onToggle}+ >+ {inOutMode+ ? 'in/out identifier'+ : 'Select column to specify if amount goes in/out'}+ </CheckboxOption>+ {inOutMode && (+ <Input+ type="text"+ value={outValue}+ onChangeValue={onChangeText}+ placeholder="Value for out rows, i.e. Credit"+ />+ )}+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/MultiplierOption.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/MultiplierOption.jsxnew file mode 100644index 0000000000..f5d922cf51--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/MultiplierOption.jsx@@ -0,0 +1,32 @@+import React from 'react';++import { Input } from '../../common/Input';+import { View } from '../../common/View';++import { CheckboxOption } from './CheckboxOption';++export function MultiplierOption({+ multiplierEnabled,+ multiplierAmount,+ onToggle,+ onChangeAmount,+}) {+ return (+ <View style={{ flexDirection: 'row', gap: 10, height: 28 }}>+ <CheckboxOption+ id="add_multiplier"+ checked={multiplierEnabled}+ onChange={onToggle}+ >+ Add multiplier+ </CheckboxOption>+ <Input+ type="text"+ style={{ display: multiplierEnabled ? 'inherit' : 'none' }}+ value={multiplierAmount}+ placeholder="Multiplier"+ onChangeValue={onChangeAmount}+ />+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/ParsedDate.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/ParsedDate.jsxnew file mode 100644index 0000000000..9abf5e340c--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/ParsedDate.jsx@@ -0,0 +1,30 @@+import React from 'react';++import { theme } from '../../../style';+import { Text } from '../../common/Text';++import { formatDate, parseDate } from './utils';++export function ParsedDate({ parseDateFormat, dateFormat, date }) {+ const parsed =+ date &&+ formatDate(+ parseDateFormat ? parseDate(date, parseDateFormat) : date,+ dateFormat,+ );+ return (+ <Text>+ <Text>+ {date || (+ <Text style={{ color: theme.pageTextLight, fontStyle: 'italic' }}>+ Empty+ </Text>+ )}{' '}+ →{' '}+ </Text>+ <Text style={{ color: parsed ? theme.noticeTextLight : theme.errorText }}>+ {parsed || 'Invalid'}+ </Text>+ </Text>+ );+}diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/SelectField.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/SelectField.jsxnew file mode 100644index 0000000000..0626b8e639--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/SelectField.jsx@@ -0,0 +1,29 @@+import React from 'react';++import { Select } from '../../common/Select';++export function SelectField({+ style,+ options,+ value,+ onChange,+ hasHeaderRow,+ firstTransaction,+}) {+ return (+ <Select+ options={[+ ['choose-field', 'Choose field...'],+ ...options.map(option => [+ option,+ hasHeaderRow+ ? option+ : `Column ${parseInt(option) + 1} (${firstTransaction[option]})`,+ ]),+ ]}+ value={value === null ? 'choose-field' : value}+ onChange={onChange}+ style={style}+ />+ );+}diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/SubLabel.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/SubLabel.jsxnew file mode 100644index 0000000000..0d1d64de24--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/SubLabel.jsx@@ -0,0 +1,12 @@+import React from 'react';++import { theme } from '../../../style';+import { Text } from '../../common/Text';++export function SubLabel({ title }) {+ return (+ <Text style={{ fontSize: 13, marginBottom: 3, color: theme.pageText }}>+ {title}+ </Text>+ );+}diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/Transaction.jsx b/packages/desktop-client/src/components/modals/ImportTransactionsModal/Transaction.jsxnew file mode 100644index 0000000000..0a861eb02a--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/Transaction.jsx@@ -0,0 +1,241 @@+import React, { useMemo } from 'react';++import { amountToCurrency } from 'loot-core/src/shared/util';++import { SvgDownAndRightArrow } from '../../../icons/v2';+import { theme, styles } from '../../../style';+import { Stack } from '../../common/Stack';+import { Tooltip } from '../../common/Tooltip';+import { View } from '../../common/View';+import { Checkbox } from '../../forms';+import { Row, Field } from '../../table';++import { ParsedDate } from './ParsedDate';+import { applyFieldMappings, formatDate, parseAmountFields } from './utils';++export function Transaction({+ transaction: rawTransaction,+ fieldMappings,+ showParsed,+ parseDateFormat,+ dateFormat,+ splitMode,+ inOutMode,+ outValue,+ flipAmount,+ multiplierAmount,+ categories,+ onCheckTransaction,+ reconcile,+}) {+ const categoryList = categories.map(category => category.name);+ const transaction = useMemo(+ () =>+ fieldMappings && !rawTransaction.isMatchedTransaction+ ? applyFieldMappings(rawTransaction, fieldMappings)+ : rawTransaction,+ [rawTransaction, fieldMappings],+ );++ let amount, outflow, inflow;+ if (rawTransaction.isMatchedTransaction) {+ amount = rawTransaction.amount;+ if (splitMode) {+ outflow = amount < 0 ? -amount : 0;+ inflow = amount > 0 ? amount : 0;+ }+ } else {+ ({ amount, outflow, inflow } = parseAmountFields(+ transaction,+ splitMode,+ inOutMode,+ outValue,+ flipAmount,+ multiplierAmount,+ ));+ }++ return (+ <Row+ style={{+ backgroundColor: theme.tableBackground,+ color:+ (transaction.isMatchedTransaction && !transaction.selected_merge) ||+ !transaction.selected+ ? theme.tableTextInactive+ : theme.tableText,+ }}+ >+ {reconcile && (+ <Field width={31}>+ {!transaction.isMatchedTransaction && (+ <Tooltip+ content={+ !transaction.existing && !transaction.ignored+ ? 'New transaction. You can import it, or skip it.'+ : transaction.ignored+ ? 'Already imported transaction. You can skip it, or import it again.'+ : transaction.existing+ ? 'Updated transaction. You can update it, import it again, or skip it.'+ : ''+ }+ placement="right top"+ >+ <Checkbox+ checked={transaction.selected}+ onChange={() => onCheckTransaction(transaction.trx_id)}+ style={+ transaction.selected_merge+ ? {+ ':checked': {+ '::after': {+ background:+ theme.checkboxBackgroundSelected ++ // update sign from packages/desktop-client/src/icons/v1/layer.svg+ // eslint-disable-next-line rulesdir/typography+ ' url(\'data:image/svg+xml; utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path fill="white" d="M10 1l10 6-10 6L0 7l10-6zm6.67 10L20 13l-10 6-10-6 3.33-2L10 15l6.67-4z" /></svg>\') 9px 9px',+ },+ },+ }+ : {+ '&': {+ border:+ '1px solid ' + theme.buttonNormalDisabledBorder,+ backgroundColor: theme.buttonNormalDisabledBorder,+ '::after': {+ display: 'block',+ background:+ theme.buttonNormalDisabledBorder ++ // minus sign adapted from packages/desktop-client/src/icons/v1/add.svg+ // eslint-disable-next-line rulesdir/typography+ ' url(\'data:image/svg+xml; utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="white" className="path" d="M23,11.5 L23,11.5 L23,11.5 C23,12.3284271 22.3284271,13 21.5,13 L1.5,13 L1.5,13 C0.671572875,13 1.01453063e-16,12.3284271 0,11.5 L0,11.5 L0,11.5 C-1.01453063e-16,10.6715729 0.671572875,10 1.5,10 L21.5,10 L21.5,10 C22.3284271,10 23,10.6715729 23,11.5 Z" /></svg>\') 9px 9px',+ width: 9,+ height: 9,+ content: ' ',+ },+ },+ ':checked': {+ border: '1px solid ' + theme.checkboxBorderSelected,+ backgroundColor: theme.checkboxBackgroundSelected,+ '::after': {+ background:+ theme.checkboxBackgroundSelected ++ // plus sign from packages/desktop-client/src/icons/v1/add.svg+ // eslint-disable-next-line rulesdir/typography+ ' url(\'data:image/svg+xml; utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="white" className="path" d="M23,11.5 L23,11.5 L23,11.5 C23,12.3284271 22.3284271,13 21.5,13 L1.5,13 L1.5,13 C0.671572875,13 1.01453063e-16,12.3284271 0,11.5 L0,11.5 L0,11.5 C-1.01453063e-16,10.6715729 0.671572875,10 1.5,10 L21.5,10 L21.5,10 C22.3284271,10 23,10.6715729 23,11.5 Z" /><path fill="white" className="path" d="M11.5,23 C10.6715729,23 10,22.3284271 10,21.5 L10,1.5 C10,0.671572875 10.6715729,1.52179594e-16 11.5,0 C12.3284271,-1.52179594e-16 13,0.671572875 13,1.5 L13,21.5 C13,22.3284271 12.3284271,23 11.5,23 Z" /></svg>\') 9px 9px',+ },+ },+ }+ }+ />+ </Tooltip>+ )}+ </Field>+ )}+ <Field width={200}>+ {transaction.isMatchedTransaction ? (+ <View>+ <Stack direction="row" align="flex-start">+ <View>+ <SvgDownAndRightArrow width={16} height={16} />+ </View>+ <View>{formatDate(transaction.date, dateFormat)}</View>+ </Stack>+ </View>+ ) : showParsed ? (+ <ParsedDate+ parseDateFormat={parseDateFormat}+ dateFormat={dateFormat}+ date={transaction.date}+ />+ ) : (+ formatDate(transaction.date, dateFormat)+ )}+ </Field>+ <Field+ width="flex"+ title={transaction.imported_payee || transaction.payee_name}+ >+ {transaction.payee_name}+ </Field>+ <Field width="flex" title={transaction.notes}>+ {transaction.notes}+ </Field>+ <Field+ width="flex"+ title={+ categoryList.includes(transaction.category)+ ? transaction.category+ : undefined+ }+ >+ {categoryList.includes(transaction.category) && transaction.category}+ </Field>+ {splitMode ? (+ <>+ <Field+ width={90}+ contentStyle={{+ textAlign: 'right',+ ...styles.tnum,+ ...(inflow === null && outflow === null+ ? { color: theme.errorText }+ : {}),+ }}+ title={+ inflow === null && outflow === null+ ? 'Invalid: unable to parse the value'+ : amountToCurrency(outflow)+ }+ >+ {amountToCurrency(outflow)}+ </Field>+ <Field+ width={90}+ contentStyle={{+ textAlign: 'right',+ ...styles.tnum,+ ...(inflow === null && outflow === null+ ? { color: theme.errorText }+ : {}),+ }}+ title={+ inflow === null && outflow === null+ ? 'Invalid: unable to parse the value'+ : amountToCurrency(inflow)+ }+ >+ {amountToCurrency(inflow)}+ </Field>+ </>+ ) : (+ <>+ {inOutMode && (+ <Field+ width={90}+ contentStyle={{ textAlign: 'left', ...styles.tnum }}+ title={transaction.inOut}+ >+ {transaction.inOut}+ </Field>+ )}+ <Field+ width={90}+ contentStyle={{+ textAlign: 'right',+ ...styles.tnum,+ ...(amount === null ? { color: theme.errorText } : {}),+ }}+ title={+ amount === null+ ? `Invalid: unable to parse the value (${transaction.amount})`+ : amountToCurrency(amount)+ }+ >+ {amountToCurrency(amount)}+ </Field>+ </>+ )}+ </Row>+ );+}diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/index.ts b/packages/desktop-client/src/components/modals/ImportTransactionsModal/index.tsnew file mode 100644index 0000000000..5bb6235f45--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/index.ts@@ -0,0 +1 @@+export { ImportTransactionsModal } from './ImportTransactionsModal';diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js b/packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.jsnew file mode 100644index 0000000000..094f862e5b--- /dev/null+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js@@ -0,0 +1,187 @@+import * as d from 'date-fns';++import { format as formatDate_ } from 'loot-core/src/shared/months';+import { looselyParseAmount } from 'loot-core/src/shared/util';++export const dateFormats = [+ { format: 'yyyy mm dd', label: 'YYYY MM DD' },+ { format: 'yy mm dd', label: 'YY MM DD' },+ { format: 'mm dd yyyy', label: 'MM DD YYYY' },+ { format: 'mm dd yy', label: 'MM DD YY' },+ { format: 'dd mm yyyy', label: 'DD MM YYYY' },+ { format: 'dd mm yy', label: 'DD MM YY' },+];++export function parseDate(str, order) {+ if (typeof str !== 'string') {+ return null;+ }++ function pad(v) {+ return v && v.length === 1 ? '0' + v : v;+ }++ const dateGroups = (a, b) => str => {+ const parts = str+ .replace(/\bjan(\.|uary)?\b/i, '01')+ .replace(/\bfeb(\.|ruary)?\b/i, '02')+ .replace(/\bmar(\.|ch)?\b/i, '03')+ .replace(/\bapr(\.|il)?\b/i, '04')+ .replace(/\bmay\.?\b/i, '05')+ .replace(/\bjun(\.|e)?\b/i, '06')+ .replace(/\bjul(\.|y)?\b/i, '07')+ .replace(/\baug(\.|ust)?\b/i, '08')+ .replace(/\bsep(\.|tember)?\b/i, '09')+ .replace(/\boct(\.|ober)?\b/i, '10')+ .replace(/\bnov(\.|ember)?\b/i, '11')+ .replace(/\bdec(\.|ember)?\b/i, '12')+ .replace(/^[^\d]+/, '')+ .replace(/[^\d]+$/, '')+ .split(/[^\d]+/);+ if (parts.length >= 3) {+ return parts.slice(0, 3);+ }++ const digits = str.replace(/[^\d]/g, '');+ return [digits.slice(0, a), digits.slice(a, a + b), digits.slice(a + b)];+ };+ const yearFirst = dateGroups(4, 2);+ const twoDig = dateGroups(2, 2);++ let parts, year, month, day;+ switch (order) {+ case 'dd mm yyyy':+ parts = twoDig(str);+ year = parts[2];+ month = parts[1];+ day = parts[0];+ break;+ case 'dd mm yy':+ parts = twoDig(str);+ year = `20${parts[2]}`;+ month = parts[1];+ day = parts[0];+ break;+ case 'yyyy mm dd':+ parts = yearFirst(str);+ year = parts[0];+ month = parts[1];+ day = parts[2];+ break;+ case 'yy mm dd':+ parts = twoDig(str);+ year = `20${parts[0]}`;+ month = parts[1];+ day = parts[2];+ break;+ case 'mm dd yy':+ parts = twoDig(str);+ year = `20${parts[2]}`;+ month = parts[0];+ day = parts[1];+ break;+ default:+ case 'mm dd yyyy':+ parts = twoDig(str);+ year = parts[2];+ month = parts[0];+ day = parts[1];+ }++ const parsed = `${year}-${pad(month)}-${pad(day)}`;+ if (!d.isValid(d.parseISO(parsed))) {+ return null;+ }+ return parsed;+}++export function formatDate(date, format) {+ if (!date) {+ return null;+ }+ try {+ return formatDate_(date, format);+ } catch (e) {}+ return null;+}++export function applyFieldMappings(transaction, mappings) {+ const result = {};+ for (const [originalField, target] of Object.entries(mappings)) {+ let field = originalField;+ if (field === 'payee') {+ field = 'payee_name';+ }++ result[field] = transaction[target || field];+ }+ // Keep preview fields on the mapped transactions+ result.trx_id = transaction.trx_id;+ result.existing = transaction.existing;+ result.ignored = transaction.ignored;+ result.selected = transaction.selected;+ result.selected_merge = transaction.selected_merge;+ return result;+}++function parseAmount(amount, mapper, multiplier) {+ if (amount == null) {+ return null;+ }++ const parsed =+ typeof amount === 'string' ? looselyParseAmount(amount) : amount;++ if (parsed === null) {+ return null;+ }++ return mapper(parsed) * multiplier;+}++export function parseAmountFields(+ trans,+ splitMode,+ inOutMode,+ outValue,+ flipAmount,+ multiplierAmount,+) {+ const multiplier = parseFloat(multiplierAmount) || 1.0;++ if (splitMode) {+ // Split mode is a little weird; first we look for an outflow and+ // if that has a value, we never want to show a number in the+ // inflow. Same for `amount`; we choose outflow first and then inflow+ const outflow = parseAmount(trans.outflow, n => -Math.abs(n), multiplier);+ const inflow = outflow+ ? 0+ : parseAmount(trans.inflow, n => Math.abs(n), multiplier);++ return {+ amount: outflow || inflow,+ outflow,+ inflow,+ };+ }+ if (inOutMode) {+ return {+ amount: parseAmount(+ trans.amount,+ n => (trans.inOut === outValue ? Math.abs(n) * -1 : Math.abs(n)),+ multiplier,+ ),+ outflow: null,+ inflow: null,+ };+ }+ return {+ amount: parseAmount(+ trans.amount,+ n => (flipAmount ? n * -1 : n),+ multiplier,+ ),+ outflow: null,+ inflow: null,+ };+}diff --git a/packages/desktop-client/src/components/modals/ImportTransactionsModal.test.js b/packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.test.jssimilarity index 98%rename from packages/desktop-client/src/components/modals/ImportTransactionsModal.test.jsrename to packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.test.jsindex 742868e29b..f4bfa6841c 100644--- a/packages/desktop-client/src/components/modals/ImportTransactionsModal.test.js+++ b/packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.test.js@@ -1,4 +1,4 @@-import { parseDate } from './ImportTransactionsModal';+import { parseDate } from './utils';describe('Import transactions', function () {describe('date parsing', function () {diff --git a/upcoming-release-notes/3552.md b/upcoming-release-notes/3552.mdnew file mode 100644index 0000000000..f5819b02b9--- /dev/null+++ b/upcoming-release-notes/3552.md@@ -0,0 +1,6 @@+---+category: Maintenance+authors: [MatissJanis]+---++Split `ImportTransactionsModal` file in multiple smaller component files.