mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-16 12:50:38 +00:00
chrone: sperate client and server to different repos.
This commit is contained in:
196
src/containers/Sales/Receipts/ReceiptForm/ReceiptForm.js
Normal file
196
src/containers/Sales/Receipts/ReceiptForm/ReceiptForm.js
Normal file
@@ -0,0 +1,196 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Formik, Form } from 'formik';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
import { omit, sumBy, isEmpty } from 'lodash';
|
||||
import classNames from 'classnames';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { ERROR } from 'common/errors';
|
||||
import {
|
||||
EditReceiptFormSchema,
|
||||
CreateReceiptFormSchema,
|
||||
} from './ReceiptForm.schema';
|
||||
|
||||
import { useReceiptFormContext } from './ReceiptFormProvider';
|
||||
|
||||
import ReceiptFromHeader from './ReceiptFormHeader';
|
||||
import ReceiptItemsEntriesEditor from './ReceiptItemsEntriesEditor';
|
||||
import ReceiptFormFloatingActions from './ReceiptFormFloatingActions';
|
||||
import ReceiptFormFooter from './ReceiptFormFooter';
|
||||
import ReceiptFormDialogs from './ReceiptFormDialogs';
|
||||
|
||||
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import { AppToaster } from 'components';
|
||||
import { compose, orderingLinesIndexes, transactionNumber } from 'utils';
|
||||
import { transformToEditForm, defaultReceipt } from './utils';
|
||||
|
||||
/**
|
||||
* Receipt form.
|
||||
*/
|
||||
function ReceiptForm({
|
||||
// #withSettings
|
||||
receiptNextNumber,
|
||||
receiptNumberPrefix,
|
||||
receiptAutoIncrement,
|
||||
preferredDepositAccount,
|
||||
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Receipt form context.
|
||||
const {
|
||||
receipt,
|
||||
editReceiptMutate,
|
||||
createReceiptMutate,
|
||||
submitPayload,
|
||||
isNewMode,
|
||||
} = useReceiptFormContext();
|
||||
|
||||
// The next receipt number.
|
||||
const nextReceiptNumber = transactionNumber(
|
||||
receiptNumberPrefix,
|
||||
receiptNextNumber,
|
||||
);
|
||||
// Initial values in create and edit mode.
|
||||
const initialValues = useMemo(
|
||||
() => ({
|
||||
...(!isEmpty(receipt)
|
||||
? { ...transformToEditForm(receipt), currency_code: base_currency }
|
||||
: {
|
||||
...defaultReceipt,
|
||||
...(receiptAutoIncrement && {
|
||||
receipt_number: nextReceiptNumber,
|
||||
}),
|
||||
deposit_account_id: parseInt(preferredDepositAccount),
|
||||
entries: orderingLinesIndexes(defaultReceipt.entries),
|
||||
currency_code: base_currency,
|
||||
}),
|
||||
}),
|
||||
[receipt, preferredDepositAccount, nextReceiptNumber, receiptAutoIncrement],
|
||||
);
|
||||
|
||||
// Transform response error to fields.
|
||||
const handleErrors = (errors, { setErrors }) => {
|
||||
if (errors.some((e) => e.type === ERROR.SALE_RECEIPT_NUMBER_NOT_UNIQUE)) {
|
||||
setErrors({
|
||||
receipt_number: intl.get('sale_receipt_number_not_unique'),
|
||||
});
|
||||
}
|
||||
if (errors.some((e) => e.type === ERROR.SALE_RECEIPT_NO_IS_REQUIRED)) {
|
||||
setErrors({
|
||||
receipt_number: intl.get('receipt.field.error.receipt_number_required'),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Handle the form submit.
|
||||
const handleFormSubmit = (
|
||||
values,
|
||||
{ setErrors, setSubmitting, 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: intl.get('quantity_cannot_be_zero_or_empty'),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
const form = {
|
||||
...omit(values, ['receipt_number_manually', 'receipt_number']),
|
||||
...(values.receipt_number_manually && {
|
||||
receipt_number: values.receipt_number,
|
||||
currency_code: base_currency,
|
||||
}),
|
||||
closed: submitPayload.status,
|
||||
entries: entries.map((entry) => ({ ...omit(entry, ['total']) })),
|
||||
};
|
||||
// Handle the request success.
|
||||
const onSuccess = (response) => {
|
||||
AppToaster.show({
|
||||
message: intl.get(
|
||||
isNewMode
|
||||
? 'the_receipt_has_been_created_successfully'
|
||||
: 'the_receipt_has_been_edited_successfully',
|
||||
{ number: values.receipt_number },
|
||||
),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
|
||||
if (submitPayload.redirect) {
|
||||
history.push('/receipts');
|
||||
}
|
||||
if (submitPayload.resetForm) {
|
||||
resetForm();
|
||||
}
|
||||
};
|
||||
|
||||
// Handle the request error.
|
||||
const onError = ({
|
||||
response: {
|
||||
data: { errors },
|
||||
},
|
||||
}) => {
|
||||
if (errors) {
|
||||
handleErrors(errors, { setErrors });
|
||||
}
|
||||
setSubmitting(false);
|
||||
};
|
||||
if (!isNewMode) {
|
||||
editReceiptMutate([receipt.id, form]).then(onSuccess).catch(onError);
|
||||
} else {
|
||||
createReceiptMutate(form).then(onSuccess).catch(onError);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
CLASSES.PAGE_FORM,
|
||||
CLASSES.PAGE_FORM_STRIP_STYLE,
|
||||
CLASSES.PAGE_FORM_RECEIPT,
|
||||
)}
|
||||
>
|
||||
<Formik
|
||||
validationSchema={
|
||||
isNewMode ? CreateReceiptFormSchema : EditReceiptFormSchema
|
||||
}
|
||||
initialValues={initialValues}
|
||||
onSubmit={handleFormSubmit}
|
||||
>
|
||||
<Form>
|
||||
<ReceiptFromHeader />
|
||||
<ReceiptItemsEntriesEditor />
|
||||
<ReceiptFormFooter />
|
||||
<ReceiptFormFloatingActions />
|
||||
|
||||
<ReceiptFormDialogs />
|
||||
</Form>
|
||||
</Formik>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withDashboardActions,
|
||||
withSettings(({ receiptSettings }) => ({
|
||||
receiptNextNumber: receiptSettings?.nextNumber,
|
||||
receiptNumberPrefix: receiptSettings?.numberPrefix,
|
||||
receiptAutoIncrement: receiptSettings?.autoIncrement,
|
||||
preferredDepositAccount: receiptSettings?.preferredDepositAccount,
|
||||
})),
|
||||
withCurrentOrganization(),
|
||||
)(ReceiptForm);
|
||||
@@ -0,0 +1,57 @@
|
||||
import * as Yup from 'yup';
|
||||
import intl from 'react-intl-universal';
|
||||
import { DATATYPES_LENGTH } from 'common/dataTypes';
|
||||
import { isBlank } from 'utils';
|
||||
|
||||
const Schema = Yup.object().shape({
|
||||
customer_id: Yup.string()
|
||||
.label(intl.get('customer_name_'))
|
||||
.required(),
|
||||
receipt_date: Yup.date()
|
||||
.required()
|
||||
.label(intl.get('receipt_date_')),
|
||||
receipt_number: Yup.string()
|
||||
.nullable()
|
||||
.max(DATATYPES_LENGTH.STRING)
|
||||
.label(intl.get('receipt_no_')),
|
||||
deposit_account_id: Yup.number()
|
||||
.required()
|
||||
.label(intl.get('deposit_account_')),
|
||||
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING),
|
||||
receipt_message: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(DATATYPES_LENGTH.STRING)
|
||||
.label(intl.get('receipt_message_')),
|
||||
statement: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(DATATYPES_LENGTH.TEXT)
|
||||
.label(intl.get('note')),
|
||||
closed: Yup.boolean(),
|
||||
entries: Yup.array().of(
|
||||
Yup.object().shape({
|
||||
quantity: Yup.number()
|
||||
.nullable()
|
||||
.max(DATATYPES_LENGTH.INT_10)
|
||||
.when(['rate'], {
|
||||
is: (rate) => rate,
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
rate: Yup.number().nullable().max(DATATYPES_LENGTH.INT_10),
|
||||
item_id: Yup.number()
|
||||
.nullable()
|
||||
.when(['quantity', 'rate'], {
|
||||
is: (quantity, rate) => !isBlank(quantity) && !isBlank(rate),
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
discount: Yup.number().nullable().min(0).max(DATATYPES_LENGTH.INT_10),
|
||||
description: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const CreateReceiptFormSchema = Schema;
|
||||
const EditReceiptFormSchema = Schema;
|
||||
|
||||
export { CreateReceiptFormSchema, EditReceiptFormSchema };
|
||||
@@ -0,0 +1,25 @@
|
||||
import React from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import ReceiptNumberDialog from 'containers/Dialogs/ReceiptNumberDialog';
|
||||
|
||||
/**
|
||||
* Receipt form dialogs.
|
||||
*/
|
||||
export default function ReceiptFormDialogs() {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
|
||||
// Update the form once the receipt number form submit confirm.
|
||||
const handleReceiptNumberFormConfirm = ({ incrementNumber, manually }) => {
|
||||
setFieldValue('receipt_number', incrementNumber || '');
|
||||
setFieldValue('receipt_number_manually', manually);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ReceiptNumberDialog
|
||||
dialogName={'receipt-number-form'}
|
||||
onConfirm={handleReceiptNumberFormConfirm}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Intent,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
Popover,
|
||||
PopoverInteractionKind,
|
||||
Position,
|
||||
Menu,
|
||||
MenuItem,
|
||||
} from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import classNames from 'classnames';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { If, Icon } from 'components';
|
||||
import { useReceiptFormContext } from './ReceiptFormProvider';
|
||||
|
||||
/**
|
||||
* Receipt floating actions bar.
|
||||
*/
|
||||
export default function ReceiptFormFloatingActions() {
|
||||
// History context.
|
||||
const history = useHistory();
|
||||
|
||||
// Formik context.
|
||||
const { resetForm, submitForm, isSubmitting } = useFormikContext();
|
||||
|
||||
// Receipt form context.
|
||||
const { receipt, setSubmitPayload } = useReceiptFormContext();
|
||||
|
||||
// Handle submit & close button click.
|
||||
const handleSubmitCloseBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, status: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, close & new button click.
|
||||
const handleSubmitCloseAndNewBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, status: true, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, close & continue editing button click.
|
||||
const handleSubmitCloseContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, status: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit & draft button click.
|
||||
const handleSubmitDraftBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, status: false });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, draft & new button click.
|
||||
const handleSubmitDraftAndNewBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, status: false, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
const handleSubmitDraftContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, status: false });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle cancel button click.
|
||||
const handleCancelBtnClick = (event) => {
|
||||
history.goBack();
|
||||
};
|
||||
|
||||
const handleClearBtnClick = (event) => {
|
||||
resetForm();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
|
||||
{/* ----------- Save And Close ----------- */}
|
||||
<If condition={!receipt || !receipt?.is_closed}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
onClick={handleSubmitCloseBtnClick}
|
||||
text={<T id={'save_close'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'close_and_new'} />}
|
||||
onClick={handleSubmitCloseAndNewBtnClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'close_continue_editing'} />}
|
||||
onClick={handleSubmitCloseContinueEditingBtnClick}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
minimal={true}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
|
||||
/>
|
||||
</Popover>
|
||||
</ButtonGroup>
|
||||
{/* ----------- Save As Draft ----------- */}
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
className={'ml1'}
|
||||
onClick={handleSubmitDraftBtnClick}
|
||||
text={<T id={'save_as_draft'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitDraftAndNewBtnClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'save_continue_editing'} />}
|
||||
onClick={handleSubmitDraftContinueEditingBtnClick}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
minimal={true}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
|
||||
/>
|
||||
</Popover>
|
||||
</ButtonGroup>
|
||||
</If>
|
||||
{/* ----------- Save and New ----------- */}
|
||||
<If condition={receipt && receipt?.is_closed}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
onClick={handleSubmitCloseBtnClick}
|
||||
text={<T id={'save'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitCloseAndNewBtnClick}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
minimal={true}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
|
||||
/>
|
||||
</Popover>
|
||||
</ButtonGroup>
|
||||
</If>
|
||||
{/* ----------- Clear & Reset----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
disabled={isSubmitting}
|
||||
onClick={handleClearBtnClick}
|
||||
text={receipt ? <T id={'reset'} /> : <T id={'clear'} />}
|
||||
/>
|
||||
{/* ----------- Cancel ----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
onClick={handleCancelBtnClick}
|
||||
text={<T id={'cancel'} />}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import React from 'react';
|
||||
import { FormGroup, TextArea } from '@blueprintjs/core';
|
||||
import { FastField } from 'formik';
|
||||
import classNames from 'classnames';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { Dragzone, Postbox, 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)}>
|
||||
<Postbox title={<T id={'receipt_details'}/>} defaultOpen={false}>
|
||||
<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={<T id={'attachments_maximum'} />}
|
||||
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</Postbox>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { useFormikContext } from 'formik';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { PageFormBigNumber } from 'components';
|
||||
import ReceiptFormHeaderFields from './ReceiptFormHeaderFields';
|
||||
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import { getEntriesTotal } from 'containers/Entries/utils';
|
||||
import { compose } from 'redux';
|
||||
|
||||
/**
|
||||
* Receipt form header section.
|
||||
*/
|
||||
function ReceiptFormHeader({
|
||||
// #ownProps
|
||||
onReceiptNumberChanged,
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
const { values } = useFormikContext();
|
||||
|
||||
// Calculate the total due amount of bill entries.
|
||||
const totalDueAmount = useMemo(
|
||||
() => getEntriesTotal(values.entries),
|
||||
[values.entries],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
|
||||
<ReceiptFormHeaderFields
|
||||
onReceiptNumberChanged={onReceiptNumberChanged}
|
||||
/>
|
||||
<PageFormBigNumber
|
||||
label={intl.get('due_amount')}
|
||||
amount={totalDueAmount}
|
||||
currencyCode={base_currency}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withCurrentOrganization())(ReceiptFormHeader);
|
||||
@@ -0,0 +1,228 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import {
|
||||
FormGroup,
|
||||
InputGroup,
|
||||
Position,
|
||||
ControlGroup,
|
||||
} from '@blueprintjs/core';
|
||||
import { DateInput } from '@blueprintjs/datetime';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import classNames from 'classnames';
|
||||
import { FastField, ErrorMessage } from 'formik';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import {
|
||||
AccountsSelectList,
|
||||
ContactSelecetList,
|
||||
FieldRequiredHint,
|
||||
Icon,
|
||||
InputPrependButton,
|
||||
} from 'components';
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import withDialogActions from 'containers/Dialog/withDialogActions';
|
||||
import { ACCOUNT_TYPE } from 'common/accountTypes';
|
||||
import {
|
||||
momentFormatter,
|
||||
compose,
|
||||
tansformDateValue,
|
||||
handleDateChange,
|
||||
inputIntent,
|
||||
} from 'utils';
|
||||
import { useReceiptFormContext } from './ReceiptFormProvider';
|
||||
import {
|
||||
accountsFieldShouldUpdate,
|
||||
customersFieldShouldUpdate,
|
||||
useObserveReceiptNoSettings,
|
||||
} from './utils';
|
||||
|
||||
/**
|
||||
* Receipt form header fields.
|
||||
*/
|
||||
function ReceiptFormHeader({
|
||||
//#withDialogActions
|
||||
openDialog,
|
||||
|
||||
// #ownProps
|
||||
onReceiptNumberChanged,
|
||||
|
||||
// #withSettings
|
||||
receiptAutoIncrement,
|
||||
receiptNextNumber,
|
||||
receiptNumberPrefix,
|
||||
}) {
|
||||
const { accounts, customers } = useReceiptFormContext();
|
||||
|
||||
const handleReceiptNumberChange = useCallback(() => {
|
||||
openDialog('receipt-number-form', {});
|
||||
}, [openDialog]);
|
||||
|
||||
const handleReceiptNoBlur = (form, field) => (event) => {
|
||||
const newValue = event.target.value;
|
||||
|
||||
if (field.value !== newValue && receiptAutoIncrement) {
|
||||
openDialog('receipt-number-form', {
|
||||
initialFormValues: {
|
||||
manualTransactionNo: newValue,
|
||||
incrementMode: 'manual-transaction',
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Synsc receipt number settings with the form.
|
||||
useObserveReceiptNoSettings(receiptNumberPrefix, receiptNextNumber);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
|
||||
{/* ----------- Customer name ----------- */}
|
||||
<FastField
|
||||
name={'customer_id'}
|
||||
customers={customers}
|
||||
shouldUpdate={customersFieldShouldUpdate}
|
||||
>
|
||||
{({ 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);
|
||||
}}
|
||||
popoverFill={true}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Deposit account ----------- */}
|
||||
<FastField
|
||||
name={'deposit_account_id'}
|
||||
accounts={accounts}
|
||||
shouldUpdate={accountsFieldShouldUpdate}
|
||||
>
|
||||
{({ 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={accounts}
|
||||
onAccountSelected={(account) => {
|
||||
form.setFieldValue('deposit_account_id', account.id);
|
||||
}}
|
||||
defaultSelectText={<T id={'select_deposit_account'} />}
|
||||
selectedAccountId={value}
|
||||
popoverFill={true}
|
||||
filterByTypes={[
|
||||
ACCOUNT_TYPE.CASH,
|
||||
ACCOUNT_TYPE.BANK,
|
||||
ACCOUNT_TYPE.OTHER_CURRENT_ASSET,
|
||||
]}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Receipt date ----------- */}
|
||||
<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 }}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Receipt number ----------- */}
|
||||
<FastField name={'receipt_number'}>
|
||||
{({ form, 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}
|
||||
value={field.value}
|
||||
asyncControl={true}
|
||||
onBlur={handleReceiptNoBlur(form, field)}
|
||||
/>
|
||||
<InputPrependButton
|
||||
buttonProps={{
|
||||
onClick: handleReceiptNumberChange,
|
||||
icon: <Icon icon={'settings-18'} />,
|
||||
}}
|
||||
tooltip={true}
|
||||
tooltipProps={{
|
||||
content: (
|
||||
<T
|
||||
id={'setting_your_auto_generated_payment_receive_number'}
|
||||
/>
|
||||
),
|
||||
position: Position.BOTTOM_LEFT,
|
||||
}}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</ControlGroup>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- 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_no" />}
|
||||
>
|
||||
<InputGroup minimal={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withDialogActions,
|
||||
withSettings(({ receiptSettings }) => ({
|
||||
receiptAutoIncrement: receiptSettings?.autoIncrement,
|
||||
receiptNextNumber: receiptSettings?.nextNumber,
|
||||
receiptNumberPrefix: receiptSettings?.numberPrefix,
|
||||
})),
|
||||
)(ReceiptFormHeader);
|
||||
21
src/containers/Sales/Receipts/ReceiptForm/ReceiptFormPage.js
Normal file
21
src/containers/Sales/Receipts/ReceiptForm/ReceiptFormPage.js
Normal file
@@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
import 'style/pages/SaleReceipt/PageForm.scss';
|
||||
|
||||
import ReceiptFrom from './ReceiptForm';
|
||||
import { ReceiptFormProvider } from './ReceiptFormProvider';
|
||||
|
||||
/**
|
||||
* Receipt form page.
|
||||
*/
|
||||
export default function ReceiptFormPage() {
|
||||
const { id } = useParams();
|
||||
const idInt = parseInt(id, 10);
|
||||
|
||||
return (
|
||||
<ReceiptFormProvider receiptId={idInt}>
|
||||
<ReceiptFrom />
|
||||
</ReceiptFormProvider>
|
||||
);
|
||||
}
|
||||
101
src/containers/Sales/Receipts/ReceiptForm/ReceiptFormProvider.js
Normal file
101
src/containers/Sales/Receipts/ReceiptForm/ReceiptFormProvider.js
Normal file
@@ -0,0 +1,101 @@
|
||||
import React, { createContext, useState } from 'react';
|
||||
import DashboardInsider from 'components/Dashboard/DashboardInsider';
|
||||
import {
|
||||
useReceipt,
|
||||
useAccounts,
|
||||
useSettingsReceipts,
|
||||
useCustomers,
|
||||
useItems,
|
||||
useCreateReceipt,
|
||||
useEditReceipt,
|
||||
} from 'hooks/query';
|
||||
|
||||
const ReceiptFormContext = createContext();
|
||||
|
||||
/**
|
||||
* Receipt form provider.
|
||||
*/
|
||||
function ReceiptFormProvider({ receiptId, ...props }) {
|
||||
// Fetch sale receipt details.
|
||||
const { data: receipt, isLoading: isReceiptLoading } = useReceipt(
|
||||
receiptId,
|
||||
{
|
||||
enabled: !!receiptId,
|
||||
},
|
||||
);
|
||||
// Fetch accounts list.
|
||||
const { data: accounts, isLoading: isAccountsLoading } = useAccounts();
|
||||
|
||||
// Fetch customers list.
|
||||
const {
|
||||
data: { customers },
|
||||
isLoading: isCustomersLoading,
|
||||
} = useCustomers({ page_size: 10000 });
|
||||
|
||||
// Filter all sellable items only.
|
||||
const stringifiedFilterRoles = React.useMemo(
|
||||
() =>
|
||||
JSON.stringify([
|
||||
{ index: 1, fieldKey: 'sellable', value: true, condition: '&&', comparator: 'equals', },
|
||||
{ index: 2, fieldKey: 'active', value: true, condition: '&&', comparator: 'equals' },
|
||||
]),
|
||||
[],
|
||||
);
|
||||
|
||||
// Handle fetch Items data table or list
|
||||
const {
|
||||
data: { items },
|
||||
isLoading: isItemsLoading,
|
||||
} = useItems({
|
||||
page_size: 10000,
|
||||
stringified_filter_roles: stringifiedFilterRoles,
|
||||
});
|
||||
|
||||
// Fetch receipt settings.
|
||||
const { isLoading: isSettingLoading } = useSettingsReceipts();
|
||||
|
||||
const { mutateAsync: createReceiptMutate } = useCreateReceipt();
|
||||
const { mutateAsync: editReceiptMutate } = useEditReceipt();
|
||||
|
||||
const [submitPayload, setSubmitPayload] = useState({});
|
||||
|
||||
const isNewMode = !receiptId;
|
||||
|
||||
const provider = {
|
||||
receiptId,
|
||||
receipt,
|
||||
accounts,
|
||||
customers,
|
||||
items,
|
||||
submitPayload,
|
||||
|
||||
isNewMode,
|
||||
isReceiptLoading,
|
||||
isAccountsLoading,
|
||||
isCustomersLoading,
|
||||
isItemsLoading,
|
||||
isSettingLoading,
|
||||
|
||||
createReceiptMutate,
|
||||
editReceiptMutate,
|
||||
setSubmitPayload,
|
||||
};
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={
|
||||
isReceiptLoading ||
|
||||
isAccountsLoading ||
|
||||
isCustomersLoading ||
|
||||
isItemsLoading ||
|
||||
isSettingLoading
|
||||
}
|
||||
name={'receipt-form'}
|
||||
>
|
||||
<ReceiptFormContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const useReceiptFormContext = () => React.useContext(ReceiptFormContext);
|
||||
|
||||
export { ReceiptFormProvider, useReceiptFormContext };
|
||||
@@ -0,0 +1,34 @@
|
||||
import React from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { FastField } from 'formik';
|
||||
import ItemsEntriesTable from 'containers/Entries/ItemsEntriesTable';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { useReceiptFormContext } from './ReceiptFormProvider';
|
||||
import { entriesFieldShouldUpdate } from './utils';
|
||||
|
||||
export default function ReceiptItemsEntriesEditor({ defaultReceipt }) {
|
||||
const { items } = useReceiptFormContext();
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
|
||||
<FastField name={'entries'} items={items} shouldUpdate={entriesFieldShouldUpdate}>
|
||||
{({
|
||||
form: { values, setFieldValue },
|
||||
field: { value },
|
||||
meta: { error, touched },
|
||||
}) => (
|
||||
<ItemsEntriesTable
|
||||
entries={value}
|
||||
onUpdateData={(entries) => {
|
||||
setFieldValue('entries', entries);
|
||||
}}
|
||||
items={items}
|
||||
errors={error}
|
||||
linesNumber={4}
|
||||
currencyCode={values.currency_code}
|
||||
/>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
101
src/containers/Sales/Receipts/ReceiptForm/utils.js
Normal file
101
src/containers/Sales/Receipts/ReceiptForm/utils.js
Normal file
@@ -0,0 +1,101 @@
|
||||
import React from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import moment from 'moment';
|
||||
import * as R from 'ramda';
|
||||
import {
|
||||
defaultFastFieldShouldUpdate,
|
||||
transactionNumber,
|
||||
repeatValue,
|
||||
transformToForm,
|
||||
} from 'utils';
|
||||
import {
|
||||
updateItemsEntriesTotal,
|
||||
ensureEntriesHaveEmptyLine,
|
||||
} from 'containers/Entries/utils';
|
||||
|
||||
export const MIN_LINES_NUMBER = 4;
|
||||
|
||||
export const defaultReceiptEntry = {
|
||||
index: 0,
|
||||
item_id: '',
|
||||
rate: '',
|
||||
discount: '',
|
||||
quantity: '',
|
||||
description: '',
|
||||
amount: '',
|
||||
};
|
||||
|
||||
export const defaultReceipt = {
|
||||
customer_id: '',
|
||||
deposit_account_id: '',
|
||||
receipt_number: '',
|
||||
receipt_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
reference_no: '',
|
||||
receipt_message: '',
|
||||
statement: '',
|
||||
closed: '',
|
||||
entries: [...repeatValue(defaultReceiptEntry, MIN_LINES_NUMBER)],
|
||||
};
|
||||
|
||||
/**
|
||||
* Transform to form in edit mode.
|
||||
*/
|
||||
export const transformToEditForm = (receipt) => {
|
||||
const initialEntries = [
|
||||
...receipt.entries.map((entry) => ({
|
||||
...transformToForm(entry, defaultReceiptEntry),
|
||||
})),
|
||||
...repeatValue(
|
||||
defaultReceiptEntry,
|
||||
Math.max(MIN_LINES_NUMBER - receipt.entries.length, 0),
|
||||
),
|
||||
];
|
||||
const entries = R.compose(
|
||||
ensureEntriesHaveEmptyLine(defaultReceiptEntry),
|
||||
updateItemsEntriesTotal,
|
||||
)(initialEntries);
|
||||
|
||||
return {
|
||||
...transformToForm(receipt, defaultReceipt),
|
||||
entries,
|
||||
};
|
||||
};
|
||||
|
||||
export const useObserveReceiptNoSettings = (prefix, nextNumber) => {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
|
||||
React.useEffect(() => {
|
||||
const receiptNo = transactionNumber(prefix, nextNumber);
|
||||
setFieldValue('receipt_number', receiptNo);
|
||||
}, [setFieldValue, prefix, nextNumber]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines entries fast field should update.
|
||||
*/
|
||||
export const entriesFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.items !== oldProps.items ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines accounts fast field should update.
|
||||
*/
|
||||
export const accountsFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.accounts !== oldProps.accounts ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines customers fast field should update.
|
||||
*/
|
||||
export const customersFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.customers !== oldProps.customers ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user