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:
Ahmed Bouhuolia
2020-11-12 20:44:22 +02:00
parent f35cf90bc5
commit 6d4b3164a8
36 changed files with 2088 additions and 1878 deletions

View File

@@ -1,12 +1,15 @@
import React from 'react';
import { Intent, Button } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
import { saveInvoke } from 'utils';
export default function BillFloatingActions({
formik: { isSubmitting },
isSubmitting,
onSubmitClick,
onSubmitAndNewClick,
onCancelClick,
bill,
onClearClick,
billId,
}) {
return (
<div className={'form__floating-footer'}>
@@ -15,11 +18,11 @@ export default function BillFloatingActions({
loading={isSubmitting}
intent={Intent.PRIMARY}
type="submit"
onClick={() => {
onSubmitClick({ redirect: true });
onClick={(event) => {
saveInvoke(onSubmitClick, event);
}}
>
{bill && bill.id ? <T id={'edit'} /> : <T id={'save_send'} />}
{billId ? <T id={'edit'} /> : <T id={'save'} />}
</Button>
<Button
@@ -27,24 +30,29 @@ export default function BillFloatingActions({
loading={isSubmitting}
intent={Intent.PRIMARY}
className={'ml1'}
name={'save'}
type="submit"
onClick={() => {
onSubmitClick({ redirect: false });
onClick={(event) => {
saveInvoke(onSubmitAndNewClick, event);
}}
>
<T id={'save'} />
<T id={'save_new'} />
</Button>
<Button className={'ml1'} disabled={isSubmitting}>
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={(event) => {
saveInvoke(onClearClick, event);
}}
>
<T id={'clear'} />
</Button>
<Button
className={'ml1'}
type="submit"
onClick={() => {
onCancelClick && onCancelClick();
onClick={(event) => {
saveInvoke(onCancelClick, event);
}}
>
<T id={'close'} />

View File

@@ -1,23 +1,18 @@
import React, {
useMemo,
useState,
useCallback,
useEffect,
useRef,
} 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 } from '@blueprintjs/core';
import classNames from 'classnames';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { pick, sumBy } from 'lodash';
import { useIntl } from 'react-intl';
import { useHistory } from 'react-router-dom';
import { pick, sumBy, omit } from 'lodash';
import { CLASSES } from 'common/classes';
import { EditBillFormSchema, CreateBillFormSchema } from './BillForm.schema';
import BillFormHeader from './BillFormHeader';
import EstimatesItemsTable from 'containers/Sales/Estimate/EntriesItemsTable';
import BillFloatingActions from './BillFloatingActions';
import BillFormFooter from './BillFormFooter';
import EditableItemsEntriesTable from 'containers/Entries/EditableItemsEntriesTable';
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withMediaActions from 'containers/Media/withMediaActions';
@@ -25,12 +20,31 @@ import withBillActions from './withBillActions';
import withBillDetail from './withBillDetail';
import { AppToaster } from 'components';
import useMedia from 'hooks/useMedia';
import { ERROR } from 'common/errors';
import { compose, repeatValue } from 'utils';
import { compose, repeatValue, orderingLinesIndexes } from 'utils';
const MIN_LINES_NUMBER = 5;
const defaultBill = {
index: 0,
item_id: '',
rate: '',
discount: '',
quantity: '',
description: '',
};
const defaultInitialValues = {
vendor_id: '',
bill_number: '',
bill_date: moment(new Date()).format('YYYY-MM-DD'),
due_date: moment(new Date()).format('YYYY-MM-DD'),
reference_no: '',
note: '',
entries: [...repeatValue(defaultBill, MIN_LINES_NUMBER)],
};
function BillForm({
//#WithMedia
requestSubmitMedia,
@@ -54,27 +68,10 @@ function BillForm({
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 = !billId;
useEffect(() => {
if (bill && bill.id) {
@@ -84,88 +81,7 @@ function BillForm({
}
}, [changePageTitle, bill, formatMessage]);
const validationSchema = Yup.object().shape({
vendor_id: Yup.number()
.required()
.label(formatMessage({ id: 'vendor_name_' })),
bill_date: Yup.date()
.required()
.label(formatMessage({ id: 'bill_date_' })),
due_date: Yup.date()
.required()
.label(formatMessage({ id: 'due_date_' })),
bill_number: Yup.string()
.required()
.label(formatMessage({ id: 'bill_number_' })),
reference_no: Yup.string().nullable().min(1).max(255),
// status: Yup.string().required().nullable(),
note: 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(),
}),
total: Yup.number().nullable(),
discount: Yup.number().nullable().min(0).max(100),
description: Yup.string().nullable(),
}),
),
});
const saveBillSubmit = useCallback(
(payload) => {
onFormSubmit && onFormSubmit(payload);
},
[onFormSubmit],
);
const defaultBill = useMemo(
() => ({
index: 0,
item_id: null,
rate: null,
discount: 0,
quantity: null,
description: '',
}),
[],
);
const defaultInitialValues = useMemo(
() => ({
vendor_id: '',
bill_number: '',
bill_date: moment(new Date()).format('YYYY-MM-DD'),
due_date: moment(new Date()).format('YYYY-MM-DD'),
// status: 'Bill',
reference_no: '',
note: '',
entries: [...repeatValue(defaultBill, MIN_LINES_NUMBER)],
}),
[defaultBill],
);
const orderingIndex = (_bill) => {
return _bill.map((item, index) => ({
...item,
index: index + 1,
}));
};
// Initial values in create and edit mode.
const initialValues = useMemo(
() => ({
...(bill
@@ -183,147 +99,88 @@ function BillForm({
}
: {
...defaultInitialValues,
entries: orderingIndex(defaultInitialValues.entries),
entries: orderingLinesIndexes(defaultInitialValues.entries),
}),
}),
[bill, defaultInitialValues, defaultBill],
[bill],
);
const initialAttachmentFiles = useMemo(() => {
return bill && bill.media
? bill.media.map((attach) => ({
preview: attach.attachment_file,
uploaded: true,
metadata: { ...attach },
}))
: [];
}, [bill]);
// Transform response error to fields.
const handleErrors = (errors, { setErrors }) => {
if (errors.some((e) => e.type === ERROR.BILL_NUMBER_EXISTS)) {
setErrors({
bill_number: formatMessage({
id: 'bill_number_exists',
}),
bill_number: formatMessage({ id: 'bill_number_exists' }),
});
}
};
const formik = useFormik({
validationSchema,
initialValues: {
...initialValues,
},
onSubmit: (values, { setSubmitting, setErrors, resetForm }) => {
const entries = values.entries.filter(
(item) => item.item_id && item.quantity,
);
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
// Handles form submit.
const handleFormSubmit = (
values,
{ setSubmitting, setErrors, resetForm },
) => {
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 (bill && bill.id) {
requestEditBill(bill.id, requestForm)
.then((response) => {
AppToaster.show({
message: formatMessage(
{
id: 'the_bill_has_been_successfully_edited',
},
{ number: values.bill_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
saveBillSubmit({ action: 'update', ...payload });
resetForm();
changePageSubtitle('');
})
.catch((errors) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
});
} else {
requestSubmitBill(requestForm)
.then((response) => {
AppToaster.show({
message: formatMessage(
{ id: 'the_bill_has_been_successfully_created' },
{ number: values.bill_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
saveBillSubmit({ action: 'new', ...payload });
resetForm();
})
.catch((errors) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
});
}
},
});
const handleSubmitClick = useCallback(
(payload) => {
setPayload(payload);
formik.submitForm();
formik.setSubmitting(false);
},
[setPayload, formik],
);
const handleCancelClick = useCallback(
(payload) => {
onCancelForm && onCancelForm(payload);
},
[onCancelForm],
);
const handleDeleteFile = useCallback(
(_deletedFiles) => {
_deletedFiles.forEach((deletedFile) => {
if (deletedFile.uploaded && deletedFile.metadata.id) {
setDeletedFiles([...deletedFiles, deletedFile.metadata.id]);
}
if (totalQuantity === 0) {
AppToaster.show({
message: formatMessage({
id: 'quantity_cannot_be_zero_or_empty',
}),
intent: Intent.DANGER,
});
setSubmitting(false);
return;
}
const form = {
...values,
entries: entries.map((entry) => ({ ...omit(entry, ['total']) })),
};
// Handle the request success.
const onSuccess = (response) => {
AppToaster.show({
message: formatMessage(
{
id: isNewMode
? 'the_bill_has_been_successfully_created'
: 'the_bill_has_been_successfully_edited',
},
{ number: values.bill_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
resetForm();
changePageSubtitle('');
if (submitPayload.redirect) {
history.go('/bills');
}
};
// Handle the request error.
const onError = (errors) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
};
if (isNewMode) {
requestEditBill(bill.id, form).then(onSuccess).catch(onError);
} else {
requestSubmitBill(form).then(onSuccess).catch(onError);
}
};
// Handle bill number changed once the field blur.
const handleBillNumberChanged = useCallback(
(billNumber) => {
changePageSubtitle(billNumber);
},
[setDeletedFiles, deletedFiles],
[changePageSubtitle],
);
const onClickCleanAllLines = () => {
formik.setFieldValue(
'entries',
orderingIndex([...repeatValue(defaultBill, MIN_LINES_NUMBER)]),
);
};
const onClickAddNewRow = () => {
formik.setFieldValue(
'entries',
orderingIndex([...formik.values.entries, defaultBill]),
);
};
const handleBillNumberChanged = useCallback((billNumber) => {
changePageSubtitle(billNumber);
}, []);
// Clear page subtitle once unmount bill form page.
useEffect(
() => () => {
@@ -332,32 +189,38 @@ function BillForm({
[changePageSubtitle],
);
const handleSubmitClick = useCallback(() => {
setSubmitPayload({ redirect: true });
}, [setSubmitPayload]);
const handleCancelClick = useCallback(() => {
history.goBack();
}, [history]);
return (
<div className={classNames(CLASSES.PAGE_FORM, CLASSES.PAGE_FORM_BILL)}>
<form onSubmit={formik.handleSubmit}>
<BillFormHeader
formik={formik}
onBillNumberChanged={handleBillNumberChanged}
/>
<EstimatesItemsTable
formik={formik}
entries={formik.values.entries}
onClickAddNewRow={onClickAddNewRow}
onClickClearAllLines={onClickCleanAllLines}
/>
<BillFormFooter
formik={formik}
oninitialFiles={initialAttachmentFiles}
onDropFiles={handleDeleteFile}
/>
</form>
<BillFloatingActions
formik={formik}
onSubmitClick={handleSubmitClick}
bill={bill}
onCancelClick={handleCancelClick}
/>
<Formik
validationSchema={isNewMode ? CreateBillFormSchema : EditBillFormSchema}
initialValues={initialValues}
onSubmit={handleFormSubmit}
>
{({ isSubmitting, values }) => (
<Form>
<BillFormHeader onBillNumberChanged={handleBillNumberChanged} />
<EditableItemsEntriesTable defaultEntry={defaultBill} />
<BillFormFooter
oninitialFiles={[]}
// onDropFiles={handleDeleteFile}
/>
<BillFloatingActions
isSubmitting={isSubmitting}
billId={billId}
onSubmitClick={handleSubmitClick}
onCancelForm={handleCancelClick}
/>
</Form>
)}
</Formik>
</div>
);
}

View File

@@ -0,0 +1,51 @@
import * as Yup from 'yup';
import { formatMessage } from 'services/intl';
const BillFormSchema = Yup.object().shape({
vendor_id: Yup.number()
.required()
.label(formatMessage({ id: 'vendor_name_' })),
bill_date: Yup.date()
.required()
.label(formatMessage({ id: 'bill_date_' })),
due_date: Yup.date()
.required()
.label(formatMessage({ id: 'due_date_' })),
bill_number: Yup.string()
.required()
.label(formatMessage({ id: 'bill_number_' })),
reference_no: Yup.string().nullable().min(1).max(255),
note: 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(),
}),
total: Yup.number().nullable(),
discount: Yup.number().nullable().min(0).max(100),
description: Yup.string().nullable(),
}),
),
});
const CreateBillFormSchema = BillFormSchema;
const EditBillFormSchema = BillFormSchema;
export {
CreateBillFormSchema,
EditBillFormSchema,
};

View File

@@ -1,21 +1,33 @@
import React from 'react';
import { FormGroup, TextArea } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
import { FastField } from 'formik';
import classNames from 'classnames';
import { Row, Col } from 'components';
import { CLASSES } from 'common/classes';
import Dragzone from 'components/Dragzone';
import { inputIntent } from 'utils';
export default function BillFloatingActions({
formik: { getFieldProps },
// Bill form floating actions.
export default function BillFormFooter({
oninitialFiles,
onDropFiles,
}) {
return (
<div class="page-form__footer">
<div class={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Row>
<Col md={8}>
<FormGroup label={<T id={'note'} />} className={'form-group--note'}>
<TextArea growVertically={true} {...getFieldProps('note')} />
</FormGroup>
<FastField name={'note'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'note'} />}
className={'form-group--note'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup>
)}
</FastField>
</Col>
<Col md={4}>

View File

@@ -1,167 +1,152 @@
import React, { useCallback } from 'react';
import {
FormGroup,
InputGroup,
Intent,
Position,
MenuItem,
} from '@blueprintjs/core';
import React from 'react';
import { FormGroup, InputGroup, Position } from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FormattedMessage as T } from 'react-intl';
import moment from 'moment';
import { momentFormatter, compose, tansformDateValue } from 'utils';
import { FastField, ErrorMessage } from 'formik';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import {
ContactSelecetList,
ErrorMessage,
FieldRequiredHint,
Row,
Col,
} from 'components';
import { ContactSelecetList, FieldRequiredHint, Row, Col } from 'components';
// import withCustomers from 'containers/Customers/withCustomers';
import withVendors from 'containers/Vendors/withVendors';
import withAccounts from 'containers/Accounts/withAccounts';
import withDialogActions from 'containers/Dialog/withDialogActions';
import {
momentFormatter,
compose,
tansformDateValue,
handleDateChange,
inputIntent,
saveInvoke,
} from 'utils';
/**
* Fill form header.
*/
function BillFormHeader({
formik: { errors, touched, setFieldValue, getFieldProps, values },
onBillNumberChanged,
//#withVendors
vendorItems,
}) {
const handleDateChange = useCallback(
(date_filed) => (date) => {
const formatted = moment(date).format('YYYY-MM-DD');
setFieldValue(date_filed, formatted);
},
[setFieldValue],
);
const onChangeSelected = useCallback(
(filedName) => {
return (item) => {
setFieldValue(filedName, item.id);
};
},
[setFieldValue],
);
const handleBillNumberBlur = (event) => {
onBillNumberChanged && onBillNumberChanged(event.currentTarget.value);
saveInvoke(onBillNumberChanged, event.currentTarget.value);
};
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<div className={'page-form__primary-section'}>
{/* Vendor name */}
<FormGroup
label={<T id={'vendor_name'} />}
inline={true}
className={classNames(
'form-group--select-list',
'form-group--vendor',
CLASSES.FILL,
{/* ------- Vendor name ------ */}
<FastField name={'vendor_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'vendor_name'} />}
inline={true}
className={classNames(CLASSES.FILL, 'form-group--vendor')}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'vendor_id'} />}
>
<ContactSelecetList
contactsList={vendorItems}
selectedContactId={value}
defaultSelectText={<T id={'select_vender_account'} />}
onContactSelected={(contact) => {
form.setFieldValue('vendor_id', contact.id);
}}
/>
</FormGroup>
)}
labelInfo={<FieldRequiredHint />}
intent={errors.vendor_id && touched.vendor_id && Intent.DANGER}
helperText={
<ErrorMessage name={'vendor_id'} {...{ errors, touched }} />
}
>
<ContactSelecetList
contactsList={vendorItems}
selectedContactId={values.vendor_id}
defaultSelectText={ <T id={'select_vender_account'} /> }
onContactSelected={onChangeSelected('vendor_id')}
/>
</FormGroup>
</FastField>
<Row className={'row--bill-date'}>
<Col md={7}>
{/* Bill date */}
<FormGroup
label={<T id={'bill_date'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
className={classNames('form-group--select-list', CLASSES.FILL)}
intent={errors.bill_date && touched.bill_date && Intent.DANGER}
helperText={
<ErrorMessage name="bill_date" {...{ errors, touched }} />
}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.bill_date)}
onChange={handleDateChange('bill_date')}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
{/* ------- Bill date ------- */}
<FastField name={'bill_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'bill_date'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
className={classNames(CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="bill_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('bill_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
)}
</FastField>
</Col>
<Col md={5}>
{/* Due date */}
<FormGroup
label={<T id={'due_date'} />}
inline={true}
className={classNames(
'form-group--due-date',
'form-group--select-list',
CLASSES.FILL,
{/* ------- Due date ------- */}
<FastField name={'due_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'due_date'} />}
inline={true}
className={classNames(
'form-group--due-date',
'form-group--select-list',
CLASSES.FILL,
)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="due_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('due_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
)}
intent={errors.due_date && touched.due_date && Intent.DANGER}
helperText={
<ErrorMessage name="due_date" {...{ errors, touched }} />
}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.due_date)}
onChange={handleDateChange('due_date')}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
</FastField>
</Col>
</Row>
{/* Bill number */}
<FormGroup
label={<T id={'bill_number'} />}
inline={true}
className={('form-group--bill_number', CLASSES.FILL)}
intent={errors.bill_number && touched.bill_number && Intent.DANGER}
helperText={
<ErrorMessage name="bill_number" {...{ errors, touched }} />
}
>
<InputGroup
intent={errors.bill_number && touched.bill_number && Intent.DANGER}
minimal={true}
{...getFieldProps('bill_number')}
onBlur={handleBillNumberBlur}
/>
</FormGroup>
{/* ------- Bill number ------- */}
<FastField name={'bill_number'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'bill_number'} />}
inline={true}
className={('form-group--bill_number', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="bill_number" />}
>
<InputGroup
minimal={true}
{...field}
onBlur={handleBillNumberBlur}
/>
</FormGroup>
)}
</FastField>
{/* Reference */}
<FormGroup
label={<T id={'reference'} />}
inline={true}
className={classNames('form-group--reference', CLASSES.FILL)}
intent={errors.reference_no && touched.reference_no && Intent.DANGER}
helperText={
<ErrorMessage name="reference" {...{ errors, touched }} />
}
>
<InputGroup
intent={
errors.reference_no && touched.reference_no && Intent.DANGER
}
minimal={true}
{...getFieldProps('reference_no')}
/>
</FormGroup>
{/* ------- Reference ------- */}
<FastField name={'reference_no'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'reference'} />}
inline={true}
className={classNames('form-group--reference', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="reference" />}
>
<InputGroup minimal={true} {...field} />
</FormGroup>
)}
</FastField>
</div>
</div>
);