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

21
.vscode/FastField.code-snippets vendored Normal file
View File

@@ -0,0 +1,21 @@
{
// Place your Ratteb workspace snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and
// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope
// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is
// used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.
// Placeholders with the same ids are connected.
// Example:
"fastfield": {
"scope": "javascript,typescript",
"prefix": "fastfield",
"body": [
"<FastField name={'${1}'}>",
" {({ form, field: { value }, meta: { error, touched } }) => (",
"",
" )}",
"</FastField>"
],
"description": "Fast field component"
}
}

View File

@@ -26,5 +26,5 @@
"editor.tabSize": 2, "editor.tabSize": 2,
"editor.insertSpaces": true, "editor.insertSpaces": true,
"git.ignoreLimitWarning": true, "git.ignoreLimitWarning": true,
"god.tsconfig": "./tsconfig.json", "god.tsconfig": "./server/tsconfig.json",
} }

View File

@@ -2,6 +2,7 @@ import React, { useCallback, useState, useEffect, useMemo } from 'react';
import { MenuItem, Button } from '@blueprintjs/core'; import { MenuItem, Button } from '@blueprintjs/core';
import { Select } from '@blueprintjs/select'; import { Select } from '@blueprintjs/select';
import { FormattedMessage as T } from 'react-intl'; import { FormattedMessage as T } from 'react-intl';
import classNames from 'classnames';
import { isEmpty } from 'lodash'; import { isEmpty } from 'lodash';
export default function AccountsSelectList({ export default function AccountsSelectList({
@@ -103,6 +104,7 @@ export default function AccountsSelectList({
filterable={true} filterable={true}
onItemSelect={onAccountSelect} onItemSelect={onAccountSelect}
disabled={disabled} disabled={disabled}
className={classNames('form-group--select-list')}
> >
<Button <Button
disabled={disabled} disabled={disabled}

View File

@@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { IntlProvider } from 'react-intl'; import { RawIntlProvider } from 'react-intl';
import { Router, Switch, Route } from 'react-router'; import { Router, Switch, Route } from 'react-router';
import { createBrowserHistory } from 'history'; import { createBrowserHistory } from 'history';
import { ReactQueryConfigProvider } from 'react-query'; import { ReactQueryConfigProvider } from 'react-query';
@@ -9,8 +9,8 @@ import PrivateRoute from 'components/Guards/PrivateRoute';
import Authentication from 'components/Authentication'; import Authentication from 'components/Authentication';
import DashboardPrivatePages from 'components/Dashboard/PrivatePages'; import DashboardPrivatePages from 'components/Dashboard/PrivatePages';
import GlobalErrors from 'containers/GlobalErrors/GlobalErrors'; import GlobalErrors from 'containers/GlobalErrors/GlobalErrors';
import intl from 'services/intl';
import messages from 'lang/en';
import 'style/App.scss'; import 'style/App.scss';
function App({ locale }) { function App({ locale }) {
@@ -22,7 +22,7 @@ function App({ locale }) {
}, },
}; };
return ( return (
<IntlProvider locale={locale} messages={messages}> <RawIntlProvider value={intl}>
<div className="App"> <div className="App">
<ReactQueryConfigProvider config={queryConfig}> <ReactQueryConfigProvider config={queryConfig}>
<Router history={history}> <Router history={history}>
@@ -41,7 +41,7 @@ function App({ locale }) {
<ReactQueryDevtools /> <ReactQueryDevtools />
</ReactQueryConfigProvider> </ReactQueryConfigProvider>
</div> </div>
</IntlProvider> </RawIntlProvider>
); );
} }

View File

@@ -57,6 +57,7 @@ export default function ContactSelecetList({
itemPredicate={FilterContacts} itemPredicate={FilterContacts}
itemRenderer={handleContactRenderer} itemRenderer={handleContactRenderer}
popoverProps={{ minimal: true }} popoverProps={{ minimal: true }}
className={'form-group--select-list'}
{...restProps} {...restProps}
/> />
); );

View File

@@ -35,6 +35,7 @@ import CurrencySelectList from './CurrencySelectList'
import SalutationList from './SalutationList'; import SalutationList from './SalutationList';
import DisplayNameList from './DisplayNameList'; import DisplayNameList from './DisplayNameList';
import MoneyInputGroup from './MoneyInputGroup'; import MoneyInputGroup from './MoneyInputGroup';
import Dragzone from './Dragzone';
const Hint = FieldHint; const Hint = FieldHint;
@@ -77,4 +78,5 @@ export {
DisplayNameList, DisplayNameList,
SalutationList, SalutationList,
MoneyInputGroup, MoneyInputGroup,
Dragzone,
}; };

View File

@@ -0,0 +1,83 @@
import React, { useState } from 'react';
import { FastField, useFormikContext } from 'formik';
import { Alert, Intent } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
import ItemsEntriesTable from './ItemsEntriesTable';
import { orderingLinesIndexes, repeatValue } from 'utils';
export default function EditableItemsEntriesTable({
defaultEntry,
minLinesNumber = 2,
linesNumber = 5,
}) {
const { setFieldValue, values } = useFormikContext();
const [clearLinesAlert, setClearLinesAlert] = useState(false);
const handleClickAddNewRow = () => {
setFieldValue(
'entries',
orderingLinesIndexes([...values.entries, defaultEntry]),
);
};
const handleClearAllLines = () => {
setClearLinesAlert(true);
};
const handleClickRemoveLine = (rowIndex) => {
if (values.entries.length <= minLinesNumber) {
return;
}
const removeIndex = parseInt(rowIndex, 10);
const newRows = values.entries.filter((row, index) => index !== removeIndex);
setFieldValue(
'entries',
orderingLinesIndexes(newRows),
);
};
const handleConfirmClearLines = () => {
setFieldValue(
'entries',
orderingLinesIndexes([...repeatValue(defaultEntry, linesNumber)]),
);
setClearLinesAlert(false);
};
const handleCancelClearLines = () => {
setClearLinesAlert(false);
};
return (
<>
<FastField name={'entries'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<ItemsEntriesTable
onUpdateData={(entries) => {
form.setFieldValue('entries', entries);
}}
entries={value}
errors={error}
onClickAddNewRow={handleClickAddNewRow}
onClickClearAllLines={handleClearAllLines}
onClickRemoveRow={handleClickRemoveLine}
/>
)}
</FastField>
<Alert
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={<T id={'ok'} />}
intent={Intent.WARNING}
isOpen={clearLinesAlert}
onCancel={handleCancelClearLines}
onConfirm={handleConfirmClearLines}
>
<p>
Clearing the table lines will delete all entries were applied, Is this
okay?
</p>
</Alert>
</>
);
}

View File

@@ -0,0 +1,267 @@
import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { omit } from 'lodash';
import { Button, Intent, Position, Tooltip } from '@blueprintjs/core';
import { FormattedMessage as T, useIntl } from 'react-intl';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import { Hint, Icon } from 'components';
import DataTable from 'components/DataTable';
import {
InputGroupCell,
MoneyFieldCell,
ItemsListCell,
PercentFieldCell,
DivFieldCell,
} from 'components/DataTableCells';
import withItems from 'containers/Items/withItems';
import {
compose,
formattedAmount,
orderingLinesIndexes,
saveInvoke,
} from 'utils';
// Actions cell renderer component.
const ActionsCellRenderer = ({
row: { index },
column: { id },
cell: { value },
data,
payload,
}) => {
if (data.length <= index + 1) {
return '';
}
const onRemoveRole = () => {
payload.removeRow(index);
};
return (
<Tooltip content={<T id={'remove_the_line'} />} position={Position.LEFT}>
<Button
icon={<Icon icon={'times-circle'} iconSize={14} />}
iconSize={14}
className="m12"
intent={Intent.DANGER}
onClick={onRemoveRole}
/>
</Tooltip>
);
};
// Total cell renderer.
const TotalCellRenderer = (content, type) => (props) => {
if (props.data.length === props.row.index + 1) {
const total = props.data.reduce((total, entry) => {
const amount = parseInt(entry[type], 10);
const computed = amount ? total + amount : total;
return computed;
}, 0);
return <span>{formattedAmount(total, 'USD')}</span>;
}
return content(props);
};
const calculateDiscount = (discount, quantity, rate) =>
quantity * rate - (quantity * rate * discount) / 100;
const CellRenderer = (content, type) => (props) => {
if (props.data.length === props.row.index + 1) {
return '';
}
return content(props);
};
const ItemHeaderCell = () => (
<>
<T id={'product_and_service'} />
<Hint />
</>
);
function ItemsEntriesTable({
//#withitems
itemsCurrentPage,
//#ownProps
entries,
errors,
onUpdateData,
onClickRemoveRow,
onClickAddNewRow,
onClickClearAllLines,
}) {
const [rows, setRows] = useState([]);
const { formatMessage } = useIntl();
useEffect(() => {
setRows([...entries.map((e) => ({ ...e }))]);
}, [entries]);
const columns = useMemo(
() => [
{
Header: '#',
accessor: 'index',
Cell: ({ row: { index } }) => <span>{index + 1}</span>,
width: 40,
disableResizing: true,
disableSortBy: true,
className: 'index',
},
{
Header: ItemHeaderCell,
id: 'item_id',
accessor: 'item_id',
Cell: ItemsListCell,
disableSortBy: true,
width: 180,
},
{
Header: formatMessage({ id: 'description' }),
accessor: 'description',
Cell: InputGroupCell,
disableSortBy: true,
className: 'description',
width: 100,
},
{
Header: formatMessage({ id: 'quantity' }),
accessor: 'quantity',
Cell: CellRenderer(InputGroupCell, 'quantity'),
disableSortBy: true,
width: 80,
className: 'quantity',
},
{
Header: formatMessage({ id: 'rate' }),
accessor: 'rate',
Cell: TotalCellRenderer(MoneyFieldCell, 'rate'),
disableSortBy: true,
width: 80,
className: 'rate',
},
{
Header: formatMessage({ id: 'discount' }),
accessor: 'discount',
Cell: CellRenderer(PercentFieldCell, InputGroupCell),
disableSortBy: true,
width: 80,
className: 'discount',
},
{
Header: formatMessage({ id: 'total' }),
accessor: (row) =>
calculateDiscount(row.discount, row.quantity, row.rate),
Cell: TotalCellRenderer(DivFieldCell, 'total'),
disableSortBy: true,
width: 120,
className: 'total',
},
{
Header: '',
accessor: 'action',
Cell: ActionsCellRenderer,
className: 'actions',
disableSortBy: true,
disableResizing: true,
width: 45,
},
],
[formatMessage],
);
const handleUpdateData = useCallback(
(rowIndex, columnId, value) => {
const newRows = rows.map((row, index) => {
if (index === rowIndex) {
const newRow = { ...rows[rowIndex], [columnId]: value };
return {
...newRow,
total: calculateDiscount(
newRow.discount,
newRow.quantity,
newRow.rate,
),
};
}
return row;
});
saveInvoke(onUpdateData, newRows);
},
[rows, onUpdateData],
);
const handleRemoveRow = useCallback(
(rowIndex) => {
if (rows.length <= 1) {
return;
}
const removeIndex = parseInt(rowIndex, 10);
saveInvoke(onClickRemoveRow, removeIndex);
},
[rows, onClickRemoveRow],
);
const onClickNewRow = (event) => {
saveInvoke(onClickAddNewRow, event);
};
const handleClickClearAllLines = (event) => {
saveInvoke(onClickClearAllLines, event);
};
const rowClassNames = useCallback(
(row) => ({
'row--total': rows.length === row.index + 1,
}),
[rows],
);
return (
<div
className={classNames(
CLASSES.DATATABLE_EDITOR,
CLASSES.DATATABLE_EDITOR_ITEMS_ENTRIES,
)}
>
<DataTable
columns={columns}
data={rows}
rowClassNames={rowClassNames}
sticky={true}
payload={{
items: itemsCurrentPage,
errors: errors || [],
updateData: handleUpdateData,
removeRow: handleRemoveRow,
}}
/>
<div className={classNames(CLASSES.DATATABLE_EDITOR_ACTIONS, 'mt1')}>
<Button
small={true}
className={'button--secondary button--new-line'}
onClick={onClickNewRow}
>
<T id={'new_lines'} />
</Button>
<Button
small={true}
className={'button--secondary button--clear-lines ml1'}
onClick={handleClickClearAllLines}
>
<T id={'clear_all_lines'} />
</Button>
</div>
</div>
);
}
export default compose(
withItems(({ itemsCurrentPage }) => ({
itemsCurrentPage,
})),
)(ItemsEntriesTable);

View File

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

View File

@@ -1,23 +1,18 @@
import React, { import React, { useState, useMemo, useCallback, useEffect } from 'react';
useMemo, import { Formik, Form } from 'formik';
useState,
useCallback,
useEffect,
useRef,
} from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import moment from 'moment'; import moment from 'moment';
import { Intent } from '@blueprintjs/core'; import { Intent } from '@blueprintjs/core';
import classNames from 'classnames'; import classNames from 'classnames';
import { FormattedMessage as T, useIntl } from 'react-intl'; import { useIntl } from 'react-intl';
import { pick, sumBy } from 'lodash'; import { useHistory } from 'react-router-dom';
import { pick, sumBy, omit } from 'lodash';
import { CLASSES } from 'common/classes'; import { CLASSES } from 'common/classes';
import { EditBillFormSchema, CreateBillFormSchema } from './BillForm.schema';
import BillFormHeader from './BillFormHeader'; import BillFormHeader from './BillFormHeader';
import EstimatesItemsTable from 'containers/Sales/Estimate/EntriesItemsTable';
import BillFloatingActions from './BillFloatingActions'; import BillFloatingActions from './BillFloatingActions';
import BillFormFooter from './BillFormFooter'; import BillFormFooter from './BillFormFooter';
import EditableItemsEntriesTable from 'containers/Entries/EditableItemsEntriesTable';
import withDashboardActions from 'containers/Dashboard/withDashboardActions'; import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withMediaActions from 'containers/Media/withMediaActions'; import withMediaActions from 'containers/Media/withMediaActions';
@@ -25,12 +20,31 @@ import withBillActions from './withBillActions';
import withBillDetail from './withBillDetail'; import withBillDetail from './withBillDetail';
import { AppToaster } from 'components'; import { AppToaster } from 'components';
import useMedia from 'hooks/useMedia';
import { ERROR } from 'common/errors'; import { ERROR } from 'common/errors';
import { compose, repeatValue } from 'utils'; import { compose, repeatValue, orderingLinesIndexes } from 'utils';
const MIN_LINES_NUMBER = 5; 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({ function BillForm({
//#WithMedia //#WithMedia
requestSubmitMedia, requestSubmitMedia,
@@ -54,27 +68,10 @@ function BillForm({
onCancelForm, onCancelForm,
}) { }) {
const { formatMessage } = useIntl(); const { formatMessage } = useIntl();
const [payload, setPayload] = useState({}); const history = useHistory();
const { const [submitPayload, setSubmitPayload] = useState({});
setFiles, const isNewMode = !billId;
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 = [];
};
useEffect(() => { useEffect(() => {
if (bill && bill.id) { if (bill && bill.id) {
@@ -84,88 +81,7 @@ function BillForm({
} }
}, [changePageTitle, bill, formatMessage]); }, [changePageTitle, bill, formatMessage]);
const validationSchema = Yup.object().shape({ // Initial values in create and edit mode.
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,
}));
};
const initialValues = useMemo( const initialValues = useMemo(
() => ({ () => ({
...(bill ...(bill
@@ -183,38 +99,26 @@ function BillForm({
} }
: { : {
...defaultInitialValues, ...defaultInitialValues,
entries: orderingIndex(defaultInitialValues.entries), entries: orderingLinesIndexes(defaultInitialValues.entries),
}), }),
}), }),
[bill, defaultInitialValues, defaultBill], [bill],
); );
const initialAttachmentFiles = useMemo(() => { // Transform response error to fields.
return bill && bill.media
? bill.media.map((attach) => ({
preview: attach.attachment_file,
uploaded: true,
metadata: { ...attach },
}))
: [];
}, [bill]);
const handleErrors = (errors, { setErrors }) => { const handleErrors = (errors, { setErrors }) => {
if (errors.some((e) => e.type === ERROR.BILL_NUMBER_EXISTS)) { if (errors.some((e) => e.type === ERROR.BILL_NUMBER_EXISTS)) {
setErrors({ setErrors({
bill_number: formatMessage({ bill_number: formatMessage({ id: 'bill_number_exists' }),
id: 'bill_number_exists',
}),
}); });
} }
}; };
const formik = useFormik({ // Handles form submit.
validationSchema, const handleFormSubmit = (
initialValues: { values,
...initialValues, { setSubmitting, setErrors, resetForm },
}, ) => {
onSubmit: (values, { setSubmitting, setErrors, resetForm }) => {
const entries = values.entries.filter( const entries = values.entries.filter(
(item) => item.item_id && item.quantity, (item) => item.item_id && item.quantity,
); );
@@ -233,96 +137,49 @@ function BillForm({
const form = { const form = {
...values, ...values,
entries, entries: entries.map((entry) => ({ ...omit(entry, ['total']) })),
}; };
const requestForm = { ...form }; // Handle the request success.
if (bill && bill.id) { const onSuccess = (response) => {
requestEditBill(bill.id, requestForm)
.then((response) => {
AppToaster.show({ AppToaster.show({
message: formatMessage( message: formatMessage(
{ {
id: 'the_bill_has_been_successfully_edited', id: isNewMode
? 'the_bill_has_been_successfully_created'
: 'the_bill_has_been_successfully_edited',
}, },
{ number: values.bill_number }, { number: values.bill_number },
), ),
intent: Intent.SUCCESS, intent: Intent.SUCCESS,
}); });
setSubmitting(false); setSubmitting(false);
saveBillSubmit({ action: 'update', ...payload });
resetForm(); resetForm();
changePageSubtitle(''); changePageSubtitle('');
})
.catch((errors) => { if (submitPayload.redirect) {
history.go('/bills');
}
};
// Handle the request error.
const onError = (errors) => {
handleErrors(errors, { setErrors }); handleErrors(errors, { setErrors });
setSubmitting(false); setSubmitting(false);
}); };
if (isNewMode) {
requestEditBill(bill.id, form).then(onSuccess).catch(onError);
} else { } else {
requestSubmitBill(requestForm) requestSubmitBill(form).then(onSuccess).catch(onError);
.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]);
}
});
},
[setDeletedFiles, deletedFiles],
);
const onClickCleanAllLines = () => {
formik.setFieldValue(
'entries',
orderingIndex([...repeatValue(defaultBill, MIN_LINES_NUMBER)]),
);
}; };
const onClickAddNewRow = () => { // Handle bill number changed once the field blur.
formik.setFieldValue( const handleBillNumberChanged = useCallback(
'entries', (billNumber) => {
orderingIndex([...formik.values.entries, defaultBill]),
);
};
const handleBillNumberChanged = useCallback((billNumber) => {
changePageSubtitle(billNumber); changePageSubtitle(billNumber);
}, []); },
[changePageSubtitle],
);
// Clear page subtitle once unmount bill form page. // Clear page subtitle once unmount bill form page.
useEffect( useEffect(
@@ -332,32 +189,38 @@ function BillForm({
[changePageSubtitle], [changePageSubtitle],
); );
const handleSubmitClick = useCallback(() => {
setSubmitPayload({ redirect: true });
}, [setSubmitPayload]);
const handleCancelClick = useCallback(() => {
history.goBack();
}, [history]);
return ( return (
<div className={classNames(CLASSES.PAGE_FORM, CLASSES.PAGE_FORM_BILL)}> <div className={classNames(CLASSES.PAGE_FORM, CLASSES.PAGE_FORM_BILL)}>
<form onSubmit={formik.handleSubmit}> <Formik
<BillFormHeader validationSchema={isNewMode ? CreateBillFormSchema : EditBillFormSchema}
formik={formik} initialValues={initialValues}
onBillNumberChanged={handleBillNumberChanged} onSubmit={handleFormSubmit}
/> >
{({ isSubmitting, values }) => (
<EstimatesItemsTable <Form>
formik={formik} <BillFormHeader onBillNumberChanged={handleBillNumberChanged} />
entries={formik.values.entries} <EditableItemsEntriesTable defaultEntry={defaultBill} />
onClickAddNewRow={onClickAddNewRow}
onClickClearAllLines={onClickCleanAllLines}
/>
<BillFormFooter <BillFormFooter
formik={formik} oninitialFiles={[]}
oninitialFiles={initialAttachmentFiles} // onDropFiles={handleDeleteFile}
onDropFiles={handleDeleteFile}
/> />
</form>
<BillFloatingActions <BillFloatingActions
formik={formik} isSubmitting={isSubmitting}
billId={billId}
onSubmitClick={handleSubmitClick} onSubmitClick={handleSubmitClick}
bill={bill} onCancelForm={handleCancelClick}
onCancelClick={handleCancelClick}
/> />
</Form>
)}
</Formik>
</div> </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 React from 'react';
import { FormGroup, TextArea } from '@blueprintjs/core'; import { FormGroup, TextArea } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl'; import { FormattedMessage as T } from 'react-intl';
import { FastField } from 'formik';
import classNames from 'classnames';
import { Row, Col } from 'components'; import { Row, Col } from 'components';
import { CLASSES } from 'common/classes';
import Dragzone from 'components/Dragzone'; import Dragzone from 'components/Dragzone';
import { inputIntent } from 'utils';
export default function BillFloatingActions({ // Bill form floating actions.
formik: { getFieldProps }, export default function BillFormFooter({
oninitialFiles, oninitialFiles,
onDropFiles, onDropFiles,
}) { }) {
return ( return (
<div class="page-form__footer"> <div class={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Row> <Row>
<Col md={8}> <Col md={8}>
<FormGroup label={<T id={'note'} />} className={'form-group--note'}> <FastField name={'note'}>
<TextArea growVertically={true} {...getFieldProps('note')} /> {({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'note'} />}
className={'form-group--note'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup> </FormGroup>
)}
</FastField>
</Col> </Col>
<Col md={4}> <Col md={4}>

View File

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

View File

@@ -84,7 +84,10 @@ function EntriesItemsTable({
onClickAddNewRow, onClickAddNewRow,
onClickClearAllLines, onClickClearAllLines,
entries, entries,
formik: { errors, setFieldValue, values },
errors,
setFieldValue,
values,
}) { }) {
const [rows, setRows] = useState([]); const [rows, setRows] = useState([]);
const { formatMessage } = useIntl(); const { formatMessage } = useIntl();

View File

@@ -1,47 +1,57 @@
import React from 'react'; import React from 'react';
import { Intent, Button } from '@blueprintjs/core'; import { Intent, Button } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl'; import { FormattedMessage as T } from 'react-intl';
import { queryCache } from 'react-query'; import { saveInvoke } from 'utils';
export default function EstimateFloatingActions({ export default function EstimateFloatingActions({
formik: { isSubmitting, resetForm }, isSubmitting,
onSubmitClick, onSubmitClick,
onCancelClick, onCancelClick,
onClearClick, onClearClick,
estimate, onSubmitAndNewClick,
estimateId,
}) { }) {
const handleSubmitBtnClick = (event) => {
saveInvoke(onSubmitClick, event);
};
const handleCancelBtnClick = (event) => {
saveInvoke(onCancelClick, event);
};
const handleClearBtnClick = (event) => {
saveInvoke(onClearClick, event);
};
const handleSubmitAndNewClick = (event) => {
saveInvoke(onSubmitAndNewClick, event);
}
return ( return (
<div className={'form__floating-footer'}> <div className={'form__floating-footer'}>
<Button <Button
disabled={isSubmitting} disabled={isSubmitting}
intent={Intent.PRIMARY} intent={Intent.PRIMARY}
type="submit" type="submit"
onClick={() => { onClick={handleSubmitBtnClick}
onSubmitClick({ redirect: true });
}}
> >
{estimate && estimate.id ? <T id={'edit'} /> : <T id={'save_send'} />} {(estimateId) ? <T id={'edit'} /> : <T id={'save'} />}
</Button> </Button>
<Button <Button
disabled={isSubmitting} disabled={isSubmitting}
intent={Intent.PRIMARY} intent={Intent.PRIMARY}
className={'ml1'} className={'ml1'}
name={'save'}
type="submit" type="submit"
onClick={() => { onClick={handleSubmitAndNewClick}
onSubmitClick({ redirect: false });
}}
> >
<T id={'save'} /> <T id={'save_new'} />
</Button> </Button>
<Button <Button
className={'ml1'} className={'ml1'}
disabled={isSubmitting} disabled={isSubmitting}
// onClick={() => { onClick={handleClearBtnClick}
// onClearClick && onClearClick();
// }}
> >
<T id={'clear'} /> <T id={'clear'} />
</Button> </Button>
@@ -49,9 +59,7 @@ export default function EstimateFloatingActions({
<Button <Button
className={'ml1'} className={'ml1'}
type="submit" type="submit"
onClick={() => { onClick={handleCancelBtnClick}
onCancelClick && onCancelClick();
}}
> >
<T id={'close'} /> <T id={'close'} />
</Button> </Button>

View File

@@ -1,24 +1,24 @@
import React, { import React, { useMemo, useCallback, useEffect, useState } from 'react';
useMemo, import { Formik, Form } from 'formik';
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import moment from 'moment'; import moment from 'moment';
import { Intent, FormGroup, TextArea } from '@blueprintjs/core'; import { Intent } from '@blueprintjs/core';
import { FormattedMessage as T, useIntl } from 'react-intl'; import { FormattedMessage as T, useIntl } from 'react-intl';
import { pick, sumBy } from 'lodash'; import { pick, sumBy } from 'lodash';
import classNames from 'classnames'; import classNames from 'classnames';
import { useHistory } from 'react-router-dom';
import { CLASSES } from 'common/classes'; import { CLASSES } from 'common/classes';
import EstimateFormHeader from './EstimateFormHeader'; import {
import EntriesItemsTable from './EntriesItemsTable'; CreateEstimateFormSchema,
import EstimateFloatingActions from './EstimateFloatingActions'; EditEstimateFormSchema,
} from './EstimateForm.schema';
import EstimateFormHeader from './EstimateFormHeader';
import EditableItemsEntriesTable from 'containers/Entries/EditableItemsEntriesTable';
import EstimateFloatingActions from './EstimateFloatingActions';
import EstimateFormFooter from './EstimateFormFooter';
import EstimateNumberWatcher from './EstimateNumberWatcher';
import withEstimates from './withEstimates';
import withEstimateActions from './withEstimateActions'; import withEstimateActions from './withEstimateActions';
import withEstimateDetail from './withEstimateDetail'; import withEstimateDetail from './withEstimateDetail';
@@ -26,25 +26,44 @@ import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withMediaActions from 'containers/Media/withMediaActions'; import withMediaActions from 'containers/Media/withMediaActions';
import withSettings from 'containers/Settings/withSettings'; import withSettings from 'containers/Settings/withSettings';
import { AppToaster, Row, Col } from 'components'; import { AppToaster } from 'components';
import Dragzone from 'components/Dragzone'; import Dragzone from 'components/Dragzone';
import useMedia from 'hooks/useMedia'; import useMedia from 'hooks/useMedia';
import { ERROR } from 'common/errors'; import { ERROR } from 'common/errors';
import { compose, repeatValue } from 'utils'; import { compose, repeatValue, orderingLinesIndexes } from 'utils';
const MIN_LINES_NUMBER = 4; const MIN_LINES_NUMBER = 4;
const defaultEstimate = {
index: 0,
item_id: null,
rate: null,
discount: 0,
quantity: null,
description: '',
};
const defaultInitialValues = {
customer_id: '',
estimate_date: moment(new Date()).format('YYYY-MM-DD'),
expiration_date: moment(new Date()).format('YYYY-MM-DD'),
estimate_number: '',
reference: '',
note: '',
terms_conditions: '',
entries: [...repeatValue(defaultEstimate, MIN_LINES_NUMBER)],
};
/** /**
* Estimate form. * Estimate form.
*/ */
const EstimateForm = ({ const EstimateForm = ({
//#WithMedia // #WithMedia
requestSubmitMedia, requestSubmitMedia,
requestDeleteMedia, requestDeleteMedia,
//#WithEstimateActions // #WithEstimateActions
requestSubmitEstimate, requestSubmitEstimate,
requestEditEstimate, requestEditEstimate,
setEstimateNumberChanged, setEstimateNumberChanged,
@@ -69,27 +88,10 @@ const EstimateForm = ({
onCancelForm, onCancelForm,
}) => { }) => {
const { formatMessage } = useIntl(); const { formatMessage } = useIntl();
const [payload, setPayload] = useState({}); const history = useHistory();
const [submitPayload, setSubmitPayload] = useState({});
const { const isNewMode = !estimateId;
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 estimateNumber = estimateNumberPrefix const estimateNumber = estimateNumberPrefix
? `${estimateNumberPrefix}-${estimateNextNumber}` ? `${estimateNumberPrefix}-${estimateNextNumber}`
@@ -103,94 +105,15 @@ const EstimateForm = ({
changePageSubtitle(`No. ${estimateNumber}`); changePageSubtitle(`No. ${estimateNumber}`);
changePageTitle(formatMessage({ id: 'new_estimate' })); changePageTitle(formatMessage({ id: 'new_estimate' }));
} }
}, [changePageTitle, estimate, formatMessage]); }, [
estimate,
const validationSchema = Yup.object().shape({ estimateNumber,
customer_id: Yup.number() formatMessage,
.label(formatMessage({ id: 'customer_name_' })) changePageTitle,
.required(), changePageSubtitle,
estimate_date: Yup.date() ]);
.required()
.label(formatMessage({ id: 'estimate_date_' })),
expiration_date: Yup.date()
.required()
.label(formatMessage({ id: 'expiration_date_' })),
estimate_number: Yup.string()
.required()
.nullable()
.label(formatMessage({ id: 'estimate_number_' })),
reference: Yup.string().min(1).max(255),
note: 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 saveEstimateSubmit = useCallback(
(payload) => {
onFormSubmit && onFormSubmit(payload);
},
[onFormSubmit],
);
const defaultEstimate = useMemo(
() => ({
index: 0,
item_id: null,
rate: null,
discount: 0,
quantity: null,
description: '',
}),
[],
);
const defaultInitialValues = useMemo(
() => ({
customer_id: '',
estimate_date: moment(new Date()).format('YYYY-MM-DD'),
expiration_date: moment(new Date()).format('YYYY-MM-DD'),
estimate_number: estimateNumber,
reference: '',
note: '',
terms_conditions: '',
entries: [...repeatValue(defaultEstimate, MIN_LINES_NUMBER)],
}),
[defaultEstimate],
);
const orderingProductsIndex = (_entries) => {
return _entries.map((item, index) => ({
...item,
index: index + 1,
}));
};
// Initial values in create and edit mode.
const initialValues = useMemo( const initialValues = useMemo(
() => ({ () => ({
...(estimate ...(estimate
@@ -208,22 +131,14 @@ const EstimateForm = ({
} }
: { : {
...defaultInitialValues, ...defaultInitialValues,
entries: orderingProductsIndex(defaultInitialValues.entries), estimate_number: estimateNumber,
entries: orderingLinesIndexes(defaultInitialValues.entries),
}), }),
}), }),
[estimate, defaultInitialValues, defaultEstimate], [estimate, estimateNumber],
); );
const initialAttachmentFiles = useMemo(() => { // Transform response errors to fields.
return estimate && estimate.media
? estimate.media.map((attach) => ({
preview: attach.attachment_file,
uploaded: true,
metadata: { ...attach },
}))
: [];
}, [estimate]);
const handleErrors = (errors, { setErrors }) => { const handleErrors = (errors, { setErrors }) => {
if (errors.some((e) => e.type === ERROR.ESTIMATE_NUMBER_IS_NOT_UNQIUE)) { if (errors.some((e) => e.type === ERROR.ESTIMATE_NUMBER_IS_NOT_UNQIUE)) {
setErrors({ setErrors({
@@ -234,12 +149,11 @@ const EstimateForm = ({
} }
}; };
const formik = useFormik({ // Handles form submit.
validationSchema, const handleFormSubmit = (
initialValues: { values,
...initialValues, { setSubmitting, setErrors, resetForm },
}, ) => {
onSubmit: (values, { setSubmitting, setErrors, resetForm }) => {
const entries = values.entries.filter( const entries = values.entries.filter(
(item) => item.item_id && item.quantity, (item) => item.item_id && item.quantity,
); );
@@ -258,106 +172,41 @@ const EstimateForm = ({
} }
const form = { const form = {
...values, ...values,
entries, // Exclude all entries properties that out of request schema.
entries: entries.map((entry) => ({
...pick(entry, Object.keys(defaultEstimate)),
})),
}; };
const requestForm = { ...form }; const onSuccess = (response) => {
if (estimate && estimate.id) {
requestEditEstimate(estimate.id, requestForm)
.then((response) => {
AppToaster.show({ AppToaster.show({
message: formatMessage( message: formatMessage(
{ {
id: 'the_estimate_has_been_successfully_edited', id: isNewMode
? 'the_estimate_has_been_successfully_edited'
: 'the_estimate_has_been_successfully_created',
}, },
{ number: values.estimate_number }, { number: values.estimate_number },
), ),
intent: Intent.SUCCESS, intent: Intent.SUCCESS,
}); });
setSubmitting(false); setSubmitting(false);
saveEstimateSubmit({ action: 'update', ...payload });
resetForm(); resetForm();
})
.catch((errors) => { if (submitPayload.redirect) {
handleErrors(errors, { setErrors }); history.push('/estimates');
setSubmitting(false);
});
} else {
requestSubmitEstimate(requestForm)
.then((response) => {
AppToaster.show({
message: formatMessage(
{ id: 'the_estimate_has_been_successfully_created' },
{ number: values.estimate_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
resetForm();
saveEstimateSubmit({ action: 'new', ...payload });
})
.catch((errors) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
});
} }
},
});
useEffect(() => {
if (estimateNumberChanged) {
formik.setFieldValue('estimate_number', estimateNumber);
changePageSubtitle(`No. ${estimateNumber}`);
setEstimateNumberChanged(false);
}
}, [
estimateNumber,
estimateNumberChanged,
setEstimateNumberChanged,
formik.setFieldValue,
changePageSubtitle,
]);
const handleSubmitClick = useCallback(
(payload) => {
setPayload(payload);
formik.submitForm();
},
[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]);
}
});
},
[setDeletedFiles, deletedFiles],
);
const handleClickAddNewRow = () => {
formik.setFieldValue(
'entries',
orderingProductsIndex([...formik.values.entries, defaultEstimate]),
);
}; };
const handleClearAllLines = () => { const onError = (errors) => {
formik.setFieldValue( handleErrors(errors, { setErrors });
'entries', setSubmitting(false);
orderingProductsIndex([ };
...repeatValue(defaultEstimate, MIN_LINES_NUMBER),
]), if (estimate && estimate.id) {
); requestEditEstimate(estimate.id, form).then(onSuccess).catch(onError);
} else {
requestSubmitEstimate(form).then(onSuccess).catch(onError);
}
}; };
const handleEstimateNumberChange = useCallback( const handleEstimateNumberChange = useCallback(
@@ -367,62 +216,40 @@ const EstimateForm = ({
[changePageSubtitle], [changePageSubtitle],
); );
const handleSubmitClick = useCallback((event) => {
setSubmitPayload({ redirect: true });
}, [setSubmitPayload]);
const handleCancelClick = useCallback((event) => {
history.goBack();
}, [history]);
return ( return (
<div className={classNames(CLASSES.PAGE_FORM, CLASSES.PAGE_FORM_ESTIMATE)}> <div className={classNames(CLASSES.PAGE_FORM, CLASSES.PAGE_FORM_ESTIMATE)}>
<form onSubmit={formik.handleSubmit}> <Formik
validationSchema={
isNewMode ? CreateEstimateFormSchema : EditEstimateFormSchema
}
initialValues={initialValues}
onSubmit={handleFormSubmit}
>
{({ isSubmitting }) => (
<Form>
<EstimateFormHeader <EstimateFormHeader
onEstimateNumberChanged={handleEstimateNumberChange} onEstimateNumberChanged={handleEstimateNumberChange}
formik={formik}
/> />
<EntriesItemsTable <EstimateNumberWatcher estimateNumber={estimateNumber} />
entries={formik.values.entries} <EditableItemsEntriesTable />
onClickAddNewRow={handleClickAddNewRow} <EstimateFormFooter />
onClickClearAllLines={handleClearAllLines}
formik={formik}
/>
<div class={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Row>
<Col md={8}>
{/* --------- Customer Note --------- */}
<FormGroup
label={<T id={'customer_note'} />}
className={'form-group--customer_note'}
>
<TextArea
growVertically={true}
{...formik.getFieldProps('note')}
/>
</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>
<EstimateFloatingActions <EstimateFloatingActions
formik={formik} isSubmiting={isSubmitting}
estimateId={estimateId}
onSubmitClick={handleSubmitClick} onSubmitClick={handleSubmitClick}
estimate={estimate}
onCancelClick={handleCancelClick} onCancelClick={handleCancelClick}
/> />
</Form>
)}
</Formik>
</div> </div>
); );
}; };
@@ -436,7 +263,4 @@ export default compose(
estimateNextNumber: estimatesSettings?.nextNumber, estimateNextNumber: estimatesSettings?.nextNumber,
estimateNumberPrefix: estimatesSettings?.numberPrefix, estimateNumberPrefix: estimatesSettings?.numberPrefix,
})), })),
withEstimates(({ estimateNumberChanged }) => ({
estimateNumberChanged,
})),
)(EstimateForm); )(EstimateForm);

View File

@@ -0,0 +1,51 @@
import * as Yup from 'yup';
import { formatMessage } from 'services/intl';
const Schema = Yup.object().shape({
customer_id: Yup.number()
.label(formatMessage({ id: 'customer_name_' }))
.required(),
estimate_date: Yup.date()
.required()
.label(formatMessage({ id: 'estimate_date_' })),
expiration_date: Yup.date()
.required()
.label(formatMessage({ id: 'expiration_date_' })),
estimate_number: Yup.string()
.required()
.nullable()
.label(formatMessage({ id: 'estimate_number_' })),
reference: Yup.string().min(1).max(255),
note: 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(),
}),
),
});
export const CreateEstimateFormSchema = Schema;
export const EditEstimateFormSchema = Schema;

View File

@@ -0,0 +1,58 @@
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 { CLASSES } from 'common/classes';
import { Row, Col } from 'components';
import Dragzone from 'components/Dragzone';
import { inputIntent } from 'utils';
/**
* Estimate form footer.
*/
export default function EstiamteFormFooter({}) {
return (
<div class={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Row>
<Col md={8}>
{/* --------- Customer Note --------- */}
<FastField name={'note'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'customer_note'} />}
className={'form-group--customer_note'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup>
)}
</FastField>
{/* --------- Terms and conditions --------- */}
<FastField name={'terms_conditions'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'terms_conditions'} />}
className={'form-group--terms_conditions'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup>
)}
</FastField>
</Col>
<Col md={4}>
<Dragzone
initialFiles={[]}
// onDrop={handleDropFiles}
// onDeleteFile={handleDeleteFile}
hint={'Attachments: Maxiumum size: 20MB'}
/>
</Col>
</Row>
</div>
);
}

View File

@@ -1,22 +1,18 @@
import React, { useMemo, useCallback, useState } from 'react'; import React, { useCallback } from 'react';
import { import {
FormGroup, FormGroup,
InputGroup, InputGroup,
Intent,
Position, Position,
MenuItem,
Classes,
ControlGroup, ControlGroup,
} from '@blueprintjs/core'; } from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime'; import { DateInput } from '@blueprintjs/datetime';
import { FormattedMessage as T } from 'react-intl'; import { FormattedMessage as T } from 'react-intl';
import moment from 'moment'; import { FastField, ErrorMessage } from 'formik';
import { momentFormatter, compose, tansformDateValue, saveInvoke } from 'utils'; import { momentFormatter, compose, tansformDateValue, saveInvoke } from 'utils';
import classNames from 'classnames'; import classNames from 'classnames';
import { CLASSES } from 'common/classes'; import { CLASSES } from 'common/classes';
import { import {
ContactSelecetList, ContactSelecetList,
ErrorMessage,
FieldRequiredHint, FieldRequiredHint,
Icon, Icon,
InputPrependButton, InputPrependButton,
@@ -27,9 +23,10 @@ import {
import withCustomers from 'containers/Customers/withCustomers'; import withCustomers from 'containers/Customers/withCustomers';
import withDialogActions from 'containers/Dialog/withDialogActions'; import withDialogActions from 'containers/Dialog/withDialogActions';
function EstimateFormHeader({ import { inputIntent, handleDateChange } from 'utils';
formik: { errors, touched, setFieldValue, getFieldProps, values }, import { formatMessage } from 'services/intl';
function EstimateFormHeader({
//#withCustomers //#withCustomers
customers, customers,
// #withDialogActions // #withDialogActions
@@ -37,35 +34,6 @@ function EstimateFormHeader({
// #ownProps // #ownProps
onEstimateNumberChanged, onEstimateNumberChanged,
}) { }) {
const handleDateChange = useCallback(
(date_filed) => (date) => {
const formatted = moment(date).format('YYYY-MM-DD');
setFieldValue(date_filed, formatted);
},
[setFieldValue],
);
const CustomerRenderer = useCallback(
(cutomer, { handleClick }) => (
<MenuItem
key={cutomer.id}
text={cutomer.display_name}
onClick={handleClick}
/>
),
[],
);
// handle change customer
const onChangeCustomer = useCallback(
(filedName) => {
return (customer) => {
setFieldValue(filedName, customer.id);
};
},
[setFieldValue],
);
const handleEstimateNumberChange = useCallback(() => { const handleEstimateNumberChange = useCallback(() => {
openDialog('estimate-number-form', {}); openDialog('estimate-number-form', {});
}, [openDialog]); }, [openDialog]);
@@ -78,106 +46,104 @@ function EstimateFormHeader({
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}> <div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<div className={'page-form__primary-section'}> <div className={'page-form__primary-section'}>
{/* ----------- Customer name ----------- */} {/* ----------- Customer name ----------- */}
<FastField name={'customer_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'customer_name'} />} label={<T id={'customer_name'} />}
inline={true} inline={true}
className={classNames( className={classNames(
'form-group--select-list', CLASSES.FILL,
'form-group--customer', 'form-group--customer',
Classes.FILL,
)} )}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
intent={errors.customer_id && touched.customer_id && Intent.DANGER} intent={inputIntent({ error, touched })}
helperText={ helperText={<ErrorMessage name={'customer_id'} />}
<ErrorMessage name={'customer_id'} {...{ errors, touched }} />
}
> >
<ContactSelecetList <ContactSelecetList
contactsList={customers} contactsList={customers}
selectedContactId={values.customer_id} selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />} defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={onChangeCustomer('customer_id')} onContactSelected={(customer) => {
form.setFieldValue('customer_id', customer.id);
}}
/> />
</FormGroup> </FormGroup>
)}
</FastField>
<Row> <Row>
<Col md={8} className={'col--estimate-date'}> <Col md={8} className={'col--estimate-date'}>
{/* ----------- Estimate date ----------- */} {/* ----------- Estimate date ----------- */}
<FastField name={'estimate_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'estimate_date'} />} label={<T id={'estimate_date'} />}
inline={true} inline={true}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
className={classNames( className={classNames(
'form-group--select-list', CLASSES.FILL,
'form-group--estimate-date', 'form-group--estimate-date',
Classes.FILL,
)} )}
intent={ intent={inputIntent({ error, touched })}
errors.estimate_date && touched.estimate_date && Intent.DANGER helperText={<ErrorMessage name="estimate_date" />}
}
helperText={
<ErrorMessage name="estimate_date" {...{ errors, touched }} />
}
> >
<DateInput <DateInput
{...momentFormatter('YYYY/MM/DD')} {...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.estimate_date)} value={tansformDateValue(value)}
onChange={handleDateChange('estimate_date')} onChange={handleDateChange((formattedDate) => {
form.setFieldValue('estimate_date', formatMessage);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }} popoverProps={{ position: Position.BOTTOM, minimal: true }}
/> />
</FormGroup> </FormGroup>
)}
</FastField>
</Col> </Col>
<Col md={4} className={'col--expiration-date'}> <Col md={4} className={'col--expiration-date'}>
{/* ----------- Expiration date ----------- */} {/* ----------- Expiration date ----------- */}
<FastField name={'expiration_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'expiration_date'} />} label={<T id={'expiration_date'} />}
inline={true} inline={true}
className={classNames( className={classNames(
'form-group--select-list', CLASSES.FORM_GROUP_LIST_SELECT,
CLASSES.FILL,
'form-group--expiration-date', 'form-group--expiration-date',
Classes.FILL,
)} )}
intent={ intent={inputIntent({ error, touched })}
errors.expiration_date && helperText={<ErrorMessage name="expiration_date" />}
touched.expiration_date &&
Intent.DANGER
}
helperText={
<ErrorMessage name="expiration_date" {...{ errors, touched }} />
}
> >
<DateInput <DateInput
{...momentFormatter('YYYY/MM/DD')} {...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.expiration_date)} value={tansformDateValue(value)}
onChange={handleDateChange('expiration_date')} onChange={handleDateChange((formattedDate) => {
form.setFieldValue('expiration_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }} popoverProps={{ position: Position.BOTTOM, minimal: true }}
/> />
</FormGroup> </FormGroup>
)}
</FastField>
</Col> </Col>
</Row> </Row>
{/* ----------- Estimate number ----------- */} {/* ----------- Estimate number ----------- */}
<FastField name={'estimate_number'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'estimate'} />} label={<T id={'estimate'} />}
inline={true} inline={true}
className={('form-group--estimate-number', Classes.FILL)} className={('form-group--estimate-number', CLASSES.FILL)}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
intent={ intent={inputIntent({ error, touched })}
errors.estimate_number && touched.estimate_number && Intent.DANGER helperText={<ErrorMessage name="estimate_number" />}
}
helperText={
<ErrorMessage name="estimate_number" {...{ errors, touched }} />
}
> >
<ControlGroup fill={true}> <ControlGroup fill={true}>
<InputGroup <InputGroup
intent={
errors.estimate_number &&
touched.estimate_number &&
Intent.DANGER
}
minimal={true} minimal={true}
{...getFieldProps('estimate_number')} {...field}
onBlur={handleEstimateNumberChanged} onBlur={handleEstimateNumberChanged}
/> />
<InputPrependButton <InputPrependButton
@@ -193,23 +159,23 @@ function EstimateFormHeader({
/> />
</ControlGroup> </ControlGroup>
</FormGroup> </FormGroup>
)}
</FastField>
{/* ----------- Reference ----------- */} {/* ----------- Reference ----------- */}
<FastField name={'reference'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'reference'} />} label={<T id={'reference'} />}
inline={true} inline={true}
className={classNames('form-group--reference', Classes.FILL)} className={classNames('form-group--reference', CLASSES.FILL)}
intent={errors.reference && touched.reference && Intent.DANGER} intent={inputIntent({ error, touched })}
helperText={ helperText={<ErrorMessage name="reference" />}
<ErrorMessage name="reference" {...{ errors, touched }} />
}
> >
<InputGroup <InputGroup minimal={true} {...field} />
intent={errors.reference && touched.reference && Intent.DANGER}
minimal={true}
{...getFieldProps('reference')}
/>
</FormGroup> </FormGroup>
)}
</FastField>
</div> </div>
</div> </div>
); );

View File

@@ -0,0 +1,46 @@
import { useEffect } from 'react';
import { useFormikContext } from 'formik';
import withEstimates from './withEstimates';
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withEstimateActions from './withEstimateActions';
import { compose } from 'utils';
function EstimateNumberWatcher({
estimateNumberChanged,
// #WithEstimateActions
setEstimateNumberChanged,
// #withDashboardActions
changePageSubtitle,
// #ownProps
estimateNumber,
}) {
const { setFieldValue } = useFormikContext();
useEffect(() => {
if (estimateNumberChanged) {
setFieldValue('estimate_number', estimateNumber);
changePageSubtitle(`No. ${estimateNumber}`);
setEstimateNumberChanged(false);
}
}, [
estimateNumber,
estimateNumberChanged,
setEstimateNumberChanged,
setFieldValue,
changePageSubtitle,
]);
return null;
}
export default compose(
withEstimates(({ estimateNumberChanged }) => ({
estimateNumberChanged,
})),
withEstimateActions,
withDashboardActions
)(EstimateNumberWatcher)

View File

@@ -1,50 +1,56 @@
import React from 'react'; import React from 'react';
import { Intent, Button } from '@blueprintjs/core'; import { Intent, Button } from '@blueprintjs/core';
import { useFormikContext } from 'formik';
import { FormattedMessage as T } from 'react-intl'; import { FormattedMessage as T } from 'react-intl';
import { CLASSES } from 'common/classes';
import classNames from 'classnames';
import { saveInvoke } from 'utils';
export default function InvoiceFloatingActions({ export default function InvoiceFloatingActions({
formik: { isSubmitting }, isSubmitting,
onSubmitClick, onSubmitClick,
onSubmitAndNewClick,
onCancelClick, onCancelClick,
onClearClick,
invoice, invoice,
}) { }) {
const { resetForm } = useFormikContext();
return ( return (
<div className={'form__floating-footer'}> <div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
<Button <Button
disabled={isSubmitting} disabled={isSubmitting}
intent={Intent.PRIMARY} intent={Intent.PRIMARY}
type="submit" type="submit"
onClick={() => { onClick={(event) => {
onSubmitClick({ redirect: true }); saveInvoke(onSubmitClick, event);
}} }}
> >
{invoice && invoice.id ? <T id={'edit'} /> : <T id={'save_send'} />} {invoice && invoice.id ? <T id={'edit'} /> : <T id={'save'} />}
</Button> </Button>
<Button <Button
disabled={isSubmitting} disabled={isSubmitting}
intent={Intent.PRIMARY} intent={Intent.PRIMARY}
className={'ml1'} className={'ml1'}
name={'save'}
type="submit" type="submit"
onClick={() => { onClick={(event) => {
onSubmitClick({ redirect: false }); saveInvoke(onSubmitAndNewClick, event);
}} }}
> >
<T id={'save'} /> <T id={'save_new'} />
</Button> </Button>
<Button className={'ml1'} disabled={isSubmitting}> <Button className={'ml1'} disabled={isSubmitting} onClick={(event) => {
resetForm();
saveInvoke(onClearClick, event);
}}>
<T id={'clear'} /> <T id={'clear'} />
</Button> </Button>
<Button <Button className={'ml1'} type="submit" onClick={(event) => {
className={'ml1'} saveInvoke(onCancelClick, event);
type="submit" }}>
onClick={() => {
onCancelClick && onCancelClick();
}}
>
<T id={'close'} /> <T id={'close'} />
</Button> </Button>
</div> </div>

View File

@@ -1,24 +1,23 @@
import React, { import React, { useState, useMemo, useCallback, useEffect } from 'react';
useMemo, import { Formik, Form } from 'formik';
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import moment from 'moment'; import moment from 'moment';
import { Intent, FormGroup, TextArea } from '@blueprintjs/core'; import { Intent } from '@blueprintjs/core';
import { FormattedMessage as T, useIntl } from 'react-intl'; import { useIntl } from 'react-intl';
import { pick, sumBy } from 'lodash'; import { pick, sumBy, omit } from 'lodash';
import classNames from 'classnames'; import classNames from 'classnames';
import { CLASSES } from 'common/classes'; import { CLASSES } from 'common/classes';
import InvoiceFormHeader from './InvoiceFormHeader'; import {
import EntriesItemsTable from 'containers/Sales/Estimate/EntriesItemsTable'; CreateInvoiceFormSchema,
import InvoiceFloatingActions from './InvoiceFloatingActions'; 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 withInvoiceActions from './withInvoiceActions';
import withInvoiceDetail from './withInvoiceDetail'; import withInvoiceDetail from './withInvoiceDetail';
@@ -26,19 +25,40 @@ import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withMediaActions from 'containers/Media/withMediaActions'; import withMediaActions from 'containers/Media/withMediaActions';
import withSettings from 'containers/Settings/withSettings'; import withSettings from 'containers/Settings/withSettings';
import { AppToaster, Col, Row } from 'components'; import { AppToaster } from 'components';
import Dragzone from 'components/Dragzone';
import useMedia from 'hooks/useMedia'; import useMedia from 'hooks/useMedia';
import { ERROR } from 'common/errors'; 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 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. * Invoice form.
*/ */
function InvoiceForm({ function InvoiceForm({
// #WithMedia // #WithMedia
requestSubmitMedia, requestSubmitMedia,
@@ -47,7 +67,6 @@ function InvoiceForm({
// #WithInvoiceActions // #WithInvoiceActions
requestSubmitInvoice, requestSubmitInvoice,
requestEditInvoice, requestEditInvoice,
setInvoiceNumberChanged,
// #withDashboard // #withDashboard
changePageTitle, changePageTitle,
@@ -60,36 +79,15 @@ function InvoiceForm({
// #withInvoiceDetail // #withInvoiceDetail
invoice, invoice,
// #withInvoices
invoiceNumberChanged,
// #own Props // #own Props
invoiceId, invoiceId,
onFormSubmit,
onCancelForm, onCancelForm,
}) { }) {
const { formatMessage } = useIntl(); const { formatMessage } = useIntl();
const [payload, setPayload] = useState({}); const history = useHistory();
const { const [submitPayload, setSubmitPayload] = useState({});
setFiles, const isNewMode = !invoiceId;
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 invoiceNumber = invoiceNumberPrefix const invoiceNumber = invoiceNumberPrefix
? `${invoiceNumberPrefix}-${invoiceNextNumber}` ? `${invoiceNumberPrefix}-${invoiceNextNumber}`
@@ -103,93 +101,13 @@ function InvoiceForm({
changePageSubtitle(`No. ${invoiceNumber}`); changePageSubtitle(`No. ${invoiceNumber}`);
changePageTitle(formatMessage({ id: 'new_invoice' })); changePageTitle(formatMessage({ id: 'new_invoice' }));
} }
}, [changePageTitle, changePageSubtitle, invoice, formatMessage]); }, [
changePageTitle,
const validationSchema = Yup.object().shape({ changePageSubtitle,
customer_id: Yup.string() invoice,
.label(formatMessage({ id: 'customer_name_' })) invoiceNumber,
.required(), formatMessage,
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,
}));
};
const initialValues = useMemo( const initialValues = useMemo(
() => ({ () => ({
@@ -208,38 +126,24 @@ function InvoiceForm({
} }
: { : {
...defaultInitialValues, ...defaultInitialValues,
entries: orderingIndex(defaultInitialValues.entries), invoice_no: invoiceNumber,
entries: orderingLinesIndexes(defaultInitialValues.entries),
}), }),
}), }),
[invoice, defaultInitialValues, defaultInvoice], [invoice, invoiceNumber],
); );
const initialAttachmentFiles = useMemo(() => { // Handle form errors.
return invoice && invoice.media
? invoice.media.map((attach) => ({
preview: attach.attachment_file,
uploaded: true,
metadata: { ...attach },
}))
: [];
}, [invoice]);
const handleErrors = (errors, { setErrors }) => { const handleErrors = (errors, { setErrors }) => {
if (errors.some((e) => e.type === ERROR.SALE_INVOICE_NUMBER_IS_EXISTS)) { if (errors.some((e) => e.type === ERROR.SALE_INVOICE_NUMBER_IS_EXISTS)) {
setErrors({ setErrors({
invoice_no: formatMessage({ invoice_no: formatMessage({ id: 'sale_invoice_number_is_exists' }),
id: 'sale_invoice_number_is_exists',
}),
}); });
} }
}; };
const formik = useFormik({ // Handles form submit.
validationSchema, const handleSubmit = (values, { setSubmitting, setErrors, resetForm }) => {
initialValues: {
...initialValues,
},
onSubmit: (values, { setSubmitting, setErrors, resetForm }) => {
setSubmitting(true); setSubmitting(true);
const entries = values.entries.filter( const entries = values.entries.filter(
@@ -247,11 +151,10 @@ function InvoiceForm({
); );
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity)); const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
// Throw danger toaster in case total quantity equals zero.
if (totalQuantity === 0) { if (totalQuantity === 0) {
AppToaster.show({ AppToaster.show({
message: formatMessage({ message: formatMessage({ id: 'quantity_cannot_be_zero_or_empty' }),
id: 'quantity_cannot_be_zero_or_empty',
}),
intent: Intent.DANGER, intent: Intent.DANGER,
}); });
setSubmitting(false); setSubmitting(false);
@@ -259,103 +162,57 @@ function InvoiceForm({
} }
const form = { const form = {
...values, ...values,
entries, entries: entries.map((entry) => ({ ...omit(entry, ['total']) })),
}; };
// Handle the request success.
const requestForm = { ...form }; const onSuccess = () => {
if (invoice && invoice.id) {
requestEditInvoice(invoice.id, requestForm)
.then((response) => {
AppToaster.show({ AppToaster.show({
message: formatMessage( message: formatMessage(
{ {
id: 'the_invoice_has_been_successfully_edited', id: isNewMode
? 'the_invocie_has_been_successfully_created'
: 'the_invoice_has_been_successfully_edited',
}, },
{ number: values.invoice_no }, { number: values.invoice_no },
), ),
intent: Intent.SUCCESS, intent: Intent.SUCCESS,
}); });
setSubmitting(false); setSubmitting(false);
saveInvokeSubmit({ action: 'update', ...payload });
resetForm(); 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);
}
}, [
invoiceNumber,
invoiceNumberChanged,
formik.setFieldValue,
changePageSubtitle,
]);
const handleSubmitClick = useCallback( if (submitPayload.redirect) {
(payload) => { history.push('/invoices');
setPayload(payload); }
formik.submitForm(); };
}, // Handle the request error.
[setPayload, formik], 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( const handleCancelClick = useCallback(
(payload) => { (payload) => {
onCancelForm && onCancelForm(payload); history.goBack();
}, },
[onCancelForm], [history],
); );
const handleDeleteFile = useCallback( const handleSubmitClick = useCallback(() => {
(_deletedFiles) => { setSubmitPayload({ redirect: true });
_deletedFiles.forEach((deletedFile) => { }, [setSubmitPayload]);
if (deletedFile.uploaded && deletedFile.metadata.id) {
setDeletedFiles([...deletedFiles, deletedFile.metadata.id]);
}
});
},
[setDeletedFiles, deletedFiles],
);
const handleClickAddNewRow = () => { const handleSubmitAndNewClick = useCallback(() => {
formik.setFieldValue( setSubmitPayload({ redirect: false });
'entries', }, [setSubmitPayload]);
orderingIndex([...formik.values.entries, defaultInvoice]),
);
};
const handleClearAllLines = () => {
formik.setFieldValue(
'entries',
orderingIndex([...repeatValue(defaultInvoice, MIN_LINES_NUMBER)]),
);
};
const handleInvoiceNumberChanged = useCallback( const handleInvoiceNumberChanged = useCallback(
(invoiceNumber) => { (invoiceNumber) => {
@@ -366,62 +223,31 @@ function InvoiceForm({
return ( return (
<div className={classNames(CLASSES.PAGE_FORM, CLASSES.PAGE_FORM_INVOICE)}> <div className={classNames(CLASSES.PAGE_FORM, CLASSES.PAGE_FORM_INVOICE)}>
<form onSubmit={formik.handleSubmit}> <Formik
validationSchema={
isNewMode ? CreateInvoiceFormSchema : EditInvoiceFormSchema
}
initialValues={initialValues}
onSubmit={handleSubmit}
>
{({ isSubmitting }) => (
<Form>
<InvoiceFormHeader <InvoiceFormHeader
onInvoiceNumberChanged={handleInvoiceNumberChanged} onInvoiceNumberChanged={handleInvoiceNumberChanged}
formik={formik}
/> />
<EntriesItemsTable <InvoiceNumberChangeWatcher invoiceNumber={invoiceNumber} />
entries={formik.values.entries} <EditableItemsEntriesTable defaultEntry={defaultInvoice} />
onClickAddNewRow={handleClickAddNewRow} <InvoiceFormFooter />
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 <InvoiceFloatingActions
formik={formik} isSubmitting={isSubmitting}
onSubmitClick={handleSubmitClick}
invoice={invoice} invoice={invoice}
onCancelClick={handleCancelClick} onCancelClick={handleCancelClick}
onSubmitClick={handleSubmitClick}
onSubmitAndNewClick={handleSubmitAndNewClick}
/> />
</Form>
)}
</Formik>
</div> </div>
); );
} }
@@ -436,5 +262,4 @@ export default compose(
invoiceNextNumber: invoiceSettings?.nextNumber, invoiceNextNumber: invoiceSettings?.nextNumber,
invoiceNumberPrefix: invoiceSettings?.numberPrefix, invoiceNumberPrefix: invoiceSettings?.numberPrefix,
})), })),
withInvoices(({ invoiceNumberChanged }) => ({ invoiceNumberChanged })),
)(InvoiceForm); )(InvoiceForm);

View File

@@ -0,0 +1,49 @@
import * as Yup from 'yup';
import { formatMessage } from 'services/intl';
const Schema = 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(),
}),
),
});
export const CreateInvoiceFormSchema = Schema;
export const EditInvoiceFormSchema = Schema;

View File

@@ -0,0 +1,55 @@
import React from 'react';
import { FastField } from 'formik';
import classNames from 'classnames';
import { FormGroup, TextArea } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
import { CLASSES } from 'common/classes';
import { Row, Col } from 'components';
import Dragzone from 'components/Dragzone';
import { inputIntent } from 'utils';
export default function InvoiceFormFooter() {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Row>
<Col md={8}>
{/* --------- Invoice message --------- */}
<FastField name={'invoice_message'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'invoice_message'} />}
className={'form-group--invoice_message'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup>
)}
</FastField>
{/* --------- Terms and conditions --------- */}
<FastField name={'terms_conditions'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'terms_conditions'} />}
className={'form-group--terms_conditions'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup>
)}
</FastField>
</Col>
<Col md={4}>
<Dragzone
initialFiles={[]}
// onDrop={handleDropFiles}
// onDeleteFile={handleDeleteFile}
hint={'Attachments: Maxiumum size: 20MB'}
/>
</Col>
</Row>
</div>
);
}

View File

@@ -1,12 +1,12 @@
import React, { useMemo, useCallback, useState } from 'react'; import React, { useCallback } from 'react';
import { import {
FormGroup, FormGroup,
InputGroup, InputGroup,
Intent,
Position, Position,
ControlGroup, ControlGroup,
} from '@blueprintjs/core'; } from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime'; import { DateInput } from '@blueprintjs/datetime';
import { FastField, ErrorMessage } from 'formik';
import { FormattedMessage as T } from 'react-intl'; import { FormattedMessage as T } from 'react-intl';
import moment from 'moment'; import moment from 'moment';
import { momentFormatter, compose, tansformDateValue, saveInvoke } from 'utils'; import { momentFormatter, compose, tansformDateValue, saveInvoke } from 'utils';
@@ -14,7 +14,6 @@ import classNames from 'classnames';
import { CLASSES } from 'common/classes'; import { CLASSES } from 'common/classes';
import { import {
ContactSelecetList, ContactSelecetList,
ErrorMessage,
FieldRequiredHint, FieldRequiredHint,
Icon, Icon,
InputPrependButton, InputPrependButton,
@@ -25,9 +24,9 @@ import {
import withCustomers from 'containers/Customers/withCustomers'; import withCustomers from 'containers/Customers/withCustomers';
import withDialogActions from 'containers/Dialog/withDialogActions'; import withDialogActions from 'containers/Dialog/withDialogActions';
function InvoiceFormHeader({ import { inputIntent, handleDateChange } from 'utils';
formik: { errors, touched, setFieldValue, getFieldProps, values },
function InvoiceFormHeader({
//#withCustomers //#withCustomers
customers, customers,
//#withDialogActions //#withDialogActions
@@ -36,24 +35,6 @@ function InvoiceFormHeader({
// #ownProps // #ownProps
onInvoiceNumberChanged, onInvoiceNumberChanged,
}) { }) {
const handleDateChange = useCallback(
(date_filed) => (date) => {
const formatted = moment(date).format('YYYY-MM-DD');
setFieldValue(date_filed, formatted);
},
[setFieldValue],
);
// handle change customer
const onChangeCustomer = useCallback(
(filedName) => {
return (customer) => {
setFieldValue(filedName, customer.id);
};
},
[setFieldValue],
);
const handleInvoiceNumberChange = useCallback(() => { const handleInvoiceNumberChange = useCallback(() => {
openDialog('invoice-number-form', {}); openDialog('invoice-number-form', {});
}, [openDialog]); }, [openDialog]);
@@ -66,96 +47,102 @@ function InvoiceFormHeader({
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}> <div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}> <div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}>
{/* ----------- Customer name ----------- */} {/* ----------- Customer name ----------- */}
<FastField name={'customer_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'customer_name'} />} label={<T id={'customer_name'} />}
inline={true} inline={true}
className={classNames( className={classNames(
'form-group--select-list',
'form-group--customer-name', 'form-group--customer-name',
CLASSES.FILL, CLASSES.FILL,
)} )}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
intent={errors.customer_id && touched.customer_id && Intent.DANGER} intent={inputIntent({ error, touched })}
helperText={ helperText={<ErrorMessage name={'customer_id'} />}
<ErrorMessage name={'customer_id'} {...{ errors, touched }} />
}
> >
<ContactSelecetList <ContactSelecetList
contactsList={customers} contactsList={customers}
selectedContactId={values.customer_id} selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />} defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={onChangeCustomer('customer_id')} onContactSelected={(customer) => {
form.setFieldValue('customer_id', customer.id);
}}
/> />
</FormGroup> </FormGroup>
)}
</FastField>
<Row> <Row>
<Col md={7} className={'col--invoice-date'}> <Col md={7} className={'col--invoice-date'}>
{/* ----------- Invoice date ----------- */} {/* ----------- Invoice date ----------- */}
<FastField name={'invoice_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'invoice_date'} />} label={<T id={'invoice_date'} />}
inline={true} inline={true}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
className={classNames( className={classNames(
'form-group--select-list',
'form-group--invoice-date', 'form-group--invoice-date',
CLASSES.FILL, CLASSES.FILL,
)} )}
intent={ intent={inputIntent({ error, touched })}
errors.invoice_date && touched.invoice_date && Intent.DANGER helperText={<ErrorMessage name="invoice_date" />}
}
helperText={
<ErrorMessage name="invoice_date" {...{ errors, touched }} />
}
> >
<DateInput <DateInput
{...momentFormatter('YYYY/MM/DD')} {...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.invoice_date)} value={tansformDateValue(value)}
onChange={handleDateChange('invoice_date')} onChange={handleDateChange((formattedDate) => {
form.setFieldValue('invoice_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }} popoverProps={{ position: Position.BOTTOM, minimal: true }}
/> />
</FormGroup> </FormGroup>
)}
</FastField>
</Col> </Col>
<Col md={5} className={'col--due-date'}> <Col md={5} className={'col--due-date'}>
{/* ----------- Due date ----------- */} {/* ----------- Due date ----------- */}
<FastField name={'due_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'due_date'} />} label={<T id={'due_date'} />}
inline={true} inline={true}
className={classNames( className={classNames(
'form-group--select-list',
'form-group--due-date', 'form-group--due-date',
CLASSES.FILL, CLASSES.FILL,
)} )}
intent={errors.due_date && touched.due_date && Intent.DANGER} intent={inputIntent({ error, touched })}
helperText={ helperText={<ErrorMessage name="due_date" />}
<ErrorMessage name="due_date" {...{ errors, touched }} />
}
> >
<DateInput <DateInput
{...momentFormatter('YYYY/MM/DD')} {...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.due_date)} value={tansformDateValue(value)}
onChange={handleDateChange('due_date')} onChange={handleDateChange((formattedDate) => {
form.setFieldValue('due_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }} popoverProps={{ position: Position.BOTTOM, minimal: true }}
/> />
</FormGroup> </FormGroup>
)}
</FastField>
</Col> </Col>
</Row> </Row>
{/* ----------- Invoice number ----------- */} {/* ----------- Invoice number ----------- */}
<FastField name={'invoice_no'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'invoice_no'} />} label={<T id={'invoice_no'} />}
inline={true} inline={true}
className={classNames('form-group--invoice-no', CLASSES.FILL)} className={classNames('form-group--invoice-no', CLASSES.FILL)}
intent={errors.invoice_no && touched.invoice_no && Intent.DANGER} intent={inputIntent({ error, touched })}
helperText={ helperText={<ErrorMessage name="invoice_no" />}
<ErrorMessage name="invoice_no" {...{ errors, touched }} />
}
> >
<ControlGroup fill={true}> <ControlGroup fill={true}>
<InputGroup <InputGroup
intent={errors.invoice_no && touched.invoice_no && Intent.DANGER}
minimal={true} minimal={true}
{...getFieldProps('invoice_no')} {...field}
onBlur={handleInvoiceNumberChanged} onBlur={handleInvoiceNumberChanged}
/> />
<InputPrependButton <InputPrependButton
@@ -171,25 +158,23 @@ function InvoiceFormHeader({
/> />
</ControlGroup> </ControlGroup>
</FormGroup> </FormGroup>
)}
</FastField>
{/* ----------- Reference ----------- */} {/* ----------- Reference ----------- */}
<FastField name={'reference'}>
{({ field, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'reference'} />} label={<T id={'reference'} />}
inline={true} inline={true}
className={classNames('form-group--reference', CLASSES.FILL)} className={classNames('form-group--reference', CLASSES.FILL)}
intent={errors.reference_no && touched.reference_no && Intent.DANGER} intent={inputIntent({ error, touched })}
helperText={ helperText={<ErrorMessage name="reference" />}
<ErrorMessage name="reference" {...{ errors, touched }} />
}
> >
<InputGroup <InputGroup minimal={true} {...field} />
intent={
errors.reference_no && touched.reference_no && Intent.DANGER
}
minimal={true}
{...getFieldProps('reference_no')}
/>
</FormGroup> </FormGroup>
)}
</FastField>
</div> </div>
</div> </div>
); );

View File

@@ -0,0 +1,44 @@
import { useEffect } from 'react';
import { useFormikContext } from 'formik';
import withInvoices from './withInvoices';
import withInvoiceActions from './withInvoiceActions';
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import { compose } from 'utils';
function InvoiceNumberChangeWatcher({
invoiceNumber,
// #WithInvoiceActions
setInvoiceNumberChanged,
// #withInvoices
invoiceNumberChanged,
// #withDashboardActions
changePageSubtitle,
}) {
const { setFieldValue } = useFormikContext();
useEffect(() => {
if (invoiceNumberChanged) {
setFieldValue('invoice_no', invoiceNumber);
changePageSubtitle(`No. ${invoiceNumber}`);
setInvoiceNumberChanged(false);
}
}, [
invoiceNumber,
invoiceNumberChanged,
setFieldValue,
changePageSubtitle,
setInvoiceNumberChanged,
]);
return null;
}
export default compose(
withInvoices(({ invoiceNumberChanged }) => ({ invoiceNumberChanged })),
withInvoiceActions,
withDashboardActions,
)(InvoiceNumberChangeWatcher);

View File

@@ -1,27 +1,26 @@
import React, { import React, { useMemo, useCallback, useEffect, useState } from 'react';
useMemo, import { Formik, Form } from 'formik';
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import moment from 'moment'; import moment from 'moment';
import { Intent, FormGroup, TextArea, ControlGroup } from '@blueprintjs/core'; import { Intent } from '@blueprintjs/core';
import { FormattedMessage as T, useIntl } from 'react-intl'; import { FormattedMessage as T, useIntl } from 'react-intl';
import { pick, sumBy } from 'lodash'; import { pick, sumBy } from 'lodash';
import classNames from 'classnames'; import classNames from 'classnames';
import { useHistory } from 'react-router-dom';
import { CLASSES } from 'common/classes'; import { CLASSES } from 'common/classes';
import { ERROR } from 'common/errors'; import { ERROR } from 'common/errors';
import ReceiptFromHeader from './ReceiptFormHeader'; import {
import EntriesItemsTable from 'containers/Sales/Estimate/EntriesItemsTable'; EditReceiptFormSchema,
import ReceiptReceiveFloatingActions from './ReceiptReceiveFloatingActions'; CreateReceiptFormSchema,
} from './ReceiptForm.schema';
import ReceiptFromHeader from './ReceiptFormHeader';
import EditableItemsEntriesTable from 'containers/Entries/EditableItemsEntriesTable';
import ReceiptFormFloatingActions from './ReceiptFormFloatingActions';
import ReceiptFormFooter from './ReceiptFormFooter';
import ReceiptNumberWatcher from './ReceiptNumberWatcher';
import withReceipts from './withReceipts';
import withReceiptActions from './withReceiptActions'; import withReceiptActions from './withReceiptActions';
import withReceiptDetail from './withReceiptDetail'; import withReceiptDetail from './withReceiptDetail';
@@ -29,14 +28,34 @@ import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withMediaActions from 'containers/Media/withMediaActions'; import withMediaActions from 'containers/Media/withMediaActions';
import withSettings from 'containers/Settings/withSettings'; import withSettings from 'containers/Settings/withSettings';
import { AppToaster, Row, Col } from 'components'; import { AppToaster } from 'components';
import Dragzone from 'components/Dragzone'; import Dragzone from 'components/Dragzone';
import useMedia from 'hooks/useMedia'; import useMedia from 'hooks/useMedia';
import { compose, repeatValue } from 'utils'; import { compose, repeatValue, orderingLinesIndexes } from 'utils';
const MIN_LINES_NUMBER = 4; const MIN_LINES_NUMBER = 4;
const defaultReceipt = {
index: 0,
item_id: null,
rate: null,
discount: 0,
quantity: null,
description: '',
};
const defaultInitialValues = {
customer_id: '',
deposit_account_id: '',
receipt_number: '',
receipt_date: moment(new Date()).format('YYYY-MM-DD'),
reference_no: '',
receipt_message: '',
statement: '',
entries: [...repeatValue(defaultReceipt, MIN_LINES_NUMBER)],
};
/** /**
* Receipt form. * Receipt form.
*/ */
@@ -49,7 +68,6 @@ function ReceiptForm({
//#withReceiptActions //#withReceiptActions
requestSubmitReceipt, requestSubmitReceipt,
requestEditReceipt, requestEditReceipt,
setReceiptNumberChanged,
//#withReceiptDetail //#withReceiptDetail
receipt, receipt,
@@ -62,36 +80,16 @@ function ReceiptForm({
receiptNextNumber, receiptNextNumber,
receiptNumberPrefix, receiptNumberPrefix,
// #withReceipts
receiptNumberChanged,
//#own Props //#own Props
receiptId, receiptId,
onFormSubmit, onFormSubmit,
onCancelForm, onCancelForm,
}) { }) {
const { formatMessage } = useIntl(); const { formatMessage } = useIntl();
const [payload, setPayload] = useState({}); const history = useHistory();
const { const [submitPayload, setSubmitPayload ] = useState({});
setFiles, const isNewMode = !receiptId;
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 receiptNumber = receiptNumberPrefix const receiptNumber = receiptNumberPrefix
? `${receiptNumberPrefix}-${receiptNextNumber}` ? `${receiptNumberPrefix}-${receiptNextNumber}`
@@ -105,93 +103,15 @@ function ReceiptForm({
changePageSubtitle(`No. ${receiptNumber}`); changePageSubtitle(`No. ${receiptNumber}`);
changePageTitle(formatMessage({ id: 'new_receipt' })); changePageTitle(formatMessage({ id: 'new_receipt' }));
} }
}, [changePageTitle, changePageSubtitle, receipt, formatMessage]); }, [
changePageTitle,
const validationSchema = Yup.object().shape({ changePageSubtitle,
customer_id: Yup.string() receipt,
.label(formatMessage({ id: 'customer_name_' })) receiptNumber,
.required(), formatMessage,
receipt_date: Yup.date() ]);
.required()
.label(formatMessage({ id: 'receipt_date_' })),
receipt_number: Yup.string()
.required()
.label(formatMessage({ id: 'receipt_no_' })),
deposit_account_id: Yup.number()
.required()
.label(formatMessage({ id: 'deposit_account_' })),
reference_no: Yup.string().min(1).max(255),
receipt_message: Yup.string()
.trim()
.min(1)
.max(1024)
.label(formatMessage({ id: 'receipt_message_' })),
statement: 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 defaultReceipt = useMemo(
() => ({
index: 0,
item_id: null,
rate: null,
discount: 0,
quantity: null,
description: '',
}),
[],
);
const defaultInitialValues = useMemo(
() => ({
customer_id: '',
deposit_account_id: '',
receipt_number: receiptNumber,
receipt_date: moment(new Date()).format('YYYY-MM-DD'),
reference_no: '',
receipt_message: '',
statement: '',
entries: [...repeatValue(defaultReceipt, MIN_LINES_NUMBER)],
}),
[defaultReceipt],
);
const orderingIndex = (_receipt) => {
return _receipt.map((item, index) => ({
...item,
index: index + 1,
}));
};
// Initial values in create and edit mode.
const initialValues = useMemo( const initialValues = useMemo(
() => ({ () => ({
...(receipt ...(receipt
@@ -209,22 +129,14 @@ function ReceiptForm({
} }
: { : {
...defaultInitialValues, ...defaultInitialValues,
entries: orderingIndex(defaultInitialValues.entries), receipt_number: receiptNumber,
entries: orderingLinesIndexes(defaultInitialValues.entries),
}), }),
}), }),
[receipt, defaultInitialValues, defaultReceipt], [receipt],
); );
const initialAttachmentFiles = useMemo(() => { // Transform response error to fields.
return receipt && receipt.media
? receipt.media.map((attach) => ({
preview: attach.attachment_file,
uploaded: true,
metadata: { ...attach },
}))
: [];
}, [receipt]);
const handleErrors = (errors, { setErrors }) => { const handleErrors = (errors, { setErrors }) => {
if (errors.some((e) => e.type === ERROR.SALE_RECEIPT_NUMBER_NOT_UNIQUE)) { if (errors.some((e) => e.type === ERROR.SALE_RECEIPT_NUMBER_NOT_UNIQUE)) {
setErrors({ setErrors({
@@ -234,12 +146,12 @@ function ReceiptForm({
}); });
} }
}; };
const formik = useFormik({
validationSchema, // Handle the form submit.
initialValues: { const handleFormSubmit = (
...initialValues, values,
}, { setErrors, setSubmitting, resetForm },
onSubmit: (values, { setErrors, setSubmitting, resetForm }) => { ) => {
const entries = values.entries.filter( const entries = values.entries.filter(
(item) => item.item_id && item.quantity, (item) => item.item_id && item.quantity,
); );
@@ -258,106 +170,43 @@ function ReceiptForm({
} }
const form = { const form = {
...values, ...values,
entries, entries: entries.map((entry) => ({
// Exclude all properties that out of request entries schema.
...pick(entry, Object.keys(defaultReceipt)),
})),
};
// Handle the request success.
const onSuccess = (response) => {
AppToaster.show({
message: formatMessage(
{
id: isNewMode
? 'the_receipt_has_been_successfully_created'
: 'the_receipt_has_been_successfully_edited',
},
{ number: values.receipt_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
resetForm();
if (submitPayload.redirect) {
history.push('/receipts');
}
}; };
const requestForm = { ...form }; // Handle the request error.
const onError = (errors) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
};
if (receipt && receipt.id) { if (receipt && receipt.id) {
requestEditReceipt(receipt.id, requestForm) requestEditReceipt(receipt.id, form).then(onSuccess).catch(onError);
.then(() => {
AppToaster.show({
message: formatMessage(
{
id: 'the_receipt_has_been_successfully_edited',
},
{ number: values.receipt_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
saveInvokeSubmit({ action: 'update', ...payload });
resetForm();
})
.catch((errors) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
});
} else { } else {
requestSubmitReceipt(requestForm) requestSubmitReceipt(form).then(onSuccess).catch(onError);
.then((response) => {
AppToaster.show({
message: formatMessage(
{
id: 'the_receipt_has_been_successfully_created',
},
{ number: values.receipt_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
saveInvokeSubmit({ action: 'new', ...payload });
resetForm();
})
.catch((errors) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
});
} }
},
});
useEffect(() => {
if (receiptNumberChanged) {
formik.setFieldValue('receipt_number', receiptNumber);
changePageSubtitle(`No. ${receiptNumber}`);
setReceiptNumberChanged(false);
}
}, [
receiptNumber,
receiptNumberChanged,
formik.setFieldValue,
changePageSubtitle,
]);
const handleDeleteFile = useCallback(
(_deletedFiles) => {
_deletedFiles.forEach((deletedFile) => {
if (deletedFile.uploaded && deletedFile.metadata.id) {
setDeletedFiles([...deletedFiles, deletedFile.metadata.id]);
}
});
},
[setDeletedFiles, deletedFiles],
);
const handleSubmitClick = useCallback(
(payload) => {
setPayload(payload);
formik.submitForm();
},
[setPayload, formik],
);
const handleCancelClick = useCallback(
(payload) => {
onCancelForm && onCancelForm(payload);
},
[onCancelForm],
);
const handleClickAddNewRow = () => {
formik.setFieldValue(
'entries',
orderingIndex([...formik.values.entries, defaultReceipt]),
);
};
const handleClearAllLines = () => {
formik.setFieldValue(
'entries',
orderingIndex([...repeatValue(defaultReceipt, MIN_LINES_NUMBER)]),
);
}; };
const handleReceiptNumberChanged = useCallback( const handleReceiptNumberChanged = useCallback(
@@ -367,64 +216,42 @@ function ReceiptForm({
[changePageSubtitle], [changePageSubtitle],
); );
const handleSubmitClick = (event) => {
setSubmitPayload({ redirect: true });
};
const handleSubmitAndNewClick = (event) => {
setSubmitPayload({ redirect: false });
};
const handleCancelClick = (event) => {
history.goBack();
};
return ( return (
<div className={classNames(CLASSES.PAGE_FORM_RECEIPT, CLASSES.PAGE_FORM)}> <div className={classNames(CLASSES.PAGE_FORM_RECEIPT, CLASSES.PAGE_FORM)}>
<form onSubmit={formik.handleSubmit}> <Formik
validationSchema={
isNewMode ? CreateReceiptFormSchema : EditReceiptFormSchema
}
initialValues={initialValues}
onSubmit={handleFormSubmit}
>
<Form>
<ReceiptFromHeader <ReceiptFromHeader
onReceiptNumberChanged={handleReceiptNumberChanged} onReceiptNumberChanged={handleReceiptNumberChanged}
formik={formik}
/> />
<ReceiptNumberWatcher receiptNumber={receiptNumber} />
<EntriesItemsTable <EditableItemsEntriesTable />
entries={formik.values.entries} <ReceiptFormFooter />
onClickAddNewRow={handleClickAddNewRow} <ReceiptFormFloatingActions
onClickClearAllLines={handleClearAllLines} receiptId={receiptId}
formik={formik}
/>
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Row>
<Col md={8}>
{/* --------- Receipt message --------- */}
<FormGroup
label={<T id={'receipt_message'} />}
className={'form-group--receipt_message'}
>
<TextArea
growVertically={true}
{...formik.getFieldProps('receipt_message')}
/>
</FormGroup>
{/* --------- Statement--------- */}
<FormGroup
label={<T id={'statement'} />}
className={'form-group--statement'}
>
<TextArea
growVertically={true}
{...formik.getFieldProps('statement')}
/>
</FormGroup>
</Col>
<Col md={4}>
<Dragzone
initialFiles={initialAttachmentFiles}
onDrop={handleDropFiles}
onDeleteFile={handleDeleteFile}
hint={'Attachments: Maxiumum size: 20MB'}
/>
</Col>
</Row>
</div>
</form>
<ReceiptReceiveFloatingActions
formik={formik}
onSubmitClick={handleSubmitClick} onSubmitClick={handleSubmitClick}
receipt={receipt} onSubmitAndNewClick={handleSubmitAndNewClick}
onCancelForm={handleCancelClick} onCancelForm={handleCancelClick}
/> />
</Form>
</Formik>
</div> </div>
); );
} }
@@ -438,5 +265,4 @@ export default compose(
receiptNextNumber: receiptSettings?.nextNumber, receiptNextNumber: receiptSettings?.nextNumber,
receiptNumberPrefix: receiptSettings?.numberPrefix, receiptNumberPrefix: receiptSettings?.numberPrefix,
})), })),
withReceipts(({ receiptNumberChanged }) => ({ receiptNumberChanged })),
)(ReceiptForm); )(ReceiptForm);

View File

@@ -0,0 +1,55 @@
import * as Yup from 'yup';
import { formatMessage } from 'services/intl';
const Schema = Yup.object().shape({
customer_id: Yup.string()
.label(formatMessage({ id: 'customer_name_' }))
.required(),
receipt_date: Yup.date()
.required()
.label(formatMessage({ id: 'receipt_date_' })),
receipt_number: Yup.string()
.required()
.label(formatMessage({ id: 'receipt_no_' })),
deposit_account_id: Yup.number()
.required()
.label(formatMessage({ id: 'deposit_account_' })),
reference_no: Yup.string().min(1).max(255),
receipt_message: Yup.string()
.trim()
.min(1)
.max(1024)
.label(formatMessage({ id: 'receipt_message_' })),
statement: 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 CreateReceiptFormSchema = Schema;
const EditReceiptFormSchema = Schema;
export {
CreateReceiptFormSchema,
EditReceiptFormSchema
};

View File

@@ -0,0 +1,63 @@
import React from 'react';
import { Intent, Button } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
import { useFormikContext } from 'formik';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import { saveInvoke } from 'utils';
export default function ReceiptFormFloatingActions({
isSubmitting,
receiptId,
onSubmitClick,
onCancelClick,
onClearClick,
onSubmitAndNewClick,
}) {
const { resetForm } = useFormikContext();
return (
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
type="submit"
onClick={(event) => {
saveInvoke(onSubmitClick, event);
}}
>
{receiptId ? <T id={'edit'} /> : <T id={'save'} />}
</Button>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
className={'ml1'}
name={'save'}
type="submit"
onClick={(event) => {
saveInvoke(onSubmitAndNewClick, event);
}}
>
<T id={'save_new'} />
</Button>
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={(event) => {
resetForm();
saveInvoke(onClearClick, event);
}}
>
<T id={'clear'} />
</Button>
<Button className={'ml1'} onClick={(event) => {
saveInvoke(onCancelClick, event);
}}>
<T id={'close'} />
</Button>
</div>
);
}

View File

@@ -0,0 +1,53 @@
import React from 'react';
import { FormGroup, TextArea } from '@blueprintjs/core';
import { FastField } from 'formik';
import classNames from 'classnames';
import { FormattedMessage as T } from 'react-intl';
import { Dragzone, Row, Col } from 'components';
import { CLASSES } from 'common/classes';
import { inputIntent } from 'utils';
export default function ReceiptFormFooter({}) {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Row>
<Col md={8}>
{/* --------- Receipt message --------- */}
<FastField name={'receipt_message'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'receipt_message'} />}
className={'form-group--receipt_message'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup>
)}
</FastField>
{/* --------- Statement--------- */}
<FastField name={'statement'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'statement'} />}
className={'form-group--statement'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup>
)}
</FastField>
</Col>
<Col md={4}>
<Dragzone
initialFiles={[]}
// onDrop={handleDropFiles}
// onDeleteFile={handleDeleteFile}
hint={'Attachments: Maxiumum size: 20MB'}
/>
</Col>
</Row>
</div>
);
}

View File

@@ -1,22 +1,20 @@
import React, { useMemo, useCallback, useState } from 'react'; import React, { useCallback } from 'react';
import { import {
FormGroup, FormGroup,
InputGroup, InputGroup,
Intent,
Position, Position,
ControlGroup, ControlGroup,
} from '@blueprintjs/core'; } from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime'; import { DateInput } from '@blueprintjs/datetime';
import { FormattedMessage as T } from 'react-intl'; import { FormattedMessage as T } from 'react-intl';
import moment from 'moment';
import { momentFormatter, compose, tansformDateValue, saveInvoke } from 'utils';
import classNames from 'classnames'; import classNames from 'classnames';
import { FastField, ErrorMessage } from 'formik';
import { CLASSES } from 'common/classes'; import { CLASSES } from 'common/classes';
import { import {
AccountsSelectList, AccountsSelectList,
ContactSelecetList, ContactSelecetList,
ErrorMessage,
FieldRequiredHint, FieldRequiredHint,
Icon, Icon,
InputPrependButton, InputPrependButton,
@@ -26,9 +24,17 @@ import withCustomers from 'containers/Customers/withCustomers';
import withAccounts from 'containers/Accounts/withAccounts'; import withAccounts from 'containers/Accounts/withAccounts';
import withDialogActions from 'containers/Dialog/withDialogActions'; import withDialogActions from 'containers/Dialog/withDialogActions';
function ReceiptFormHeader({ import {
formik: { errors, touched, setFieldValue, getFieldProps, values }, momentFormatter,
compose,
tansformDateValue,
saveInvoke,
handleDateChange,
inputIntent,
} from 'utils';
function ReceiptFormHeader({
//#withCustomers //#withCustomers
customers, customers,
@@ -41,30 +47,6 @@ function ReceiptFormHeader({
// #ownProps // #ownProps
onReceiptNumberChanged, onReceiptNumberChanged,
}) { }) {
const handleDateChange = useCallback(
(date) => {
const formatted = moment(date).format('YYYY-MM-DD');
setFieldValue('receipt_date', formatted);
},
[setFieldValue],
);
// handle change
const onChangeSelect = useCallback(
(filedName) => {
return (item) => {
setFieldValue(filedName, item.id);
};
},
[setFieldValue],
);
// Filter deposit accounts.
const depositAccounts = useMemo(
() => accountsList.filter((a) => a?.type?.key === 'current_asset'),
[accountsList],
);
const handleReceiptNumberChange = useCallback(() => { const handleReceiptNumberChange = useCallback(() => {
openDialog('receipt-number-form', {}); openDialog('receipt-number-form', {});
}, [openDialog]); }, [openDialog]);
@@ -77,95 +59,92 @@ function ReceiptFormHeader({
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}> <div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}> <div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}>
{/* ----------- Customer name ----------- */} {/* ----------- Customer name ----------- */}
<FastField name={'customer_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'customer_name'} />} label={<T id={'customer_name'} />}
inline={true} inline={true}
className={classNames( className={classNames(CLASSES.FILL, 'form-group--customer')}
'form-group--select-list',
CLASSES.FILL,
'form-group--customer',
)}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
intent={errors.customer_id && touched.customer_id && Intent.DANGER} intent={inputIntent({ error, touched })}
helperText={ helperText={<ErrorMessage name={'customer_id'} />}
<ErrorMessage name={'customer_id'} {...{ errors, touched }} />
}
> >
<ContactSelecetList <ContactSelecetList
contactsList={customers} contactsList={customers}
selectedContactId={values.customer_id} selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />} defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={onChangeSelect('customer_id')} onContactSelected={(contact) => {
form.setFieldValue('customer_id', contact.id);
}}
/> />
</FormGroup> </FormGroup>
)}
</FastField>
{/* ----------- Deposit account ----------- */} {/* ----------- Deposit account ----------- */}
<FastField name={'deposit_account_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'deposit_account'} />} label={<T id={'deposit_account'} />}
className={classNames( className={classNames(
'form-group--deposit-account', 'form-group--deposit-account',
'form-group--select-list',
CLASSES.FILL, CLASSES.FILL,
)} )}
inline={true} inline={true}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
intent={ intent={inputIntent({ error, touched })}
errors.deposit_account_id && helperText={<ErrorMessage name={'deposit_account_id'} />}
touched.deposit_account_id &&
Intent.DANGER
}
helperText={
<ErrorMessage
name={'deposit_account_id'}
{...{ errors, touched }}
/>
}
> >
<AccountsSelectList <AccountsSelectList
accounts={depositAccounts} accounts={accountsList}
onAccountSelected={onChangeSelect('deposit_account_id')} onAccountSelected={(account) => {
form.setFieldValue('deposit_account_id', account.id);
}}
defaultSelectText={<T id={'select_deposit_account'} />} defaultSelectText={<T id={'select_deposit_account'} />}
selectedAccountId={values.deposit_account_id} selectedAccountId={value}
filterByTypes={['current_asset']}
/> />
</FormGroup> </FormGroup>
)}
</FastField>
{/* ----------- Receipt date ----------- */} {/* ----------- Receipt date ----------- */}
<FastField name={'receipt_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'receipt_date'} />} label={<T id={'receipt_date'} />}
inline={true} inline={true}
className={classNames('form-group--select-list', CLASSES.FILL)} className={classNames(CLASSES.FILL)}
intent={errors.receipt_date && touched.receipt_date && Intent.DANGER} intent={inputIntent({ error, touched })}
helperText={ helperText={<ErrorMessage name="receipt_date" />}
<ErrorMessage name="receipt_date" {...{ errors, touched }} />
}
> >
<DateInput <DateInput
{...momentFormatter('YYYY/MM/DD')} {...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.receipt_date)} value={tansformDateValue(value)}
onChange={handleDateChange} onChange={handleDateChange((formattedDate) => {
form.setFieldValue('receipt_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }} popoverProps={{ position: Position.BOTTOM, minimal: true }}
/> />
</FormGroup> </FormGroup>
)}
</FastField>
{/* ----------- Receipt number ----------- */} {/* ----------- Receipt number ----------- */}
<FastField name={'receipt_number'}>
{({ field, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'receipt'} />} label={<T id={'receipt'} />}
inline={true} inline={true}
className={('form-group--receipt_number', CLASSES.FILL)} className={('form-group--receipt_number', CLASSES.FILL)}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
intent={ intent={inputIntent({ error, touched })}
errors.receipt_number && touched.receipt_number && Intent.DANGER helperText={<ErrorMessage name="receipt_number" />}
}
helperText={
<ErrorMessage name="receipt_number" {...{ errors, touched }} />
}
> >
<ControlGroup fill={true}> <ControlGroup fill={true}>
<InputGroup <InputGroup
intent={
errors.receipt_number && touched.receipt_number && Intent.DANGER
}
minimal={true} minimal={true}
{...getFieldProps('receipt_number')} {...field}
onBlur={handleReceiptNumberChanged} onBlur={handleReceiptNumberChanged}
/> />
<InputPrependButton <InputPrependButton
@@ -181,25 +160,23 @@ function ReceiptFormHeader({
/> />
</ControlGroup> </ControlGroup>
</FormGroup> </FormGroup>
)}
</FastField>
{/* ----------- Reference ----------- */} {/* ----------- Reference ----------- */}
<FastField name={'reference'}>
{({ field, meta: { error, touched } }) => (
<FormGroup <FormGroup
label={<T id={'reference'} />} label={<T id={'reference'} />}
inline={true} inline={true}
className={classNames('form-group--reference', CLASSES.FILL)} className={classNames('form-group--reference', CLASSES.FILL)}
intent={errors.reference_no && touched.reference_no && Intent.DANGER} intent={inputIntent({ error, touched })}
helperText={ helperText={<ErrorMessage name="reference" />}
<ErrorMessage name="reference" {...{ errors, touched }} />
}
> >
<InputGroup <InputGroup minimal={true} {...field} />
intent={
errors.reference_no && touched.reference_no && Intent.DANGER
}
minimal={true}
{...getFieldProps('reference_no')}
/>
</FormGroup> </FormGroup>
)}
</FastField>
</div> </div>
</div> </div>
); );

View File

@@ -0,0 +1,45 @@
import { useEffect } from 'react';
import { useFormikContext } from 'formik';
import withDashboardActions from "containers/Dashboard/withDashboardActions";
import withReceipts from './withReceipts';
import withReceiptActions from './withReceiptActions';
import { compose } from 'utils';
function ReceiptNumberWatcher({
receiptNumber,
// #withDashboardActions
changePageSubtitle,
// #withReceipts
receiptNumberChanged,
//#withReceiptActions
setReceiptNumberChanged,
}) {
const { setFieldValue } = useFormikContext();
useEffect(() => {
if (receiptNumberChanged) {
setFieldValue('receipt_number', receiptNumber);
changePageSubtitle(`No. ${receiptNumber}`);
setReceiptNumberChanged(false);
}
}, [
receiptNumber,
receiptNumberChanged,
setReceiptNumberChanged,
setFieldValue,
changePageSubtitle,
]);
return null
}
export default compose(
withReceipts(({ receiptNumberChanged }) => ({ receiptNumberChanged })),
withReceiptActions,
withDashboardActions
)(ReceiptNumberWatcher);

View File

@@ -1,52 +0,0 @@
import React from 'react';
import { Intent, Button } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
export default function ReceiptReceiveFloatingActions({
formik: { isSubmitting },
onSubmitClick,
onCancelClick,
receipt,
}) {
return (
<div className={'form__floating-footer'}>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
type="submit"
onClick={() => {
onSubmitClick({ redirect: true });
}}
>
{receipt && receipt.id ? <T id={'edit'} /> : <T id={'save_send'} />}
</Button>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
className={'ml1'}
name={'save'}
type="submit"
onClick={() => {
onSubmitClick({ redirect: false });
}}
>
<T id={'save'} />
</Button>
<Button className={'ml1'} disabled={isSubmitting}>
<T id={'clear'} />
</Button>
<Button
className={'ml1'}
type="submit"
onClick={() => {
onCancelClick && onCancelClick();
}}
>
<T id={'close'} />
</Button>
</div>
);
}

View File

@@ -0,0 +1,24 @@
import { createIntl, createIntlCache } from 'react-intl';
import messages from 'lang/en';
import { setLocale } from 'yup';
import {locale} from 'lang/en/locale';
// This is optional but highly recommended
// since it prevents memory leak
const cache = createIntlCache()
const intl = createIntl({
locale: 'en',
messages,
}, cache);
setLocale(locale)
const { formatMessage } = intl;
export {
formatMessage,
};
export default intl;

View File

@@ -120,7 +120,7 @@ body.authentication {
} }
} }
.select-list--fill-button { .bp3-fill{
.bp3-popover-wrapper, .bp3-popover-wrapper,
.bp3-popover-target { .bp3-popover-target {
display: block; display: block;

View File

@@ -74,6 +74,10 @@ export const handleNumberChange = (handler) => {
return handleStringChange((value) => handler(+value)); return handleStringChange((value) => handler(+value));
}; };
export const handleDateChange = (handler) => {
return (date) => handler(moment(date).format('YYYY-MM-DD'), date);
};
export const objectKeysTransform = (obj, transform) => { export const objectKeysTransform = (obj, transform) => {
return Object.keys(obj).reduce((acc, key) => { return Object.keys(obj).reduce((acc, key) => {
const computedKey = transform(key); const computedKey = transform(key);