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.insertSpaces": 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 { Select } from '@blueprintjs/select';
import { FormattedMessage as T } from 'react-intl';
import classNames from 'classnames';
import { isEmpty } from 'lodash';
export default function AccountsSelectList({
@@ -103,6 +104,7 @@ export default function AccountsSelectList({
filterable={true}
onItemSelect={onAccountSelect}
disabled={disabled}
className={classNames('form-group--select-list')}
>
<Button
disabled={disabled}

View File

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

View File

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

View File

@@ -35,6 +35,7 @@ import CurrencySelectList from './CurrencySelectList'
import SalutationList from './SalutationList';
import DisplayNameList from './DisplayNameList';
import MoneyInputGroup from './MoneyInputGroup';
import Dragzone from './Dragzone';
const Hint = FieldHint;
@@ -77,4 +78,5 @@ export {
DisplayNameList,
SalutationList,
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 { Intent, Button } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
import { saveInvoke } from 'utils';
export default function BillFloatingActions({
formik: { isSubmitting },
isSubmitting,
onSubmitClick,
onSubmitAndNewClick,
onCancelClick,
bill,
onClearClick,
billId,
}) {
return (
<div className={'form__floating-footer'}>
@@ -15,11 +18,11 @@ export default function BillFloatingActions({
loading={isSubmitting}
intent={Intent.PRIMARY}
type="submit"
onClick={() => {
onSubmitClick({ redirect: true });
onClick={(event) => {
saveInvoke(onSubmitClick, event);
}}
>
{bill && bill.id ? <T id={'edit'} /> : <T id={'save_send'} />}
{billId ? <T id={'edit'} /> : <T id={'save'} />}
</Button>
<Button
@@ -27,24 +30,29 @@ export default function BillFloatingActions({
loading={isSubmitting}
intent={Intent.PRIMARY}
className={'ml1'}
name={'save'}
type="submit"
onClick={() => {
onSubmitClick({ redirect: false });
onClick={(event) => {
saveInvoke(onSubmitAndNewClick, event);
}}
>
<T id={'save'} />
<T id={'save_new'} />
</Button>
<Button className={'ml1'} disabled={isSubmitting}>
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={(event) => {
saveInvoke(onClearClick, event);
}}
>
<T id={'clear'} />
</Button>
<Button
className={'ml1'}
type="submit"
onClick={() => {
onCancelClick && onCancelClick();
onClick={(event) => {
saveInvoke(onCancelClick, event);
}}
>
<T id={'close'} />

View File

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

View File

@@ -0,0 +1,51 @@
import * as Yup from 'yup';
import { formatMessage } from 'services/intl';
const BillFormSchema = Yup.object().shape({
vendor_id: Yup.number()
.required()
.label(formatMessage({ id: 'vendor_name_' })),
bill_date: Yup.date()
.required()
.label(formatMessage({ id: 'bill_date_' })),
due_date: Yup.date()
.required()
.label(formatMessage({ id: 'due_date_' })),
bill_number: Yup.string()
.required()
.label(formatMessage({ id: 'bill_number_' })),
reference_no: Yup.string().nullable().min(1).max(255),
note: Yup.string()
.trim()
.min(1)
.max(1024)
.label(formatMessage({ id: 'note' })),
entries: Yup.array().of(
Yup.object().shape({
quantity: Yup.number()
.nullable()
.when(['rate'], {
is: (rate) => rate,
then: Yup.number().required(),
}),
rate: Yup.number().nullable(),
item_id: Yup.number()
.nullable()
.when(['quantity', 'rate'], {
is: (quantity, rate) => quantity || rate,
then: Yup.number().required(),
}),
total: Yup.number().nullable(),
discount: Yup.number().nullable().min(0).max(100),
description: Yup.string().nullable(),
}),
),
});
const CreateBillFormSchema = BillFormSchema;
const EditBillFormSchema = BillFormSchema;
export {
CreateBillFormSchema,
EditBillFormSchema,
};

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,24 +1,24 @@
import React, {
useMemo,
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import React, { useMemo, useCallback, useEffect, useState } from 'react';
import { Formik, Form } from 'formik';
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 { pick, sumBy } from 'lodash';
import classNames from 'classnames';
import { useHistory } from 'react-router-dom';
import { CLASSES } from 'common/classes';
import EstimateFormHeader from './EstimateFormHeader';
import EntriesItemsTable from './EntriesItemsTable';
import EstimateFloatingActions from './EstimateFloatingActions';
import {
CreateEstimateFormSchema,
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 withEstimateDetail from './withEstimateDetail';
@@ -26,25 +26,44 @@ import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withMediaActions from 'containers/Media/withMediaActions';
import withSettings from 'containers/Settings/withSettings';
import { AppToaster, Row, Col } from 'components';
import { AppToaster } from 'components';
import Dragzone from 'components/Dragzone';
import useMedia from 'hooks/useMedia';
import { ERROR } from 'common/errors';
import { compose, repeatValue } from 'utils';
import { compose, repeatValue, orderingLinesIndexes } from 'utils';
const MIN_LINES_NUMBER = 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.
*/
const EstimateForm = ({
//#WithMedia
// #WithMedia
requestSubmitMedia,
requestDeleteMedia,
//#WithEstimateActions
// #WithEstimateActions
requestSubmitEstimate,
requestEditEstimate,
setEstimateNumberChanged,
@@ -69,27 +88,10 @@ const EstimateForm = ({
onCancelForm,
}) => {
const { formatMessage } = useIntl();
const [payload, setPayload] = useState({});
const history = useHistory();
const [submitPayload, setSubmitPayload] = useState({});
const {
setFiles,
saveMedia,
deletedFiles,
setDeletedFiles,
deleteMedia,
} = useMedia({
saveCallback: requestSubmitMedia,
deleteCallback: requestDeleteMedia,
});
const handleDropFiles = useCallback((_files) => {
setFiles(_files.filter((file) => file.uploaded === false));
}, []);
const savedMediaIds = useRef([]);
const clearSavedMediaIds = () => {
savedMediaIds.current = [];
};
const isNewMode = !estimateId;
const estimateNumber = estimateNumberPrefix
? `${estimateNumberPrefix}-${estimateNextNumber}`
@@ -103,94 +105,15 @@ const EstimateForm = ({
changePageSubtitle(`No. ${estimateNumber}`);
changePageTitle(formatMessage({ id: 'new_estimate' }));
}
}, [changePageTitle, estimate, formatMessage]);
const validationSchema = 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(),
}),
),
});
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,
}));
};
}, [
estimate,
estimateNumber,
formatMessage,
changePageTitle,
changePageSubtitle,
]);
// Initial values in create and edit mode.
const initialValues = useMemo(
() => ({
...(estimate
@@ -208,22 +131,14 @@ const EstimateForm = ({
}
: {
...defaultInitialValues,
entries: orderingProductsIndex(defaultInitialValues.entries),
estimate_number: estimateNumber,
entries: orderingLinesIndexes(defaultInitialValues.entries),
}),
}),
[estimate, defaultInitialValues, defaultEstimate],
[estimate, estimateNumber],
);
const initialAttachmentFiles = useMemo(() => {
return estimate && estimate.media
? estimate.media.map((attach) => ({
preview: attach.attachment_file,
uploaded: true,
metadata: { ...attach },
}))
: [];
}, [estimate]);
// Transform response errors to fields.
const handleErrors = (errors, { setErrors }) => {
if (errors.some((e) => e.type === ERROR.ESTIMATE_NUMBER_IS_NOT_UNQIUE)) {
setErrors({
@@ -234,130 +149,64 @@ const EstimateForm = ({
}
};
const formik = useFormik({
validationSchema,
initialValues: {
...initialValues,
},
onSubmit: (values, { setSubmitting, setErrors, resetForm }) => {
const entries = values.entries.filter(
(item) => item.item_id && item.quantity,
);
// Handles form submit.
const handleFormSubmit = (
values,
{ setSubmitting, setErrors, resetForm },
) => {
const entries = values.entries.filter(
(item) => item.item_id && item.quantity,
);
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
if (totalQuantity === 0) {
AppToaster.show({
message: formatMessage({
id: 'quantity_cannot_be_zero_or_empty',
}),
intent: Intent.DANGER,
});
setSubmitting(false);
return;
}
const form = {
...values,
entries,
};
const requestForm = { ...form };
if (estimate && estimate.id) {
requestEditEstimate(estimate.id, requestForm)
.then((response) => {
AppToaster.show({
message: formatMessage(
{
id: 'the_estimate_has_been_successfully_edited',
},
{ number: values.estimate_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
saveEstimateSubmit({ action: 'update', ...payload });
resetForm();
})
.catch((errors) => {
handleErrors(errors, { setErrors });
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]);
}
if (totalQuantity === 0) {
AppToaster.show({
message: formatMessage({
id: 'quantity_cannot_be_zero_or_empty',
}),
intent: Intent.DANGER,
});
},
[setDeletedFiles, deletedFiles],
);
setSubmitting(false);
return;
}
const form = {
...values,
// Exclude all entries properties that out of request schema.
entries: entries.map((entry) => ({
...pick(entry, Object.keys(defaultEstimate)),
})),
};
const onSuccess = (response) => {
AppToaster.show({
message: formatMessage(
{
id: isNewMode
? 'the_estimate_has_been_successfully_edited'
: 'the_estimate_has_been_successfully_created',
},
{ number: values.estimate_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
resetForm();
const handleClickAddNewRow = () => {
formik.setFieldValue(
'entries',
orderingProductsIndex([...formik.values.entries, defaultEstimate]),
);
};
if (submitPayload.redirect) {
history.push('/estimates');
}
};
const handleClearAllLines = () => {
formik.setFieldValue(
'entries',
orderingProductsIndex([
...repeatValue(defaultEstimate, MIN_LINES_NUMBER),
]),
);
const onError = (errors) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
};
if (estimate && estimate.id) {
requestEditEstimate(estimate.id, form).then(onSuccess).catch(onError);
} else {
requestSubmitEstimate(form).then(onSuccess).catch(onError);
}
};
const handleEstimateNumberChange = useCallback(
@@ -367,62 +216,40 @@ const EstimateForm = ({
[changePageSubtitle],
);
const handleSubmitClick = useCallback((event) => {
setSubmitPayload({ redirect: true });
}, [setSubmitPayload]);
const handleCancelClick = useCallback((event) => {
history.goBack();
}, [history]);
return (
<div className={classNames(CLASSES.PAGE_FORM, CLASSES.PAGE_FORM_ESTIMATE)}>
<form onSubmit={formik.handleSubmit}>
<EstimateFormHeader
onEstimateNumberChanged={handleEstimateNumberChange}
formik={formik}
/>
<EntriesItemsTable
entries={formik.values.entries}
onClickAddNewRow={handleClickAddNewRow}
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
formik={formik}
onSubmitClick={handleSubmitClick}
estimate={estimate}
onCancelClick={handleCancelClick}
/>
<Formik
validationSchema={
isNewMode ? CreateEstimateFormSchema : EditEstimateFormSchema
}
initialValues={initialValues}
onSubmit={handleFormSubmit}
>
{({ isSubmitting }) => (
<Form>
<EstimateFormHeader
onEstimateNumberChanged={handleEstimateNumberChange}
/>
<EstimateNumberWatcher estimateNumber={estimateNumber} />
<EditableItemsEntriesTable />
<EstimateFormFooter />
<EstimateFloatingActions
isSubmiting={isSubmitting}
estimateId={estimateId}
onSubmitClick={handleSubmitClick}
onCancelClick={handleCancelClick}
/>
</Form>
)}
</Formik>
</div>
);
};
@@ -436,7 +263,4 @@ export default compose(
estimateNextNumber: estimatesSettings?.nextNumber,
estimateNumberPrefix: estimatesSettings?.numberPrefix,
})),
withEstimates(({ estimateNumberChanged }) => ({
estimateNumberChanged,
})),
)(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 {
FormGroup,
InputGroup,
Intent,
Position,
MenuItem,
Classes,
ControlGroup,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FormattedMessage as T } from 'react-intl';
import moment from 'moment';
import { FastField, ErrorMessage } from 'formik';
import { momentFormatter, compose, tansformDateValue, saveInvoke } from 'utils';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import {
ContactSelecetList,
ErrorMessage,
FieldRequiredHint,
Icon,
InputPrependButton,
@@ -27,9 +23,10 @@ import {
import withCustomers from 'containers/Customers/withCustomers';
import withDialogActions from 'containers/Dialog/withDialogActions';
function EstimateFormHeader({
formik: { errors, touched, setFieldValue, getFieldProps, values },
import { inputIntent, handleDateChange } from 'utils';
import { formatMessage } from 'services/intl';
function EstimateFormHeader({
//#withCustomers
customers,
// #withDialogActions
@@ -37,35 +34,6 @@ function EstimateFormHeader({
// #ownProps
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(() => {
openDialog('estimate-number-form', {});
}, [openDialog]);
@@ -78,138 +46,136 @@ function EstimateFormHeader({
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<div className={'page-form__primary-section'}>
{/* ----------- Customer name ----------- */}
<FormGroup
label={<T id={'customer_name'} />}
inline={true}
className={classNames(
'form-group--select-list',
'form-group--customer',
Classes.FILL,
<FastField name={'customer_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'customer_name'} />}
inline={true}
className={classNames(
CLASSES.FILL,
'form-group--customer',
)}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'customer_id'} />}
>
<ContactSelecetList
contactsList={customers}
selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={(customer) => {
form.setFieldValue('customer_id', customer.id);
}}
/>
</FormGroup>
)}
labelInfo={<FieldRequiredHint />}
intent={errors.customer_id && touched.customer_id && Intent.DANGER}
helperText={
<ErrorMessage name={'customer_id'} {...{ errors, touched }} />
}
>
<ContactSelecetList
contactsList={customers}
selectedContactId={values.customer_id}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={onChangeCustomer('customer_id')}
/>
</FormGroup>
</FastField>
<Row>
<Col md={8} className={'col--estimate-date'}>
{/* ----------- Estimate date ----------- */}
<FormGroup
label={<T id={'estimate_date'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
className={classNames(
'form-group--select-list',
'form-group--estimate-date',
Classes.FILL,
<FastField name={'estimate_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'estimate_date'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
className={classNames(
CLASSES.FILL,
'form-group--estimate-date',
)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="estimate_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('estimate_date', formatMessage);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
)}
intent={
errors.estimate_date && touched.estimate_date && Intent.DANGER
}
helperText={
<ErrorMessage name="estimate_date" {...{ errors, touched }} />
}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.estimate_date)}
onChange={handleDateChange('estimate_date')}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
</FastField>
</Col>
<Col md={4} className={'col--expiration-date'}>
{/* ----------- Expiration date ----------- */}
<FormGroup
label={<T id={'expiration_date'} />}
inline={true}
className={classNames(
'form-group--select-list',
'form-group--expiration-date',
Classes.FILL,
<FastField name={'expiration_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'expiration_date'} />}
inline={true}
className={classNames(
CLASSES.FORM_GROUP_LIST_SELECT,
CLASSES.FILL,
'form-group--expiration-date',
)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="expiration_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('expiration_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
)}
intent={
errors.expiration_date &&
touched.expiration_date &&
Intent.DANGER
}
helperText={
<ErrorMessage name="expiration_date" {...{ errors, touched }} />
}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.expiration_date)}
onChange={handleDateChange('expiration_date')}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
</FastField>
</Col>
</Row>
{/* ----------- Estimate number ----------- */}
<FormGroup
label={<T id={'estimate'} />}
inline={true}
className={('form-group--estimate-number', Classes.FILL)}
labelInfo={<FieldRequiredHint />}
intent={
errors.estimate_number && touched.estimate_number && Intent.DANGER
}
helperText={
<ErrorMessage name="estimate_number" {...{ errors, touched }} />
}
>
<ControlGroup fill={true}>
<InputGroup
intent={
errors.estimate_number &&
touched.estimate_number &&
Intent.DANGER
}
minimal={true}
{...getFieldProps('estimate_number')}
onBlur={handleEstimateNumberChanged}
/>
<InputPrependButton
buttonProps={{
onClick: handleEstimateNumberChange,
icon: <Icon icon={'settings-18'} />,
}}
tooltip={true}
tooltipProps={{
content: 'Setting your auto-generated estimate number',
position: Position.BOTTOM_LEFT,
}}
/>
</ControlGroup>
</FormGroup>
<FastField name={'estimate_number'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'estimate'} />}
inline={true}
className={('form-group--estimate-number', CLASSES.FILL)}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="estimate_number" />}
>
<ControlGroup fill={true}>
<InputGroup
minimal={true}
{...field}
onBlur={handleEstimateNumberChanged}
/>
<InputPrependButton
buttonProps={{
onClick: handleEstimateNumberChange,
icon: <Icon icon={'settings-18'} />,
}}
tooltip={true}
tooltipProps={{
content: 'Setting your auto-generated estimate number',
position: Position.BOTTOM_LEFT,
}}
/>
</ControlGroup>
</FormGroup>
)}
</FastField>
{/* ----------- Reference ----------- */}
<FormGroup
label={<T id={'reference'} />}
inline={true}
className={classNames('form-group--reference', Classes.FILL)}
intent={errors.reference && touched.reference && Intent.DANGER}
helperText={
<ErrorMessage name="reference" {...{ errors, touched }} />
}
>
<InputGroup
intent={errors.reference && touched.reference && Intent.DANGER}
minimal={true}
{...getFieldProps('reference')}
/>
</FormGroup>
<FastField name={'reference'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'reference'} />}
inline={true}
className={classNames('form-group--reference', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="reference" />}
>
<InputGroup minimal={true} {...field} />
</FormGroup>
)}
</FastField>
</div>
</div>
);

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

View File

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

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 {
FormGroup,
InputGroup,
Intent,
Position,
ControlGroup,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FastField, ErrorMessage } from 'formik';
import { FormattedMessage as T } from 'react-intl';
import moment from 'moment';
import { momentFormatter, compose, tansformDateValue, saveInvoke } from 'utils';
@@ -14,7 +14,6 @@ import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import {
ContactSelecetList,
ErrorMessage,
FieldRequiredHint,
Icon,
InputPrependButton,
@@ -25,9 +24,9 @@ import {
import withCustomers from 'containers/Customers/withCustomers';
import withDialogActions from 'containers/Dialog/withDialogActions';
function InvoiceFormHeader({
formik: { errors, touched, setFieldValue, getFieldProps, values },
import { inputIntent, handleDateChange } from 'utils';
function InvoiceFormHeader({
//#withCustomers
customers,
//#withDialogActions
@@ -36,24 +35,6 @@ function InvoiceFormHeader({
// #ownProps
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(() => {
openDialog('invoice-number-form', {});
}, [openDialog]);
@@ -66,130 +47,134 @@ function InvoiceFormHeader({
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}>
{/* ----------- Customer name ----------- */}
<FormGroup
label={<T id={'customer_name'} />}
inline={true}
className={classNames(
'form-group--select-list',
'form-group--customer-name',
CLASSES.FILL,
<FastField name={'customer_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'customer_name'} />}
inline={true}
className={classNames(
'form-group--customer-name',
CLASSES.FILL,
)}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'customer_id'} />}
>
<ContactSelecetList
contactsList={customers}
selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={(customer) => {
form.setFieldValue('customer_id', customer.id);
}}
/>
</FormGroup>
)}
labelInfo={<FieldRequiredHint />}
intent={errors.customer_id && touched.customer_id && Intent.DANGER}
helperText={
<ErrorMessage name={'customer_id'} {...{ errors, touched }} />
}
>
<ContactSelecetList
contactsList={customers}
selectedContactId={values.customer_id}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={onChangeCustomer('customer_id')}
/>
</FormGroup>
</FastField>
<Row>
<Col md={7} className={'col--invoice-date'}>
{/* ----------- Invoice date ----------- */}
<FormGroup
label={<T id={'invoice_date'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
className={classNames(
'form-group--select-list',
'form-group--invoice-date',
CLASSES.FILL,
<FastField name={'invoice_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'invoice_date'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
className={classNames(
'form-group--invoice-date',
CLASSES.FILL,
)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="invoice_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('invoice_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
)}
intent={
errors.invoice_date && touched.invoice_date && Intent.DANGER
}
helperText={
<ErrorMessage name="invoice_date" {...{ errors, touched }} />
}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.invoice_date)}
onChange={handleDateChange('invoice_date')}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
</FastField>
</Col>
<Col md={5} className={'col--due-date'}>
{/* ----------- Due date ----------- */}
<FormGroup
label={<T id={'due_date'} />}
inline={true}
className={classNames(
'form-group--select-list',
'form-group--due-date',
CLASSES.FILL,
<FastField name={'due_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'due_date'} />}
inline={true}
className={classNames(
'form-group--due-date',
CLASSES.FILL,
)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="due_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('due_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
)}
intent={errors.due_date && touched.due_date && Intent.DANGER}
helperText={
<ErrorMessage name="due_date" {...{ errors, touched }} />
}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.due_date)}
onChange={handleDateChange('due_date')}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
</FastField>
</Col>
</Row>
{/* ----------- Invoice number ----------- */}
<FormGroup
label={<T id={'invoice_no'} />}
inline={true}
className={classNames('form-group--invoice-no', CLASSES.FILL)}
intent={errors.invoice_no && touched.invoice_no && Intent.DANGER}
helperText={
<ErrorMessage name="invoice_no" {...{ errors, touched }} />
}
>
<ControlGroup fill={true}>
<InputGroup
intent={errors.invoice_no && touched.invoice_no && Intent.DANGER}
minimal={true}
{...getFieldProps('invoice_no')}
onBlur={handleInvoiceNumberChanged}
/>
<InputPrependButton
buttonProps={{
onClick: handleInvoiceNumberChange,
icon: <Icon icon={'settings-18'} />,
}}
tooltip={true}
tooltipProps={{
content: 'Setting your auto-generated invoice number',
position: Position.BOTTOM_LEFT,
}}
/>
</ControlGroup>
</FormGroup>
<FastField name={'invoice_no'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'invoice_no'} />}
inline={true}
className={classNames('form-group--invoice-no', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="invoice_no" />}
>
<ControlGroup fill={true}>
<InputGroup
minimal={true}
{...field}
onBlur={handleInvoiceNumberChanged}
/>
<InputPrependButton
buttonProps={{
onClick: handleInvoiceNumberChange,
icon: <Icon icon={'settings-18'} />,
}}
tooltip={true}
tooltipProps={{
content: 'Setting your auto-generated invoice number',
position: Position.BOTTOM_LEFT,
}}
/>
</ControlGroup>
</FormGroup>
)}
</FastField>
{/* ----------- Reference ----------- */}
<FormGroup
label={<T id={'reference'} />}
inline={true}
className={classNames('form-group--reference', CLASSES.FILL)}
intent={errors.reference_no && touched.reference_no && Intent.DANGER}
helperText={
<ErrorMessage name="reference" {...{ errors, touched }} />
}
>
<InputGroup
intent={
errors.reference_no && touched.reference_no && Intent.DANGER
}
minimal={true}
{...getFieldProps('reference_no')}
/>
</FormGroup>
<FastField name={'reference'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'reference'} />}
inline={true}
className={classNames('form-group--reference', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="reference" />}
>
<InputGroup minimal={true} {...field} />
</FormGroup>
)}
</FastField>
</div>
</div>
);

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, {
useMemo,
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import React, { useMemo, useCallback, useEffect, useState } from 'react';
import { Formik, Form } from 'formik';
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 { pick, sumBy } from 'lodash';
import classNames from 'classnames';
import { useHistory } from 'react-router-dom';
import { CLASSES } from 'common/classes';
import { ERROR } from 'common/errors';
import ReceiptFromHeader from './ReceiptFormHeader';
import EntriesItemsTable from 'containers/Sales/Estimate/EntriesItemsTable';
import ReceiptReceiveFloatingActions from './ReceiptReceiveFloatingActions';
import {
EditReceiptFormSchema,
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 withReceiptDetail from './withReceiptDetail';
@@ -29,14 +28,34 @@ import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withMediaActions from 'containers/Media/withMediaActions';
import withSettings from 'containers/Settings/withSettings';
import { AppToaster, Row, Col } from 'components';
import { AppToaster } from 'components';
import Dragzone from 'components/Dragzone';
import useMedia from 'hooks/useMedia';
import { compose, repeatValue } from 'utils';
import { compose, repeatValue, orderingLinesIndexes } from 'utils';
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.
*/
@@ -49,7 +68,6 @@ function ReceiptForm({
//#withReceiptActions
requestSubmitReceipt,
requestEditReceipt,
setReceiptNumberChanged,
//#withReceiptDetail
receipt,
@@ -62,36 +80,16 @@ function ReceiptForm({
receiptNextNumber,
receiptNumberPrefix,
// #withReceipts
receiptNumberChanged,
//#own Props
receiptId,
onFormSubmit,
onCancelForm,
}) {
const { formatMessage } = useIntl();
const [payload, setPayload] = useState({});
const history = useHistory();
const {
setFiles,
saveMedia,
deletedFiles,
setDeletedFiles,
deleteMedia,
} = useMedia({
saveCallback: requestSubmitMedia,
deleteCallback: requestDeleteMedia,
});
const handleDropFiles = useCallback((_files) => {
setFiles(_files.filter((file) => file.uploaded === false));
}, []);
const savedMediaIds = useRef([]);
const clearSavedMediaIds = () => {
savedMediaIds.current = [];
};
const [submitPayload, setSubmitPayload ] = useState({});
const isNewMode = !receiptId;
const receiptNumber = receiptNumberPrefix
? `${receiptNumberPrefix}-${receiptNextNumber}`
@@ -105,93 +103,15 @@ function ReceiptForm({
changePageSubtitle(`No. ${receiptNumber}`);
changePageTitle(formatMessage({ id: 'new_receipt' }));
}
}, [changePageTitle, changePageSubtitle, receipt, formatMessage]);
const validationSchema = 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 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,
}));
};
}, [
changePageTitle,
changePageSubtitle,
receipt,
receiptNumber,
formatMessage,
]);
// Initial values in create and edit mode.
const initialValues = useMemo(
() => ({
...(receipt
@@ -209,22 +129,14 @@ function ReceiptForm({
}
: {
...defaultInitialValues,
entries: orderingIndex(defaultInitialValues.entries),
receipt_number: receiptNumber,
entries: orderingLinesIndexes(defaultInitialValues.entries),
}),
}),
[receipt, defaultInitialValues, defaultReceipt],
[receipt],
);
const initialAttachmentFiles = useMemo(() => {
return receipt && receipt.media
? receipt.media.map((attach) => ({
preview: attach.attachment_file,
uploaded: true,
metadata: { ...attach },
}))
: [];
}, [receipt]);
// Transform response error to fields.
const handleErrors = (errors, { setErrors }) => {
if (errors.some((e) => e.type === ERROR.SALE_RECEIPT_NUMBER_NOT_UNIQUE)) {
setErrors({
@@ -234,130 +146,67 @@ function ReceiptForm({
});
}
};
const formik = useFormik({
validationSchema,
initialValues: {
...initialValues,
},
onSubmit: (values, { setErrors, setSubmitting, resetForm }) => {
const entries = values.entries.filter(
(item) => item.item_id && item.quantity,
);
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
// Handle the form submit.
const handleFormSubmit = (
values,
{ setErrors, setSubmitting, resetForm },
) => {
const entries = values.entries.filter(
(item) => item.item_id && item.quantity,
);
if (totalQuantity === 0) {
AppToaster.show({
message: formatMessage({
id: 'quantity_cannot_be_zero_or_empty',
}),
intent: Intent.DANGER,
});
setSubmitting(false);
return;
}
const form = {
...values,
entries,
};
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
const requestForm = { ...form };
if (receipt && receipt.id) {
requestEditReceipt(receipt.id, requestForm)
.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 {
requestSubmitReceipt(requestForm)
.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]);
}
if (totalQuantity === 0) {
AppToaster.show({
message: formatMessage({
id: 'quantity_cannot_be_zero_or_empty',
}),
intent: Intent.DANGER,
});
},
[setDeletedFiles, deletedFiles],
);
setSubmitting(false);
return;
}
const form = {
...values,
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();
const handleSubmitClick = useCallback(
(payload) => {
setPayload(payload);
formik.submitForm();
},
[setPayload, formik],
);
if (submitPayload.redirect) {
history.push('/receipts');
}
};
const handleCancelClick = useCallback(
(payload) => {
onCancelForm && onCancelForm(payload);
},
[onCancelForm],
);
// Handle the request error.
const onError = (errors) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
};
const handleClickAddNewRow = () => {
formik.setFieldValue(
'entries',
orderingIndex([...formik.values.entries, defaultReceipt]),
);
};
const handleClearAllLines = () => {
formik.setFieldValue(
'entries',
orderingIndex([...repeatValue(defaultReceipt, MIN_LINES_NUMBER)]),
);
if (receipt && receipt.id) {
requestEditReceipt(receipt.id, form).then(onSuccess).catch(onError);
} else {
requestSubmitReceipt(form).then(onSuccess).catch(onError);
}
};
const handleReceiptNumberChanged = useCallback(
@@ -367,64 +216,42 @@ function ReceiptForm({
[changePageSubtitle],
);
const handleSubmitClick = (event) => {
setSubmitPayload({ redirect: true });
};
const handleSubmitAndNewClick = (event) => {
setSubmitPayload({ redirect: false });
};
const handleCancelClick = (event) => {
history.goBack();
};
return (
<div className={classNames(CLASSES.PAGE_FORM_RECEIPT, CLASSES.PAGE_FORM)}>
<form onSubmit={formik.handleSubmit}>
<ReceiptFromHeader
onReceiptNumberChanged={handleReceiptNumberChanged}
formik={formik}
/>
<EntriesItemsTable
entries={formik.values.entries}
onClickAddNewRow={handleClickAddNewRow}
onClickClearAllLines={handleClearAllLines}
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}
receipt={receipt}
onCancelForm={handleCancelClick}
/>
<Formik
validationSchema={
isNewMode ? CreateReceiptFormSchema : EditReceiptFormSchema
}
initialValues={initialValues}
onSubmit={handleFormSubmit}
>
<Form>
<ReceiptFromHeader
onReceiptNumberChanged={handleReceiptNumberChanged}
/>
<ReceiptNumberWatcher receiptNumber={receiptNumber} />
<EditableItemsEntriesTable />
<ReceiptFormFooter />
<ReceiptFormFloatingActions
receiptId={receiptId}
onSubmitClick={handleSubmitClick}
onSubmitAndNewClick={handleSubmitAndNewClick}
onCancelForm={handleCancelClick}
/>
</Form>
</Formik>
</div>
);
}
@@ -438,5 +265,4 @@ export default compose(
receiptNextNumber: receiptSettings?.nextNumber,
receiptNumberPrefix: receiptSettings?.numberPrefix,
})),
withReceipts(({ receiptNumberChanged }) => ({ receiptNumberChanged })),
)(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 {
FormGroup,
InputGroup,
Intent,
Position,
ControlGroup,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FormattedMessage as T } from 'react-intl';
import moment from 'moment';
import { momentFormatter, compose, tansformDateValue, saveInvoke } from 'utils';
import classNames from 'classnames';
import { FastField, ErrorMessage } from 'formik';
import { CLASSES } from 'common/classes';
import {
AccountsSelectList,
ContactSelecetList,
ErrorMessage,
FieldRequiredHint,
Icon,
InputPrependButton,
@@ -26,9 +24,17 @@ import withCustomers from 'containers/Customers/withCustomers';
import withAccounts from 'containers/Accounts/withAccounts';
import withDialogActions from 'containers/Dialog/withDialogActions';
function ReceiptFormHeader({
formik: { errors, touched, setFieldValue, getFieldProps, values },
import {
momentFormatter,
compose,
tansformDateValue,
saveInvoke,
handleDateChange,
inputIntent,
} from 'utils';
function ReceiptFormHeader({
//#withCustomers
customers,
@@ -41,30 +47,6 @@ function ReceiptFormHeader({
// #ownProps
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(() => {
openDialog('receipt-number-form', {});
}, [openDialog]);
@@ -77,129 +59,124 @@ function ReceiptFormHeader({
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}>
{/* ----------- Customer name ----------- */}
<FormGroup
label={<T id={'customer_name'} />}
inline={true}
className={classNames(
'form-group--select-list',
CLASSES.FILL,
'form-group--customer',
<FastField name={'customer_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'customer_name'} />}
inline={true}
className={classNames(CLASSES.FILL, 'form-group--customer')}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'customer_id'} />}
>
<ContactSelecetList
contactsList={customers}
selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={(contact) => {
form.setFieldValue('customer_id', contact.id);
}}
/>
</FormGroup>
)}
labelInfo={<FieldRequiredHint />}
intent={errors.customer_id && touched.customer_id && Intent.DANGER}
helperText={
<ErrorMessage name={'customer_id'} {...{ errors, touched }} />
}
>
<ContactSelecetList
contactsList={customers}
selectedContactId={values.customer_id}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={onChangeSelect('customer_id')}
/>
</FormGroup>
</FastField>
{/* ----------- Deposit account ----------- */}
<FormGroup
label={<T id={'deposit_account'} />}
className={classNames(
'form-group--deposit-account',
'form-group--select-list',
CLASSES.FILL,
<FastField name={'deposit_account_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'deposit_account'} />}
className={classNames(
'form-group--deposit-account',
CLASSES.FILL,
)}
inline={true}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'deposit_account_id'} />}
>
<AccountsSelectList
accounts={accountsList}
onAccountSelected={(account) => {
form.setFieldValue('deposit_account_id', account.id);
}}
defaultSelectText={<T id={'select_deposit_account'} />}
selectedAccountId={value}
filterByTypes={['current_asset']}
/>
</FormGroup>
)}
inline={true}
labelInfo={<FieldRequiredHint />}
intent={
errors.deposit_account_id &&
touched.deposit_account_id &&
Intent.DANGER
}
helperText={
<ErrorMessage
name={'deposit_account_id'}
{...{ errors, touched }}
/>
}
>
<AccountsSelectList
accounts={depositAccounts}
onAccountSelected={onChangeSelect('deposit_account_id')}
defaultSelectText={<T id={'select_deposit_account'} />}
selectedAccountId={values.deposit_account_id}
/>
</FormGroup>
</FastField>
{/* ----------- Receipt date ----------- */}
<FormGroup
label={<T id={'receipt_date'} />}
inline={true}
className={classNames('form-group--select-list', CLASSES.FILL)}
intent={errors.receipt_date && touched.receipt_date && Intent.DANGER}
helperText={
<ErrorMessage name="receipt_date" {...{ errors, touched }} />
}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.receipt_date)}
onChange={handleDateChange}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
<FastField name={'receipt_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'receipt_date'} />}
inline={true}
className={classNames(CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="receipt_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('receipt_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
)}
</FastField>
{/* ----------- Receipt number ----------- */}
<FormGroup
label={<T id={'receipt'} />}
inline={true}
className={('form-group--receipt_number', CLASSES.FILL)}
labelInfo={<FieldRequiredHint />}
intent={
errors.receipt_number && touched.receipt_number && Intent.DANGER
}
helperText={
<ErrorMessage name="receipt_number" {...{ errors, touched }} />
}
>
<ControlGroup fill={true}>
<InputGroup
intent={
errors.receipt_number && touched.receipt_number && Intent.DANGER
}
minimal={true}
{...getFieldProps('receipt_number')}
onBlur={handleReceiptNumberChanged}
/>
<InputPrependButton
buttonProps={{
onClick: handleReceiptNumberChange,
icon: <Icon icon={'settings-18'} />,
}}
tooltip={true}
tooltipProps={{
content: 'Setting your auto-generated receipt number',
position: Position.BOTTOM_LEFT,
}}
/>
</ControlGroup>
</FormGroup>
<FastField name={'receipt_number'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'receipt'} />}
inline={true}
className={('form-group--receipt_number', CLASSES.FILL)}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="receipt_number" />}
>
<ControlGroup fill={true}>
<InputGroup
minimal={true}
{...field}
onBlur={handleReceiptNumberChanged}
/>
<InputPrependButton
buttonProps={{
onClick: handleReceiptNumberChange,
icon: <Icon icon={'settings-18'} />,
}}
tooltip={true}
tooltipProps={{
content: 'Setting your auto-generated receipt number',
position: Position.BOTTOM_LEFT,
}}
/>
</ControlGroup>
</FormGroup>
)}
</FastField>
{/* ----------- Reference ----------- */}
<FormGroup
label={<T id={'reference'} />}
inline={true}
className={classNames('form-group--reference', CLASSES.FILL)}
intent={errors.reference_no && touched.reference_no && Intent.DANGER}
helperText={
<ErrorMessage name="reference" {...{ errors, touched }} />
}
>
<InputGroup
intent={
errors.reference_no && touched.reference_no && Intent.DANGER
}
minimal={true}
{...getFieldProps('reference_no')}
/>
</FormGroup>
<FastField name={'reference'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'reference'} />}
inline={true}
className={classNames('form-group--reference', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="reference" />}
>
<InputGroup minimal={true} {...field} />
</FormGroup>
)}
</FastField>
</div>
</div>
);

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-target {
display: block;

View File

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