mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-16 21:00:31 +00:00
feat: optimize sale estimate form performance.
feat: optimize sale receipt form performance. feat: optimize sale invoice form performance. feat: optimize bill form performance.
This commit is contained in:
@@ -1,24 +1,23 @@
|
||||
import React, {
|
||||
useMemo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import * as Yup from 'yup';
|
||||
import { useFormik } from 'formik';
|
||||
import React, { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { Formik, Form } from 'formik';
|
||||
import moment from 'moment';
|
||||
import { Intent, FormGroup, TextArea } from '@blueprintjs/core';
|
||||
import { FormattedMessage as T, useIntl } from 'react-intl';
|
||||
import { pick, sumBy } from 'lodash';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import { useIntl } from 'react-intl';
|
||||
import { pick, sumBy, omit } from 'lodash';
|
||||
import classNames from 'classnames';
|
||||
import { CLASSES } from 'common/classes';
|
||||
|
||||
import InvoiceFormHeader from './InvoiceFormHeader';
|
||||
import EntriesItemsTable from 'containers/Sales/Estimate/EntriesItemsTable';
|
||||
import InvoiceFloatingActions from './InvoiceFloatingActions';
|
||||
import {
|
||||
CreateInvoiceFormSchema,
|
||||
EditInvoiceFormSchema,
|
||||
} from './InvoiceForm.schema';
|
||||
|
||||
import InvoiceFormHeader from './InvoiceFormHeader';
|
||||
import EditableItemsEntriesTable from 'containers/Entries/EditableItemsEntriesTable';
|
||||
import InvoiceFloatingActions from './InvoiceFloatingActions';
|
||||
import InvoiceFormFooter from './InvoiceFormFooter';
|
||||
import InvoiceNumberChangeWatcher from './InvoiceNumberChangeWatcher';
|
||||
|
||||
import withInvoices from './withInvoices';
|
||||
import withInvoiceActions from './withInvoiceActions';
|
||||
import withInvoiceDetail from './withInvoiceDetail';
|
||||
|
||||
@@ -26,19 +25,40 @@ import withDashboardActions from 'containers/Dashboard/withDashboardActions';
|
||||
import withMediaActions from 'containers/Media/withMediaActions';
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
|
||||
import { AppToaster, Col, Row } from 'components';
|
||||
import Dragzone from 'components/Dragzone';
|
||||
import { AppToaster } from 'components';
|
||||
|
||||
import useMedia from 'hooks/useMedia';
|
||||
import { ERROR } from 'common/errors';
|
||||
|
||||
import { compose, repeatValue } from 'utils';
|
||||
import { compose, repeatValue, saveInvoke, orderingLinesIndexes } from 'utils';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
const MIN_LINES_NUMBER = 4;
|
||||
|
||||
const defaultInvoice = {
|
||||
index: 0,
|
||||
item_id: null,
|
||||
rate: null,
|
||||
discount: 0,
|
||||
quantity: null,
|
||||
description: '',
|
||||
};
|
||||
|
||||
const defaultInitialValues = {
|
||||
customer_id: '',
|
||||
invoice_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
due_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
status: 'SEND',
|
||||
invoice_no: '',
|
||||
reference_no: '',
|
||||
invoice_message: '',
|
||||
terms_conditions: '',
|
||||
entries: [...repeatValue(defaultInvoice, MIN_LINES_NUMBER)],
|
||||
};
|
||||
|
||||
/**
|
||||
* Invoice form.
|
||||
*/
|
||||
|
||||
function InvoiceForm({
|
||||
// #WithMedia
|
||||
requestSubmitMedia,
|
||||
@@ -47,7 +67,6 @@ function InvoiceForm({
|
||||
// #WithInvoiceActions
|
||||
requestSubmitInvoice,
|
||||
requestEditInvoice,
|
||||
setInvoiceNumberChanged,
|
||||
|
||||
// #withDashboard
|
||||
changePageTitle,
|
||||
@@ -60,36 +79,15 @@ function InvoiceForm({
|
||||
// #withInvoiceDetail
|
||||
invoice,
|
||||
|
||||
// #withInvoices
|
||||
invoiceNumberChanged,
|
||||
|
||||
// #own Props
|
||||
invoiceId,
|
||||
onFormSubmit,
|
||||
onCancelForm,
|
||||
}) {
|
||||
const { formatMessage } = useIntl();
|
||||
const [payload, setPayload] = useState({});
|
||||
const history = useHistory();
|
||||
|
||||
const {
|
||||
setFiles,
|
||||
saveMedia,
|
||||
deletedFiles,
|
||||
setDeletedFiles,
|
||||
deleteMedia,
|
||||
} = useMedia({
|
||||
saveCallback: requestSubmitMedia,
|
||||
deleteCallback: requestDeleteMedia,
|
||||
});
|
||||
|
||||
const handleDropFiles = useCallback((_files) => {
|
||||
setFiles(_files.filter((file) => file.uploaded === false));
|
||||
}, []);
|
||||
|
||||
const savedMediaIds = useRef([]);
|
||||
const clearSavedMediaIds = () => {
|
||||
savedMediaIds.current = [];
|
||||
};
|
||||
const [submitPayload, setSubmitPayload] = useState({});
|
||||
const isNewMode = !invoiceId;
|
||||
|
||||
const invoiceNumber = invoiceNumberPrefix
|
||||
? `${invoiceNumberPrefix}-${invoiceNextNumber}`
|
||||
@@ -103,93 +101,13 @@ function InvoiceForm({
|
||||
changePageSubtitle(`No. ${invoiceNumber}`);
|
||||
changePageTitle(formatMessage({ id: 'new_invoice' }));
|
||||
}
|
||||
}, [changePageTitle, changePageSubtitle, invoice, formatMessage]);
|
||||
|
||||
const validationSchema = Yup.object().shape({
|
||||
customer_id: Yup.string()
|
||||
.label(formatMessage({ id: 'customer_name_' }))
|
||||
.required(),
|
||||
invoice_date: Yup.date()
|
||||
.required()
|
||||
.label(formatMessage({ id: 'invoice_date_' })),
|
||||
due_date: Yup.date()
|
||||
.required()
|
||||
.label(formatMessage({ id: 'due_date_' })),
|
||||
invoice_no: Yup.string().label(formatMessage({ id: 'invoice_no_' })),
|
||||
reference_no: Yup.string().min(1).max(255),
|
||||
status: Yup.string().required(),
|
||||
invoice_message: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(1024)
|
||||
.label(formatMessage({ id: 'note' })),
|
||||
terms_conditions: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(1024)
|
||||
.label(formatMessage({ id: 'note' })),
|
||||
|
||||
entries: Yup.array().of(
|
||||
Yup.object().shape({
|
||||
quantity: Yup.number()
|
||||
.nullable()
|
||||
.when(['rate'], {
|
||||
is: (rate) => rate,
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
rate: Yup.number().nullable(),
|
||||
item_id: Yup.number()
|
||||
.nullable()
|
||||
.when(['quantity', 'rate'], {
|
||||
is: (quantity, rate) => quantity || rate,
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
discount: Yup.number().nullable().min(0).max(100),
|
||||
description: Yup.string().nullable(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const saveInvokeSubmit = useCallback(
|
||||
(payload) => {
|
||||
onFormSubmit && onFormSubmit(payload);
|
||||
},
|
||||
[onFormSubmit],
|
||||
);
|
||||
|
||||
const defaultInvoice = useMemo(
|
||||
() => ({
|
||||
index: 0,
|
||||
item_id: null,
|
||||
rate: null,
|
||||
discount: 0,
|
||||
quantity: null,
|
||||
description: '',
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
const defaultInitialValues = useMemo(
|
||||
() => ({
|
||||
customer_id: '',
|
||||
invoice_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
due_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
status: 'SEND',
|
||||
invoice_no: invoiceNumber,
|
||||
reference_no: '',
|
||||
invoice_message: '',
|
||||
terms_conditions: '',
|
||||
entries: [...repeatValue(defaultInvoice, MIN_LINES_NUMBER)],
|
||||
}),
|
||||
[defaultInvoice],
|
||||
);
|
||||
|
||||
const orderingIndex = (_invoice) => {
|
||||
return _invoice.map((item, index) => ({
|
||||
...item,
|
||||
index: index + 1,
|
||||
}));
|
||||
};
|
||||
}, [
|
||||
changePageTitle,
|
||||
changePageSubtitle,
|
||||
invoice,
|
||||
invoiceNumber,
|
||||
formatMessage,
|
||||
]);
|
||||
|
||||
const initialValues = useMemo(
|
||||
() => ({
|
||||
@@ -208,154 +126,93 @@ function InvoiceForm({
|
||||
}
|
||||
: {
|
||||
...defaultInitialValues,
|
||||
entries: orderingIndex(defaultInitialValues.entries),
|
||||
invoice_no: invoiceNumber,
|
||||
entries: orderingLinesIndexes(defaultInitialValues.entries),
|
||||
}),
|
||||
}),
|
||||
[invoice, defaultInitialValues, defaultInvoice],
|
||||
[invoice, invoiceNumber],
|
||||
);
|
||||
|
||||
const initialAttachmentFiles = useMemo(() => {
|
||||
return invoice && invoice.media
|
||||
? invoice.media.map((attach) => ({
|
||||
preview: attach.attachment_file,
|
||||
uploaded: true,
|
||||
metadata: { ...attach },
|
||||
}))
|
||||
: [];
|
||||
}, [invoice]);
|
||||
|
||||
// Handle form errors.
|
||||
const handleErrors = (errors, { setErrors }) => {
|
||||
if (errors.some((e) => e.type === ERROR.SALE_INVOICE_NUMBER_IS_EXISTS)) {
|
||||
setErrors({
|
||||
invoice_no: formatMessage({
|
||||
id: 'sale_invoice_number_is_exists',
|
||||
}),
|
||||
invoice_no: formatMessage({ id: 'sale_invoice_number_is_exists' }),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const formik = useFormik({
|
||||
validationSchema,
|
||||
initialValues: {
|
||||
...initialValues,
|
||||
},
|
||||
onSubmit: (values, { setSubmitting, setErrors, resetForm }) => {
|
||||
setSubmitting(true);
|
||||
// Handles form submit.
|
||||
const handleSubmit = (values, { setSubmitting, setErrors, resetForm }) => {
|
||||
setSubmitting(true);
|
||||
|
||||
const entries = values.entries.filter(
|
||||
(item) => item.item_id && item.quantity,
|
||||
);
|
||||
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
|
||||
const entries = values.entries.filter(
|
||||
(item) => item.item_id && item.quantity,
|
||||
);
|
||||
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
|
||||
|
||||
if (totalQuantity === 0) {
|
||||
AppToaster.show({
|
||||
message: formatMessage({
|
||||
id: 'quantity_cannot_be_zero_or_empty',
|
||||
}),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
const form = {
|
||||
...values,
|
||||
entries,
|
||||
};
|
||||
|
||||
const requestForm = { ...form };
|
||||
if (invoice && invoice.id) {
|
||||
requestEditInvoice(invoice.id, requestForm)
|
||||
.then((response) => {
|
||||
AppToaster.show({
|
||||
message: formatMessage(
|
||||
{
|
||||
id: 'the_invoice_has_been_successfully_edited',
|
||||
},
|
||||
{ number: values.invoice_no },
|
||||
),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
saveInvokeSubmit({ action: 'update', ...payload });
|
||||
resetForm();
|
||||
})
|
||||
.catch((errors) => {
|
||||
handleErrors(errors, { setErrors });
|
||||
setSubmitting(false);
|
||||
});
|
||||
} else {
|
||||
requestSubmitInvoice(requestForm)
|
||||
.then((response) => {
|
||||
AppToaster.show({
|
||||
message: formatMessage(
|
||||
{ id: 'the_invocie_has_been_successfully_created' },
|
||||
{ number: values.invoice_no },
|
||||
),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
saveInvokeSubmit({ action: 'new', ...payload });
|
||||
resetForm();
|
||||
})
|
||||
.catch((errors) => {
|
||||
handleErrors(errors, { setErrors });
|
||||
setSubmitting(false);
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
useEffect(() => {
|
||||
if (invoiceNumberChanged) {
|
||||
formik.setFieldValue('invoice_no', invoiceNumber);
|
||||
changePageSubtitle(`No. ${invoiceNumber}`);
|
||||
setInvoiceNumberChanged(false);
|
||||
// Throw danger toaster in case total quantity equals zero.
|
||||
if (totalQuantity === 0) {
|
||||
AppToaster.show({
|
||||
message: formatMessage({ id: 'quantity_cannot_be_zero_or_empty' }),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
}, [
|
||||
invoiceNumber,
|
||||
invoiceNumberChanged,
|
||||
formik.setFieldValue,
|
||||
changePageSubtitle,
|
||||
]);
|
||||
const form = {
|
||||
...values,
|
||||
entries: entries.map((entry) => ({ ...omit(entry, ['total']) })),
|
||||
};
|
||||
// Handle the request success.
|
||||
const onSuccess = () => {
|
||||
AppToaster.show({
|
||||
message: formatMessage(
|
||||
{
|
||||
id: isNewMode
|
||||
? 'the_invocie_has_been_successfully_created'
|
||||
: 'the_invoice_has_been_successfully_edited',
|
||||
},
|
||||
{ number: values.invoice_no },
|
||||
),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
resetForm();
|
||||
|
||||
const handleSubmitClick = useCallback(
|
||||
(payload) => {
|
||||
setPayload(payload);
|
||||
formik.submitForm();
|
||||
},
|
||||
[setPayload, formik],
|
||||
);
|
||||
if (submitPayload.redirect) {
|
||||
history.push('/invoices');
|
||||
}
|
||||
};
|
||||
// Handle the request error.
|
||||
const onError = (errors) => {
|
||||
if (errors) {
|
||||
handleErrors(errors, { setErrors });
|
||||
}
|
||||
setSubmitting(false);
|
||||
};
|
||||
|
||||
if (invoice && invoice.id) {
|
||||
requestEditInvoice(invoice.id, form).then(onSuccess).catch(onError);
|
||||
} else {
|
||||
requestSubmitInvoice(form).then(onSuccess).catch(onError);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelClick = useCallback(
|
||||
(payload) => {
|
||||
onCancelForm && onCancelForm(payload);
|
||||
history.goBack();
|
||||
},
|
||||
[onCancelForm],
|
||||
[history],
|
||||
);
|
||||
|
||||
const handleDeleteFile = useCallback(
|
||||
(_deletedFiles) => {
|
||||
_deletedFiles.forEach((deletedFile) => {
|
||||
if (deletedFile.uploaded && deletedFile.metadata.id) {
|
||||
setDeletedFiles([...deletedFiles, deletedFile.metadata.id]);
|
||||
}
|
||||
});
|
||||
},
|
||||
[setDeletedFiles, deletedFiles],
|
||||
);
|
||||
const handleSubmitClick = useCallback(() => {
|
||||
setSubmitPayload({ redirect: true });
|
||||
}, [setSubmitPayload]);
|
||||
|
||||
const handleClickAddNewRow = () => {
|
||||
formik.setFieldValue(
|
||||
'entries',
|
||||
orderingIndex([...formik.values.entries, defaultInvoice]),
|
||||
);
|
||||
};
|
||||
|
||||
const handleClearAllLines = () => {
|
||||
formik.setFieldValue(
|
||||
'entries',
|
||||
orderingIndex([...repeatValue(defaultInvoice, MIN_LINES_NUMBER)]),
|
||||
);
|
||||
};
|
||||
const handleSubmitAndNewClick = useCallback(() => {
|
||||
setSubmitPayload({ redirect: false });
|
||||
}, [setSubmitPayload]);
|
||||
|
||||
const handleInvoiceNumberChanged = useCallback(
|
||||
(invoiceNumber) => {
|
||||
@@ -366,62 +223,31 @@ function InvoiceForm({
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM, CLASSES.PAGE_FORM_INVOICE)}>
|
||||
<form onSubmit={formik.handleSubmit}>
|
||||
<InvoiceFormHeader
|
||||
onInvoiceNumberChanged={handleInvoiceNumberChanged}
|
||||
formik={formik}
|
||||
/>
|
||||
<EntriesItemsTable
|
||||
entries={formik.values.entries}
|
||||
onClickAddNewRow={handleClickAddNewRow}
|
||||
onClickClearAllLines={handleClearAllLines}
|
||||
formik={formik}
|
||||
/>
|
||||
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
|
||||
<Row>
|
||||
<Col md={8}>
|
||||
{/* --------- Invoice message --------- */}
|
||||
<FormGroup
|
||||
label={<T id={'invoice_message'} />}
|
||||
className={'form-group--invoice_message'}
|
||||
>
|
||||
<TextArea
|
||||
growVertically={true}
|
||||
{...formik.getFieldProps('invoice_message')}
|
||||
/>
|
||||
</FormGroup>
|
||||
|
||||
{/* --------- Terms and conditions --------- */}
|
||||
<FormGroup
|
||||
label={<T id={'terms_conditions'} />}
|
||||
className={'form-group--terms_conditions'}
|
||||
>
|
||||
<TextArea
|
||||
growVertically={true}
|
||||
{...formik.getFieldProps('terms_conditions')}
|
||||
/>
|
||||
</FormGroup>
|
||||
</Col>
|
||||
|
||||
<Col md={4}>
|
||||
<Dragzone
|
||||
initialFiles={initialAttachmentFiles}
|
||||
onDrop={handleDropFiles}
|
||||
onDeleteFile={handleDeleteFile}
|
||||
hint={'Attachments: Maxiumum size: 20MB'}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<InvoiceFloatingActions
|
||||
formik={formik}
|
||||
onSubmitClick={handleSubmitClick}
|
||||
invoice={invoice}
|
||||
onCancelClick={handleCancelClick}
|
||||
/>
|
||||
<Formik
|
||||
validationSchema={
|
||||
isNewMode ? CreateInvoiceFormSchema : EditInvoiceFormSchema
|
||||
}
|
||||
initialValues={initialValues}
|
||||
onSubmit={handleSubmit}
|
||||
>
|
||||
{({ isSubmitting }) => (
|
||||
<Form>
|
||||
<InvoiceFormHeader
|
||||
onInvoiceNumberChanged={handleInvoiceNumberChanged}
|
||||
/>
|
||||
<InvoiceNumberChangeWatcher invoiceNumber={invoiceNumber} />
|
||||
<EditableItemsEntriesTable defaultEntry={defaultInvoice} />
|
||||
<InvoiceFormFooter />
|
||||
<InvoiceFloatingActions
|
||||
isSubmitting={isSubmitting}
|
||||
invoice={invoice}
|
||||
onCancelClick={handleCancelClick}
|
||||
onSubmitClick={handleSubmitClick}
|
||||
onSubmitAndNewClick={handleSubmitAndNewClick}
|
||||
/>
|
||||
</Form>
|
||||
)}
|
||||
</Formik>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -436,5 +262,4 @@ export default compose(
|
||||
invoiceNextNumber: invoiceSettings?.nextNumber,
|
||||
invoiceNumberPrefix: invoiceSettings?.numberPrefix,
|
||||
})),
|
||||
withInvoices(({ invoiceNumberChanged }) => ({ invoiceNumberChanged })),
|
||||
)(InvoiceForm);
|
||||
|
||||
Reference in New Issue
Block a user