mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-16 04:40:32 +00:00
- feat: Filter expense and payment accounts on expense form.
- feat: Make journal errors with receivable and payable accounts. - fix: Handle database big numbers. - fix: Indexing lines when add a new line on make journal form. - fix: Abstruct accounts type component.
This commit is contained in:
@@ -10,7 +10,7 @@ import { useFormik } from 'formik';
|
||||
import moment from 'moment';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import { useIntl } from 'react-intl';
|
||||
import { pick } from 'lodash';
|
||||
import { pick, setWith } from 'lodash';
|
||||
|
||||
import MakeJournalEntriesHeader from './MakeJournalEntriesHeader';
|
||||
import MakeJournalEntriesFooter from './MakeJournalEntriesFooter';
|
||||
@@ -89,19 +89,23 @@ function MakeJournalEntriesForm({
|
||||
const validationSchema = Yup.object().shape({
|
||||
journal_number: Yup.string()
|
||||
.required()
|
||||
.min(1)
|
||||
.max(255)
|
||||
.label(formatMessage({ id: 'journal_number_' })),
|
||||
journal_type: Yup.string()
|
||||
.required()
|
||||
.min(1)
|
||||
.max(255)
|
||||
.label(formatMessage({ id: 'journal_type' })),
|
||||
date: Yup.date()
|
||||
.required()
|
||||
.label(formatMessage({ id: 'date' })),
|
||||
reference: Yup.string(),
|
||||
description: Yup.string(),
|
||||
reference: Yup.string().min(1).max(255),
|
||||
description: Yup.string().min(1).max(1024),
|
||||
entries: Yup.array().of(
|
||||
Yup.object().shape({
|
||||
credit: Yup.number().nullable(),
|
||||
debit: Yup.number().nullable(),
|
||||
credit: Yup.number().decimalScale(13).nullable(),
|
||||
debit: Yup.number().decimalScale(13).nullable(),
|
||||
account_id: Yup.number()
|
||||
.nullable()
|
||||
.when(['credit', 'debit'], {
|
||||
@@ -109,7 +113,7 @@ function MakeJournalEntriesForm({
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
contact_id: Yup.number().nullable(),
|
||||
note: Yup.string().nullable(),
|
||||
note: Yup.string().max(255).nullable(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
@@ -180,48 +184,66 @@ function MakeJournalEntriesForm({
|
||||
}, [manualJournal]);
|
||||
|
||||
// Transform API errors in toasts messages.
|
||||
const transformErrors = (errors, { setErrors }) => {
|
||||
const hasError = (errorType) => errors.some((e) => e.type === errorType);
|
||||
const transformErrors = (resErrors, { setErrors, errors }) => {
|
||||
const getError = (errorType) => resErrors.find((e) => e.type === errorType);
|
||||
const toastMessages = [];
|
||||
let error;
|
||||
let newErrors = { ...errors, entries: [] };
|
||||
|
||||
if (hasError(ERROR.CUSTOMERS_NOT_WITH_RECEVIABLE_ACC)) {
|
||||
AppToaster.show({
|
||||
message: formatMessage({
|
||||
id: 'customers_should_assign_with_receivable_account_only',
|
||||
}),
|
||||
intent: Intent.DANGER,
|
||||
const setEntriesErrors = (indexes, prop, message) =>
|
||||
indexes.forEach((i) => {
|
||||
const index = Math.max(i - 1, 0);
|
||||
newErrors = setWith(newErrors, `entries.[${index}].${prop}`, message);
|
||||
});
|
||||
}
|
||||
if (hasError(ERROR.PAYABLE_ENTRIES_HAS_NO_VENDORS)) {
|
||||
AppToaster.show({
|
||||
message: formatMessage({
|
||||
id: 'vendors_should_assign_with_payable_account_only',
|
||||
|
||||
if ((error = getError(ERROR.PAYABLE_ENTRIES_HAS_NO_VENDORS))) {
|
||||
toastMessages.push(
|
||||
formatMessage({
|
||||
id: 'vendors_should_selected_with_payable_account_only',
|
||||
}),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
);
|
||||
setEntriesErrors(error.indexes, 'contact_id', 'error');
|
||||
}
|
||||
if (hasError(ERROR.RECEIVABLE_ENTRIES_HAS_NO_CUSTOMERS)) {
|
||||
AppToaster.show({
|
||||
message: formatMessage({
|
||||
id: 'entries_with_receivable_account_no_assigned_with_customers',
|
||||
if ((error = getError(ERROR.RECEIVABLE_ENTRIES_HAS_NO_CUSTOMERS))) {
|
||||
toastMessages.push(
|
||||
formatMessage({
|
||||
id: 'should_select_customers_with_entries_have_receivable_account',
|
||||
}),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
);
|
||||
setEntriesErrors(error.indexes, 'contact_id', 'error');
|
||||
}
|
||||
if (hasError(ERROR.PAYABLE_ENTRIES_HAS_NO_VENDORS)) {
|
||||
AppToaster.show({
|
||||
message: formatMessage({
|
||||
id: 'entries_with_payable_account_no_assigned_with_vendors',
|
||||
if ((error = getError(ERROR.CUSTOMERS_NOT_WITH_RECEVIABLE_ACC))) {
|
||||
toastMessages.push(
|
||||
formatMessage({
|
||||
id: 'customers_should_selected_with_receivable_account_only',
|
||||
}),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
);
|
||||
setEntriesErrors(error.indexes, 'account_id', 'error');
|
||||
}
|
||||
if (hasError(ERROR.JOURNAL_NUMBER_ALREADY_EXISTS)) {
|
||||
setErrors({
|
||||
journal_number: formatMessage({
|
||||
if ((error = getError(ERROR.VENDORS_NOT_WITH_PAYABLE_ACCOUNT))) {
|
||||
toastMessages.push(
|
||||
formatMessage({
|
||||
id: 'vendors_should_selected_with_payable_account_only',
|
||||
}),
|
||||
);
|
||||
setEntriesErrors(error.indexes, 'account_id', 'error');
|
||||
}
|
||||
if ((error = getError(ERROR.JOURNAL_NUMBER_ALREADY_EXISTS))) {
|
||||
newErrors = setWith(
|
||||
newErrors,
|
||||
'journal_number',
|
||||
formatMessage({
|
||||
id: 'journal_number_is_already_used',
|
||||
}),
|
||||
});
|
||||
);
|
||||
}
|
||||
setErrors({ ...newErrors });
|
||||
AppToaster.show({
|
||||
message: toastMessages.map((message) => {
|
||||
return <div>- {message}</div>;
|
||||
}),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
};
|
||||
|
||||
const formik = useFormik({
|
||||
@@ -255,7 +277,7 @@ function MakeJournalEntriesForm({
|
||||
} else if (totalCredit === 0 || totalDebit === 0) {
|
||||
AppToaster.show({
|
||||
message: formatMessage({
|
||||
id: 'should_total_of_credit_and_debit_be_bigger_then_zero',
|
||||
id: 'amount_cannot_be_zero_or_empty',
|
||||
}),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
@@ -353,7 +375,10 @@ function MakeJournalEntriesForm({
|
||||
|
||||
// Handle click on add a new line/row.
|
||||
const handleClickAddNewRow = () => {
|
||||
formik.setFieldValue('entries', [...formik.values.entries, defaultEntry]);
|
||||
formik.setFieldValue(
|
||||
'entries',
|
||||
reorderingEntriesIndex([...formik.values.entries, defaultEntry]),
|
||||
);
|
||||
};
|
||||
|
||||
// Handle click `Clear all lines` button.
|
||||
@@ -370,13 +395,12 @@ function MakeJournalEntriesForm({
|
||||
<MakeJournalEntriesHeader formik={formik} />
|
||||
|
||||
<MakeJournalEntriesTable
|
||||
values={formik.values}
|
||||
values={formik.values.entries}
|
||||
formik={formik}
|
||||
defaultRow={defaultEntry}
|
||||
onClickClearAllLines={handleClickClearLines}
|
||||
onClickAddNewRow={handleClickAddNewRow}
|
||||
/>
|
||||
|
||||
<MakeJournalEntriesFooter
|
||||
formik={formik}
|
||||
onSubmitClick={handleSubmitClick}
|
||||
|
||||
@@ -109,7 +109,7 @@ function MakeJournalEntriesTable({
|
||||
const { formatMessage } = useIntl();
|
||||
|
||||
useEffect(() => {
|
||||
setRows([...values.entries.map((e) => ({ ...e, rowType: 'editor' }))]);
|
||||
setRows([...values.map((e) => ({ ...e, rowType: 'editor' }))]);
|
||||
}, [values, setRows]);
|
||||
|
||||
// Final table rows editor rows and total and final blank row.
|
||||
@@ -217,6 +217,9 @@ function MakeJournalEntriesTable({
|
||||
|
||||
const handleRemoveRow = useCallback(
|
||||
(rowIndex) => {
|
||||
// Can't continue if there is just one row line or less.
|
||||
if (rows.length <= 2) { return; }
|
||||
|
||||
const removeIndex = parseInt(rowIndex, 10);
|
||||
const newRows = rows.filter((row, index) => index !== removeIndex);
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ import withManualJournalsActions from 'containers/Accounting/withManualJournalsA
|
||||
function StatusAccessor(row) {
|
||||
return (
|
||||
<Choose>
|
||||
<Choose.When condition={row.status}>
|
||||
<Choose.When condition={!!row.status}>
|
||||
<Tag minimal={true}>
|
||||
<T id={'published'} />
|
||||
</Tag>
|
||||
@@ -178,7 +178,7 @@ function ManualJournalsDataTable({
|
||||
{
|
||||
id: 'status',
|
||||
Header: formatMessage({ id: 'status' }),
|
||||
accessor: StatusAccessor,
|
||||
accessor: row => StatusAccessor(row),
|
||||
width: 95,
|
||||
className: 'status',
|
||||
},
|
||||
|
||||
@@ -306,7 +306,7 @@ function AccountsChart({
|
||||
setBulkInactiveAccounts(false);
|
||||
AppToaster.show({
|
||||
message: formatMessage({
|
||||
id: 'the_accounts_has_been_successfully_inactivated',
|
||||
id: 'the_accounts_have_been_successfully_inactivated',
|
||||
}),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useMemo } from 'react';
|
||||
import React, { useCallback, useMemo, useEffect } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Classes,
|
||||
@@ -6,24 +6,24 @@ import {
|
||||
InputGroup,
|
||||
Intent,
|
||||
TextArea,
|
||||
MenuItem,
|
||||
Checkbox,
|
||||
Position,
|
||||
} from '@blueprintjs/core';
|
||||
import * as Yup from 'yup';
|
||||
import { useFormik } from 'formik';
|
||||
import { FormattedMessage as T, useIntl } from 'react-intl';
|
||||
import { If } from 'components';
|
||||
import { omit, pick } from 'lodash';
|
||||
import { pick } from 'lodash';
|
||||
import { useQuery, queryCache } from 'react-query';
|
||||
import classNames from 'classnames';
|
||||
import Yup from 'services/yup';
|
||||
import {
|
||||
ListSelect,
|
||||
If,
|
||||
ErrorMessage,
|
||||
Dialog,
|
||||
AppToaster,
|
||||
FieldRequiredHint,
|
||||
Hint,
|
||||
AccountsSelectList,
|
||||
AccountsTypesSelect,
|
||||
} from 'components';
|
||||
import AccountFormDialogContainer from 'containers/Dialogs/AccountFormDialog.container';
|
||||
|
||||
@@ -53,33 +53,33 @@ function AccountFormDialog({
|
||||
closeDialog,
|
||||
}) {
|
||||
const { formatMessage } = useIntl();
|
||||
const accountFormValidationSchema = Yup.object().shape({
|
||||
const validationSchema = Yup.object().shape({
|
||||
name: Yup.string()
|
||||
.required()
|
||||
.min(3)
|
||||
.max(255)
|
||||
.label(formatMessage({ id: 'account_name_' })),
|
||||
code: Yup.number(),
|
||||
account_type_id: Yup.string()
|
||||
.nullable()
|
||||
code: Yup.string().digits().min(3).max(6),
|
||||
account_type_id: Yup.number()
|
||||
.required()
|
||||
.label(formatMessage({ id: 'account_type_id' })),
|
||||
description: Yup.string().nullable().trim(),
|
||||
parent_account_id: Yup.string().nullable(),
|
||||
description: Yup.string().min(3).max(512).nullable().trim(),
|
||||
parent_account_id: Yup.number().nullable(),
|
||||
});
|
||||
const initialValues = useMemo(
|
||||
() => ({
|
||||
account_type_id: null,
|
||||
name: '',
|
||||
description: '',
|
||||
code: '',
|
||||
type: '',
|
||||
description: '',
|
||||
parent_account_id: null,
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
const transformApiErrors = (errors) => {
|
||||
const fields = {};
|
||||
if (errors.find((e) => e.type === 'NOT_UNIQUE_CODE')) {
|
||||
fields.code = 'Account code is not unqiue.';
|
||||
fields.code = formatMessage({ id: 'account_code_is_not_unique' });
|
||||
}
|
||||
return fields;
|
||||
};
|
||||
@@ -98,20 +98,33 @@ function AccountFormDialog({
|
||||
enableReinitialize: true,
|
||||
initialValues: {
|
||||
...initialValues,
|
||||
...(payload.action === 'edit' && pick(account, Object.keys(initialValues))),
|
||||
...(payload.action === 'edit' &&
|
||||
pick(account, Object.keys(initialValues))),
|
||||
},
|
||||
validationSchema: accountFormValidationSchema,
|
||||
validationSchema,
|
||||
onSubmit: (values, { setSubmitting, setErrors }) => {
|
||||
const exclude = ['subaccount'];
|
||||
const form = pick(values, Object.keys(initialValues));
|
||||
|
||||
const toastAccountName = values.code
|
||||
? `${values.code} - ${values.name}`
|
||||
: values.name;
|
||||
|
||||
const afterSubmit = () => {
|
||||
closeDialog(dialogName);
|
||||
queryCache.invalidateQueries('accounts-table');
|
||||
queryCache.invalidateQueries('accounts-list');
|
||||
};
|
||||
|
||||
const afterErrors = (errors) => {
|
||||
const errorsTransformed = transformApiErrors(errors);
|
||||
setErrors({ ...errorsTransformed });
|
||||
setSubmitting(false);
|
||||
};
|
||||
|
||||
if (payload.action === 'edit') {
|
||||
requestEditAccount(payload.id, values)
|
||||
requestEditAccount(payload.id, form)
|
||||
.then((response) => {
|
||||
closeDialog(dialogName);
|
||||
queryCache.invalidateQueries('accounts-table');
|
||||
afterSubmit(response);
|
||||
|
||||
AppToaster.show({
|
||||
message: formatMessage(
|
||||
@@ -124,19 +137,11 @@ function AccountFormDialog({
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
})
|
||||
.catch((errors) => {
|
||||
const errorsTransformed = transformApiErrors(errors);
|
||||
setErrors({ ...errorsTransformed });
|
||||
setSubmitting(false);
|
||||
});
|
||||
.catch(afterErrors);
|
||||
} else {
|
||||
requestSubmitAccount({
|
||||
payload: payload.parent_account_id,
|
||||
form: { ...omit(values, exclude) },
|
||||
})
|
||||
requestSubmitAccount({ form })
|
||||
.then((response) => {
|
||||
closeDialog(dialogName);
|
||||
queryCache.invalidateQueries('accounts-table', { force: true });
|
||||
afterSubmit(response);
|
||||
|
||||
AppToaster.show({
|
||||
message: formatMessage(
|
||||
@@ -150,70 +155,28 @@ function AccountFormDialog({
|
||||
position: Position.BOTTOM,
|
||||
});
|
||||
})
|
||||
.catch((errors) => {
|
||||
const errorsTransformed = transformApiErrors(errors);
|
||||
setErrors({ ...errorsTransformed });
|
||||
setSubmitting(false);
|
||||
});
|
||||
.catch(afterErrors);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (values.parent_account_id) {
|
||||
setFieldValue('subaccount', true);
|
||||
}
|
||||
}, [values.parent_account_id]);
|
||||
|
||||
// Filtered accounts based on the given account type.
|
||||
const filteredAccounts = useMemo(
|
||||
() =>
|
||||
accounts.filter(
|
||||
(account) => account.account_type_id === values.account_type_id,
|
||||
(account) =>
|
||||
account.account_type_id === values.account_type_id ||
|
||||
!values.account_type_id,
|
||||
),
|
||||
[accounts, values.account_type_id],
|
||||
);
|
||||
|
||||
// Filters accounts types items.
|
||||
const filterAccountTypeItems = (query, accountType, _index, exactMatch) => {
|
||||
const normalizedTitle = accountType.name.toLowerCase();
|
||||
const normalizedQuery = query.toLowerCase();
|
||||
|
||||
if (exactMatch) {
|
||||
return normalizedTitle === normalizedQuery;
|
||||
} else {
|
||||
return normalizedTitle.indexOf(normalizedQuery) >= 0;
|
||||
}
|
||||
};
|
||||
|
||||
// Account type item of select filed.
|
||||
const accountTypeItem = (item, { handleClick, modifiers, query }) => {
|
||||
return <MenuItem text={item.name} key={item.id} onClick={handleClick} />;
|
||||
};
|
||||
|
||||
// Account item of select accounts field.
|
||||
const accountItem = (item, { handleClick, modifiers, query }) => {
|
||||
return (
|
||||
<MenuItem
|
||||
text={item.name}
|
||||
label={item.code}
|
||||
key={item.id}
|
||||
onClick={handleClick}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
// Filters accounts items.
|
||||
const filterAccountsPredicater = useCallback(
|
||||
(query, account, _index, exactMatch) => {
|
||||
const normalizedTitle = account.name.toLowerCase();
|
||||
const normalizedQuery = query.toLowerCase();
|
||||
|
||||
if (exactMatch) {
|
||||
return normalizedTitle === normalizedQuery;
|
||||
} else {
|
||||
return (
|
||||
`${account.code} ${normalizedTitle}`.indexOf(normalizedQuery) >= 0
|
||||
);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Handles dialog close.
|
||||
const handleClose = useCallback(() => {
|
||||
closeDialog(dialogName);
|
||||
@@ -256,12 +219,12 @@ function AccountFormDialog({
|
||||
fetchAccount.refetch();
|
||||
}
|
||||
if (payload.action === 'new_child') {
|
||||
setFieldValue('subaccount', true);
|
||||
setFieldValue('parent_account_id', payload.parentAccountId);
|
||||
setFieldValue('account_type_id', payload.accountTypeId);
|
||||
}
|
||||
}, [fetchAccount, fetchAccountsList, fetchAccountsTypes]);
|
||||
}, [payload, fetchAccount, fetchAccountsList, fetchAccountsTypes]);
|
||||
|
||||
// Handle account type change.
|
||||
const onChangeAccountType = useCallback(
|
||||
(accountType) => {
|
||||
setFieldValue('account_type_id', accountType.id);
|
||||
@@ -277,21 +240,11 @@ function AccountFormDialog({
|
||||
[setFieldValue],
|
||||
);
|
||||
|
||||
// Handle dialog on closed.
|
||||
const onDialogClosed = useCallback(() => {
|
||||
resetForm();
|
||||
}, [resetForm]);
|
||||
|
||||
const subAccountLabel = useMemo(() => {
|
||||
return (
|
||||
<span>
|
||||
<T id={'sub_account'} />
|
||||
<Hint />
|
||||
</span>
|
||||
);
|
||||
}, []);
|
||||
|
||||
const requiredSpan = useMemo(() => <span class="required">*</span>, []);
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
name={dialogName}
|
||||
@@ -332,18 +285,13 @@ function AccountFormDialog({
|
||||
errors.account_type_id && touched.account_type_id && Intent.DANGER
|
||||
}
|
||||
>
|
||||
<ListSelect
|
||||
items={accountsTypes}
|
||||
noResults={<MenuItem disabled={true} text="No results." />}
|
||||
itemRenderer={accountTypeItem}
|
||||
itemPredicate={filterAccountTypeItems}
|
||||
popoverProps={{ minimal: true }}
|
||||
onItemSelect={onChangeAccountType}
|
||||
selectedItem={values.account_type_id}
|
||||
selectedItemProp={'id'}
|
||||
defaultText={<T id={'select_account_type'} />}
|
||||
labelProp={'name'}
|
||||
<AccountsTypesSelect
|
||||
accountsTypes={accountsTypes}
|
||||
selectedTypeId={values.account_type_id}
|
||||
defaultSelectText={<T id={'select_account_type'} />}
|
||||
onTypeSelected={onChangeAccountType}
|
||||
buttonProps={{ disabled: payload.action === 'edit' }}
|
||||
popoverProps={{ minimal: true }}
|
||||
/>
|
||||
</FormGroup>
|
||||
|
||||
@@ -384,7 +332,12 @@ function AccountFormDialog({
|
||||
>
|
||||
<Checkbox
|
||||
inline={true}
|
||||
label={subAccountLabel}
|
||||
label={
|
||||
<>
|
||||
<T id={'sub_account'} />
|
||||
<Hint />
|
||||
</>
|
||||
}
|
||||
{...getFieldProps('subaccount')}
|
||||
checked={values.subaccount}
|
||||
/>
|
||||
@@ -400,17 +353,11 @@ function AccountFormDialog({
|
||||
)}
|
||||
inline={true}
|
||||
>
|
||||
<ListSelect
|
||||
items={filteredAccounts}
|
||||
noResults={<MenuItem disabled={true} text="No results." />}
|
||||
itemRenderer={accountItem}
|
||||
itemPredicate={filterAccountsPredicater}
|
||||
popoverProps={{ minimal: true }}
|
||||
onItemSelect={onChangeSubaccount}
|
||||
selectedItem={values.parent_account_id}
|
||||
selectedItemProp={'id'}
|
||||
defaultText={<T id={'select_parent_account'} />}
|
||||
labelProp={'name'}
|
||||
<AccountsSelectList
|
||||
accounts={filteredAccounts}
|
||||
onAccountSelected={onChangeSubaccount}
|
||||
defaultSelectText={<T id={'select_parent_account'} />}
|
||||
selectedAccountId={values.parent_account_id}
|
||||
/>
|
||||
</FormGroup>
|
||||
</If>
|
||||
@@ -424,7 +371,7 @@ function AccountFormDialog({
|
||||
>
|
||||
<TextArea
|
||||
growVertically={true}
|
||||
large={true}
|
||||
height={280}
|
||||
{...getFieldProps('description')}
|
||||
/>
|
||||
</FormGroup>
|
||||
|
||||
@@ -154,7 +154,7 @@ function ExpensesDataTable({
|
||||
{
|
||||
id: 'payment_date',
|
||||
Header: formatMessage({ id: 'payment_date' }),
|
||||
accessor: () => moment().format('YYYY MMM DD'),
|
||||
accessor: (r) => moment(r.payment_date).format('YYYY MMM DD'),
|
||||
width: 140,
|
||||
className: 'payment_date',
|
||||
},
|
||||
|
||||
@@ -12,8 +12,8 @@ export default function ExpenseFloatingFooter({
|
||||
return (
|
||||
<div className={'form__floating-footer'}>
|
||||
<Button
|
||||
intent={Intent.PRIMARY}
|
||||
disabled={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
type="submit"
|
||||
onClick={() => {
|
||||
onSubmitClick({ publish: true, redirect: true });
|
||||
|
||||
@@ -28,6 +28,8 @@ import Dragzone from 'components/Dragzone';
|
||||
import useMedia from 'hooks/useMedia';
|
||||
import { compose, repeatValue } from 'utils';
|
||||
|
||||
const MIN_LINES_NUMBER = 4;
|
||||
|
||||
function ExpenseForm({
|
||||
// #withMedia
|
||||
requestSubmitMedia,
|
||||
@@ -81,22 +83,26 @@ function ExpenseForm({
|
||||
|
||||
const validationSchema = Yup.object().shape({
|
||||
beneficiary: Yup.string().label(formatMessage({ id: 'beneficiary' })),
|
||||
payment_account_id: Yup.string()
|
||||
payment_account_id: Yup.number()
|
||||
.required()
|
||||
.label(formatMessage({ id: 'payment_account_' })),
|
||||
payment_date: Yup.date()
|
||||
.required()
|
||||
.label(formatMessage({ id: 'payment_date_' })),
|
||||
reference_no: Yup.string(),
|
||||
currency_code: Yup.string().label(formatMessage({ id: 'currency_code' })),
|
||||
reference_no: Yup.string().min(1).max(255),
|
||||
currency_code: Yup.string()
|
||||
.nullable()
|
||||
.label(formatMessage({ id: 'currency_code' })),
|
||||
description: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(1024)
|
||||
.label(formatMessage({ id: 'description' })),
|
||||
publish: Yup.boolean().label(formatMessage({ id: 'publish' })),
|
||||
categories: Yup.array().of(
|
||||
Yup.object().shape({
|
||||
index: Yup.number().nullable(),
|
||||
amount: Yup.number().nullable(),
|
||||
index: Yup.number().min(1).max(1000).nullable(),
|
||||
amount: Yup.number().decimalScale(13).nullable(),
|
||||
expense_account_id: Yup.number()
|
||||
.nullable()
|
||||
.when(['amount'], {
|
||||
@@ -134,9 +140,7 @@ function ExpenseForm({
|
||||
description: '',
|
||||
reference_no: '',
|
||||
currency_code: '',
|
||||
categories: [
|
||||
...repeatValue(defaultCategory, 4),
|
||||
],
|
||||
categories: [...repeatValue(defaultCategory, MIN_LINES_NUMBER)],
|
||||
}),
|
||||
[defaultCategory],
|
||||
);
|
||||
@@ -153,9 +157,15 @@ function ExpenseForm({
|
||||
...(expense
|
||||
? {
|
||||
...pick(expense, Object.keys(defaultInitialValues)),
|
||||
categories: expense.categories.map((category) => ({
|
||||
...pick(category, Object.keys(defaultCategory)),
|
||||
})),
|
||||
categories: [
|
||||
...expense.categories.map((category) => ({
|
||||
...pick(category, Object.keys(defaultCategory)),
|
||||
})),
|
||||
...repeatValue(
|
||||
defaultCategory,
|
||||
Math.max(MIN_LINES_NUMBER - expense.categories.length, 0),
|
||||
),
|
||||
],
|
||||
}
|
||||
: {
|
||||
...defaultInitialValues,
|
||||
@@ -184,6 +194,20 @@ function ExpenseForm({
|
||||
...initialValues,
|
||||
},
|
||||
onSubmit: async (values, { setSubmitting, setErrors, resetForm }) => {
|
||||
setSubmitting(true);
|
||||
const totalAmount = values.categories.reduce((total, item) => {
|
||||
return total + item.amount;
|
||||
}, 0);
|
||||
|
||||
if (totalAmount <= 0) {
|
||||
AppToaster.show({
|
||||
message: formatMessage({
|
||||
id: 'amount_cannot_be_zero_or_empty',
|
||||
}),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const categories = values.categories.filter(
|
||||
(category) =>
|
||||
category.amount && category.index && category.expense_account_id,
|
||||
@@ -193,7 +217,6 @@ function ExpenseForm({
|
||||
publish: payload.publish,
|
||||
categories,
|
||||
};
|
||||
|
||||
const saveExpense = (mdeiaIds) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const requestForm = { ...form, media_ids: mdeiaIds };
|
||||
@@ -237,11 +260,9 @@ function ExpenseForm({
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
formik.resetForm();
|
||||
resetForm();
|
||||
saveInvokeSubmit({ action: 'new', ...payload });
|
||||
clearSavedMediaIds();
|
||||
|
||||
// resolve(response);
|
||||
})
|
||||
.catch((errors) => {
|
||||
setSubmitting(false);
|
||||
@@ -298,11 +319,9 @@ function ExpenseForm({
|
||||
const handleClearAllLines = () => {
|
||||
formik.setFieldValue(
|
||||
'categories',
|
||||
orderingCategoriesIndex([
|
||||
...repeatValue(defaultCategory, 4),
|
||||
]),
|
||||
);
|
||||
}
|
||||
orderingCategoriesIndex([...repeatValue(defaultCategory, MIN_LINES_NUMBER)]),
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={'expense-form'}>
|
||||
@@ -324,7 +343,6 @@ function ExpenseForm({
|
||||
>
|
||||
<TextArea
|
||||
growVertically={true}
|
||||
large={true}
|
||||
{...formik.getFieldProps('description')}
|
||||
/>
|
||||
</FormGroup>
|
||||
|
||||
@@ -61,36 +61,6 @@ function ExpenseFormHeader({
|
||||
}
|
||||
};
|
||||
|
||||
// Account item of select accounts field.
|
||||
const accountItem = (item, { handleClick }) => {
|
||||
return (
|
||||
<MenuItem
|
||||
key={item.id}
|
||||
text={item.name}
|
||||
label={item.code}
|
||||
onClick={handleClick}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
// Filters accounts items.
|
||||
// @filter accounts predicator resauble
|
||||
const filterAccountsPredicater = useCallback(
|
||||
(query, account, _index, exactMatch) => {
|
||||
const normalizedTitle = account.name.toLowerCase();
|
||||
const normalizedQuery = query.toLowerCase();
|
||||
|
||||
if (exactMatch) {
|
||||
return normalizedTitle === normalizedQuery;
|
||||
} else {
|
||||
return (
|
||||
`${account.code} ${normalizedTitle}`.indexOf(normalizedQuery) >= 0
|
||||
);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Handles change account.
|
||||
const onChangeAccount = useCallback(
|
||||
(account) => {
|
||||
@@ -112,6 +82,12 @@ function ExpenseFormHeader({
|
||||
[setFieldValue, selectedItems],
|
||||
);
|
||||
|
||||
// Filter payment accounts.
|
||||
const paymentAccounts = useMemo(
|
||||
() => accountsList.filter(a => a?.type?.key === 'current_asset'),
|
||||
[accountsList],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={'dashboard__insider--expense-form__header'}>
|
||||
<Row>
|
||||
@@ -165,7 +141,7 @@ function ExpenseFormHeader({
|
||||
}
|
||||
>
|
||||
<AccountsSelectList
|
||||
accounts={accountsList}
|
||||
accounts={paymentAccounts}
|
||||
onAccountSelected={onChangeAccount}
|
||||
defaultSelectText={<T id={'select_payment_account'} />}
|
||||
selectedAccountId={values.payment_account_id}
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
} from 'components/DataTableCells';
|
||||
import withAccounts from 'containers/Accounts/withAccounts';
|
||||
|
||||
|
||||
const ExpenseCategoryHeaderCell = () => {
|
||||
return (
|
||||
<>
|
||||
@@ -22,10 +21,10 @@ const ExpenseCategoryHeaderCell = () => {
|
||||
<Hint />
|
||||
</>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Actions cell renderer.
|
||||
const ActionsCellRenderer = ({
|
||||
// Actions cell renderer.
|
||||
const ActionsCellRenderer = ({
|
||||
row: { index },
|
||||
column: { id },
|
||||
cell: { value: initialValue },
|
||||
@@ -101,16 +100,11 @@ function ExpenseTable({
|
||||
const { formatMessage } = useIntl();
|
||||
|
||||
useEffect(() => {
|
||||
setRows([
|
||||
...categories.map((e) => ({ ...e, rowType: 'editor' })),
|
||||
]);
|
||||
setRows([...categories.map((e) => ({ ...e, rowType: 'editor' }))]);
|
||||
}, [categories]);
|
||||
|
||||
// Final table rows editor rows and total and final blank row.
|
||||
const tableRows = useMemo(
|
||||
() => [...rows, { rowType: 'total' }],
|
||||
[rows],
|
||||
);
|
||||
const tableRows = useMemo(() => [...rows, { rowType: 'total' }], [rows]);
|
||||
|
||||
// Memorized data table columns.
|
||||
const columns = useMemo(
|
||||
@@ -133,6 +127,7 @@ function ExpenseTable({
|
||||
disableSortBy: true,
|
||||
disableResizing: true,
|
||||
width: 250,
|
||||
accountsDataProp: 'expenseAccounts',
|
||||
},
|
||||
{
|
||||
Header: formatMessage({ id: 'amount_currency' }, { currency: 'USD' }),
|
||||
@@ -187,6 +182,11 @@ function ExpenseTable({
|
||||
// Handles click remove datatable row.
|
||||
const handleRemoveRow = useCallback(
|
||||
(rowIndex) => {
|
||||
// Can't continue if there is just one row line or less.
|
||||
if (rows.length <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const removeIndex = parseInt(rowIndex, 10);
|
||||
const newRows = rows.filter((row, index) => index !== removeIndex);
|
||||
|
||||
@@ -220,6 +220,12 @@ function ExpenseTable({
|
||||
[rows],
|
||||
);
|
||||
|
||||
// Filter expense accounts.
|
||||
const expenseAccounts = useMemo(
|
||||
() => accountsList.filter((a) => a?.type?.root_type === 'expense'),
|
||||
[accountsList],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={'dashboard__insider--expense-form__table'}>
|
||||
<DataTable
|
||||
@@ -229,6 +235,7 @@ function ExpenseTable({
|
||||
sticky={true}
|
||||
payload={{
|
||||
accounts: accountsList,
|
||||
expenseAccounts,
|
||||
errors: errors.categories || [],
|
||||
updateData: handleUpdateData,
|
||||
removeRow: handleRemoveRow,
|
||||
|
||||
@@ -109,7 +109,7 @@ function ExpensesList({
|
||||
.then(() => {
|
||||
AppToaster.show({
|
||||
message: formatMessage(
|
||||
{ id: 'the_expenses_has_been_successfully_deleted' },
|
||||
{ id: 'the_expenses_have_been_successfully_deleted' },
|
||||
{ count: selectedRowsCount },
|
||||
),
|
||||
intent: Intent.SUCCESS,
|
||||
@@ -160,6 +160,7 @@ function ExpensesList({
|
||||
requestPublishExpense(expense.id).then(() => {
|
||||
AppToaster.show({
|
||||
message: formatMessage({ id: 'the_expense_id_has_been_published' }),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
});
|
||||
fetchExpenses.refetch();
|
||||
|
||||
@@ -5,7 +5,7 @@ export default () => {
|
||||
const getExpenseById = getExpenseByIdFactory();
|
||||
|
||||
const mapStateToProps = (state, props) => ({
|
||||
expenseDetail: getExpenseById(state, props),
|
||||
expense: getExpenseById(state, props),
|
||||
});
|
||||
return connect(mapStateToProps);
|
||||
};
|
||||
Reference in New Issue
Block a user