mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-18 13:50:31 +00:00
refactoring: WIP payment receive and made form.
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Intent,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
Popover,
|
||||
PopoverInteractionKind,
|
||||
Position,
|
||||
Menu,
|
||||
MenuItem,
|
||||
} from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'react-intl';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import classNames from 'classnames';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { CLASSES } from 'common/classes';
|
||||
|
||||
import { Icon } from 'components';
|
||||
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
|
||||
|
||||
/**
|
||||
* Payment receive floating actions bar.
|
||||
*/
|
||||
export default function PaymentReceiveFormFloatingActions() {
|
||||
|
||||
// Payment receive form context.
|
||||
const { setSubmitPayload, isNewMode } = usePaymentReceiveFormContext();
|
||||
|
||||
// Formik form context.
|
||||
const { isSubmitting } = useFormikContext();
|
||||
|
||||
// History context.
|
||||
const history = useHistory();
|
||||
|
||||
// Handle submit button click.
|
||||
const handleSubmitBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, });
|
||||
};
|
||||
|
||||
// Handle clear button click.
|
||||
const handleClearBtnClick = (event) => {
|
||||
|
||||
};
|
||||
|
||||
// Handle cancel button click.
|
||||
const handleCancelBtnClick = (event) => {
|
||||
history.goBack();
|
||||
};
|
||||
|
||||
// Handle submit & new button click.
|
||||
const handleSubmitAndNewClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, resetForm: true, });
|
||||
};
|
||||
|
||||
// Handle submit & continue editing button click.
|
||||
const handleSubmitContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, publish: true });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
|
||||
{/* ----------- Save and New ----------- */}
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
type="submit"
|
||||
onClick={handleSubmitBtnClick}
|
||||
text={!isNewMode ? <T id={'edit'} /> : <T id={'save'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitAndNewClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'save_continue_editing'} />}
|
||||
onClick={handleSubmitContinueEditingBtnClick}
|
||||
/>
|
||||
</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>
|
||||
|
||||
{/* ----------- Clear & Reset----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
disabled={isSubmitting}
|
||||
onClick={handleClearBtnClick}
|
||||
text={!isNewMode ? <T id={'reset'} /> : <T id={'clear'} />}
|
||||
/>
|
||||
|
||||
{/* ----------- Cancel ----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
onClick={handleCancelBtnClick}
|
||||
text={<T id={'cancel'} />}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Formik, Form } from 'formik';
|
||||
|
||||
import { useIntl } from 'react-intl';
|
||||
import { pick, sumBy, omit, isEmpty } from 'lodash';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import classNames from 'classnames';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import PaymentReceiveHeader from './PaymentReceiveFormHeader';
|
||||
// import PaymentReceiveItemsTable from './PaymentReceiveItemsTable';
|
||||
import PaymentReceiveFloatingActions from './PaymentReceiveFloatingActions';
|
||||
import PaymentReceiveFormFooter from './PaymentReceiveFormFooter';
|
||||
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import {
|
||||
EditPaymentReceiveFormSchema,
|
||||
CreatePaymentReceiveFormSchema,
|
||||
} from './PaymentReceiveForm.schema';
|
||||
import { AppToaster } from 'components';
|
||||
import { compose } from 'utils';
|
||||
|
||||
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
|
||||
import {
|
||||
defaultPaymentReceive,
|
||||
defaultPaymentReceiveEntry,
|
||||
transformToEditForm,
|
||||
} from './utils';
|
||||
|
||||
import 'style/pages/PaymentReceive/PageForm.scss';
|
||||
|
||||
/**
|
||||
* Payment Receive form.
|
||||
*/
|
||||
function PaymentReceiveForm({
|
||||
// #withSettings
|
||||
paymentReceiveNextNumber,
|
||||
paymentReceiveNumberPrefix,
|
||||
}) {
|
||||
const history = useHistory();
|
||||
const { formatMessage } = useIntl();
|
||||
|
||||
// Payment receive form context.
|
||||
const {
|
||||
isNewMode,
|
||||
paymentReceive,
|
||||
paymentReceiveId,
|
||||
submitPayload,
|
||||
editPaymentReceiveMutate,
|
||||
createPaymentReceiveMutate,
|
||||
} = usePaymentReceiveFormContext();
|
||||
|
||||
// Payment receive number.
|
||||
const paymentReceiveNumber = paymentReceiveNumberPrefix
|
||||
? `${paymentReceiveNumberPrefix}-${paymentReceiveNextNumber}`
|
||||
: paymentReceiveNextNumber;
|
||||
|
||||
// Form validation schema.
|
||||
const validationSchema = isNewMode
|
||||
? CreatePaymentReceiveFormSchema
|
||||
: EditPaymentReceiveFormSchema;
|
||||
|
||||
// Form initial values.
|
||||
const initialValues = useMemo(
|
||||
() => ({
|
||||
...(!isEmpty(paymentReceive)
|
||||
? {
|
||||
...transformToEditForm(paymentReceive, []),
|
||||
}
|
||||
: {
|
||||
...paymentReceive,
|
||||
payment_receive_no: paymentReceiveNumber,
|
||||
}),
|
||||
}),
|
||||
[paymentReceive, paymentReceiveNumber],
|
||||
);
|
||||
|
||||
// Handle form submit.
|
||||
const handleSubmitForm = (
|
||||
values,
|
||||
{ setSubmitting, resetForm, setFieldError },
|
||||
) => {
|
||||
setSubmitting(true);
|
||||
|
||||
// Filters entries that have no `invoice_id` and `payment_amount`.
|
||||
const entries = values.entries
|
||||
.filter((entry) => entry.invoice_id && entry.payment_amount)
|
||||
.map((entry) => ({
|
||||
...omit(entry, ['due_amount']),
|
||||
}));
|
||||
|
||||
// Calculates the total payment amount of entries.
|
||||
const totalPaymentAmount = sumBy(entries, 'payment_amount');
|
||||
|
||||
if (totalPaymentAmount <= 0) {
|
||||
AppToaster.show({
|
||||
message: formatMessage({
|
||||
id: 'you_cannot_make_payment_with_zero_total_amount',
|
||||
}),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
const form = { ...values, entries };
|
||||
|
||||
// Handle request response success.
|
||||
const onSaved = (response) => {
|
||||
AppToaster.show({
|
||||
message: formatMessage({
|
||||
id: paymentReceiveId
|
||||
? 'the_payment_receive_transaction_has_been_edited'
|
||||
: 'the_payment_receive_transaction_has_been_created',
|
||||
}),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
|
||||
if (submitPayload.redirect) {
|
||||
history.push('/payment-receives');
|
||||
}
|
||||
if (submitPayload.resetForm) {
|
||||
resetForm();
|
||||
}
|
||||
};
|
||||
// Handle request response errors.
|
||||
const onError = (errors) => {
|
||||
const getError = (errorType) => errors.find((e) => e.type === errorType);
|
||||
|
||||
if (getError('PAYMENT_RECEIVE_NO_EXISTS')) {
|
||||
setFieldError(
|
||||
'payment_receive_no',
|
||||
formatMessage({ id: 'payment_number_is_not_unique' }),
|
||||
);
|
||||
}
|
||||
setSubmitting(false);
|
||||
};
|
||||
|
||||
if (paymentReceiveId) {
|
||||
editPaymentReceiveMutate([paymentReceiveId, form])
|
||||
.then(onSaved)
|
||||
.catch(onError);
|
||||
} else {
|
||||
createPaymentReceiveMutate(form).then(onSaved).catch(onError);
|
||||
}
|
||||
};
|
||||
|
||||
const transformDataTableToEntries = (dataTable) => {
|
||||
return dataTable.map((data) => ({
|
||||
...pick(data, Object.keys(defaultPaymentReceiveEntry)),
|
||||
}));
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
CLASSES.PAGE_FORM,
|
||||
CLASSES.PAGE_FORM_STRIP_STYLE,
|
||||
CLASSES.PAGE_FORM_PAYMENT_RECEIVE,
|
||||
)}
|
||||
>
|
||||
<Formik
|
||||
initialValues={initialValues}
|
||||
onSubmit={handleSubmitForm}
|
||||
validationSchema={validationSchema}
|
||||
>
|
||||
<Form>
|
||||
<PaymentReceiveHeader />
|
||||
<PaymentReceiveFormFooter />
|
||||
<PaymentReceiveFloatingActions />
|
||||
</Form>
|
||||
</Formik>
|
||||
|
||||
{/* <form onSubmit={handleSubmit}> */}
|
||||
{/* <PaymentReceiveHeader
|
||||
errors={errors}
|
||||
touched={touched}
|
||||
setFieldValue={setFieldValue}
|
||||
getFieldProps={getFieldProps}
|
||||
values={values}
|
||||
paymentReceiveId={paymentReceiveId}
|
||||
customerId={values.customer_id}
|
||||
onFullAmountChanged={handleFullAmountChange}
|
||||
receivableFullAmount={receivableFullAmount}
|
||||
amountReceived={fullAmountReceived}
|
||||
onPaymentReceiveNumberChanged={handlePaymentReceiveNumberChanged}
|
||||
/>
|
||||
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
|
||||
<PaymentReceiveItemsTable
|
||||
paymentReceiveId={paymentReceiveId}
|
||||
customerId={values.customer_id}
|
||||
fullAmount={fullAmount}
|
||||
onUpdateData={handleUpdataData}
|
||||
paymentReceiveEntries={localPaymentEntries}
|
||||
errors={errors?.entries}
|
||||
onClickClearAllLines={handleClearAllLines}
|
||||
onFetchEntriesSuccess={handleFetchEntriesSuccess}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<PaymentReceiveFloatingActions
|
||||
isSubmitting={isSubmitting}
|
||||
paymentReceiveId={paymentReceiveId}
|
||||
onClearClick={handleClearBtnClick}
|
||||
onSubmitClick={handleSubmitClick}
|
||||
onCancelClick={handleCancelClick}
|
||||
onSubmitForm={submitForm}
|
||||
/> */}
|
||||
{/* </form> */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withSettings(({ paymentReceiveSettings }) => ({
|
||||
paymentReceiveNextNumber: paymentReceiveSettings?.nextNumber,
|
||||
paymentReceiveNumberPrefix: paymentReceiveSettings?.numberPrefix,
|
||||
})),
|
||||
)(PaymentReceiveForm);
|
||||
@@ -0,0 +1,38 @@
|
||||
import * as Yup from 'yup';
|
||||
import { formatMessage } from 'services/intl';
|
||||
import { DATATYPES_LENGTH } from 'common/dataTypes';
|
||||
|
||||
const Schema = Yup.object().shape({
|
||||
customer_id: Yup.string()
|
||||
.label(formatMessage({ id: 'customer_name_' }))
|
||||
.required(),
|
||||
payment_date: Yup.date()
|
||||
.required()
|
||||
.label(formatMessage({ id: 'payment_date_' })),
|
||||
deposit_account_id: Yup.number()
|
||||
.required()
|
||||
.label(formatMessage({ id: 'deposit_account_' })),
|
||||
full_amount: Yup.number().nullable(),
|
||||
payment_receive_no: Yup.string()
|
||||
.nullable()
|
||||
.max(DATATYPES_LENGTH.STRING)
|
||||
.label(formatMessage({ id: 'payment_receive_no_' })),
|
||||
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING).nullable(),
|
||||
description: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
|
||||
entries: Yup.array().of(
|
||||
Yup.object().shape({
|
||||
id: Yup.number().nullable(),
|
||||
due_amount: Yup.number().nullable(),
|
||||
payment_amount: Yup.number().nullable().max(Yup.ref('due_amount')),
|
||||
invoice_id: Yup.number()
|
||||
.nullable()
|
||||
.when(['payment_amount'], {
|
||||
is: (payment_amount) => payment_amount,
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export const CreatePaymentReceiveFormSchema = Schema;
|
||||
export const EditPaymentReceiveFormSchema = Schema;
|
||||
@@ -0,0 +1,32 @@
|
||||
import React from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { FormGroup, TextArea } from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'react-intl';
|
||||
import { FastField } from 'formik';
|
||||
import { Row, Col } from 'components';
|
||||
import { CLASSES } from 'common/classes';
|
||||
|
||||
/**
|
||||
* Payment receive form footer.
|
||||
*/
|
||||
export default function PaymentReceiveFormFooter({ getFieldProps }) {
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
|
||||
<Row>
|
||||
<Col md={8}>
|
||||
{/* --------- Statement --------- */}
|
||||
<FastField name={'statement'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'statement'} />}
|
||||
className={'form-group--statement'}
|
||||
>
|
||||
<TextArea growVertically={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</Col>
|
||||
</Row>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { sumBy } from 'lodash';
|
||||
import { useFormikContext } from 'formik';
|
||||
import classNames from 'classnames';
|
||||
import { Money } from 'components';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import PaymentReceiveHeaderFields from './PaymentReceiveHeaderFields';
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
/**
|
||||
* Payment receive form header.
|
||||
*/
|
||||
function PaymentReceiveFormHeader({
|
||||
// #withSettings
|
||||
baseCurrency,
|
||||
}) {
|
||||
// Formik form context.
|
||||
const { values } = useFormikContext();
|
||||
|
||||
// Calculates the total receivable amount from due amount.
|
||||
const receivableFullAmount = useMemo(
|
||||
() => sumBy(values.entries, 'due_amount'),
|
||||
[values.entries],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}>
|
||||
<PaymentReceiveHeaderFields />
|
||||
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_BIG_NUMBERS)}>
|
||||
<div class="big-amount">
|
||||
<span class="big-amount__label">Amount Received</span>
|
||||
<h1 class="big-amount__number">
|
||||
<Money amount={receivableFullAmount} currency={baseCurrency} />
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withSettings(({ organizationSettings }) => ({
|
||||
baseCurrency: organizationSettings?.baseCurrency,
|
||||
})),
|
||||
)(PaymentReceiveFormHeader);
|
||||
@@ -0,0 +1,18 @@
|
||||
import React from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
import { PaymentReceiveFormProvider } from './PaymentReceiveFormProvider';
|
||||
import PaymentReceiveForm from './PaymentReceiveForm';
|
||||
|
||||
/**
|
||||
* Payment receive form page.
|
||||
*/
|
||||
export default function PaymentReceiveFormPage() {
|
||||
const { id: paymentReceiveId } = useParams();
|
||||
|
||||
return (
|
||||
<PaymentReceiveFormProvider paymentReceiveId={paymentReceiveId}>
|
||||
<PaymentReceiveForm paymentReceiveId={paymentReceiveId} />
|
||||
</PaymentReceiveFormProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import { DashboardInsider } from 'components';
|
||||
import {
|
||||
useSettings,
|
||||
usePaymentReceive,
|
||||
useAccounts,
|
||||
useCustomers,
|
||||
useCreatePaymentReceive,
|
||||
useEditPaymentReceive
|
||||
} from 'hooks/query';
|
||||
|
||||
// Payment receive form context.
|
||||
const PaymentReceiveFormContext = createContext();
|
||||
|
||||
/**
|
||||
* Payment receive form provider.
|
||||
*/
|
||||
function PaymentReceiveFormProvider({ paymentReceiveId, ...props }) {
|
||||
// Fetches payment recevie details.
|
||||
const {
|
||||
data: paymentReceive,
|
||||
isLoading: isPaymentLoading,
|
||||
isFetching: isPaymentFetching,
|
||||
} = usePaymentReceive(paymentReceiveId, {
|
||||
enabled: !!paymentReceiveId,
|
||||
});
|
||||
|
||||
// Handle fetch accounts data.
|
||||
const { data: accounts, isFetching: isAccountsFetching } = useAccounts();
|
||||
|
||||
// Fetch payment made settings.
|
||||
const fetchSettings = useSettings();
|
||||
|
||||
// Fetches customers list.
|
||||
const {
|
||||
data: { customers },
|
||||
isFetching: isCustomersFetching,
|
||||
} = useCustomers();
|
||||
|
||||
const [submitPayload, setSubmitPayload] = React.useState({});
|
||||
const isNewMode = !paymentReceiveId;
|
||||
|
||||
// Create and edit payment receive mutations.
|
||||
const { mutateAsync: editPaymentReceiveMutate } = useEditPaymentReceive();
|
||||
const { mutateAsync: createPaymentReceiveMutate } = useCreatePaymentReceive();
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
paymentReceive,
|
||||
accounts,
|
||||
customers,
|
||||
|
||||
isPaymentLoading,
|
||||
isPaymentFetching,
|
||||
isAccountsFetching,
|
||||
isCustomersFetching,
|
||||
|
||||
submitPayload,
|
||||
setSubmitPayload,
|
||||
isNewMode,
|
||||
|
||||
editPaymentReceiveMutate,
|
||||
createPaymentReceiveMutate
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={
|
||||
isPaymentLoading ||
|
||||
isAccountsFetching ||
|
||||
isCustomersFetching
|
||||
}
|
||||
name={'payment-receive-form'}
|
||||
>
|
||||
<PaymentReceiveFormContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const usePaymentReceiveFormContext = () =>
|
||||
useContext(PaymentReceiveFormContext);
|
||||
|
||||
export { PaymentReceiveFormProvider, usePaymentReceiveFormContext };
|
||||
@@ -0,0 +1,223 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import {
|
||||
FormGroup,
|
||||
InputGroup,
|
||||
Position,
|
||||
ControlGroup,
|
||||
} from '@blueprintjs/core';
|
||||
import { DateInput } from '@blueprintjs/datetime';
|
||||
import { FormattedMessage as T } from 'react-intl';
|
||||
import { FastField, useFormikContext } from 'formik';
|
||||
import { sumBy } from 'lodash';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import classNames from 'classnames';
|
||||
import { momentFormatter, tansformDateValue, inputIntent } from 'utils';
|
||||
import {
|
||||
AccountsSelectList,
|
||||
ContactSelecetList,
|
||||
ErrorMessage,
|
||||
FieldRequiredHint,
|
||||
Icon,
|
||||
InputPrependButton,
|
||||
MoneyInputGroup,
|
||||
InputPrependText,
|
||||
Hint,
|
||||
Money,
|
||||
} from 'components';
|
||||
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
|
||||
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import withDialogActions from 'containers/Dialog/withDialogActions';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
/**
|
||||
* Payment receive header fields.
|
||||
*/
|
||||
function PaymentReceiveHeaderFields({ baseCurrency }) {
|
||||
// Payment receive form context.
|
||||
const { customers, accounts, isNewMode } = usePaymentReceiveFormContext();
|
||||
|
||||
// Formik form context.
|
||||
const { values } = useFormikContext();
|
||||
|
||||
const fullAmountReceived = useMemo(
|
||||
() => sumBy(values.entries, 'payment_amount'),
|
||||
[values.entries],
|
||||
);
|
||||
|
||||
const handleReceiveFullAmountClick = () => {};
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
|
||||
{/* ------------- Customer name ------------- */}
|
||||
<FastField name={'customer_id'}>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'customer_name'} />}
|
||||
inline={true}
|
||||
className={classNames('form-group--select-list', 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={(value) => {
|
||||
form.setFieldValue('customer_id', value);
|
||||
}}
|
||||
popoverFill={true}
|
||||
disabled={!isNewMode}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ------------- Payment date ------------- */}
|
||||
<FastField name={'payment_date'}>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'payment_date'} />}
|
||||
inline={true}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
className={classNames('form-group--select-list', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="payment_date" />}
|
||||
>
|
||||
<DateInput
|
||||
{...momentFormatter('YYYY/MM/DD')}
|
||||
value={tansformDateValue(value)}
|
||||
// onChange={handleDateChange('payment_date')}
|
||||
popoverProps={{ position: Position.BOTTOM, minimal: true }}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ------------ Full amount ------------ */}
|
||||
<FastField name={'customer_name'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'full_amount'} />}
|
||||
inline={true}
|
||||
className={('form-group--full-amount', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
labelInfo={<Hint />}
|
||||
helperText={<ErrorMessage name="full_amount" />}
|
||||
>
|
||||
<ControlGroup>
|
||||
<InputPrependText text={baseCurrency} />
|
||||
<MoneyInputGroup
|
||||
inputGroupProps={{
|
||||
medium: true,
|
||||
...field,
|
||||
}}
|
||||
/>
|
||||
</ControlGroup>
|
||||
|
||||
<a
|
||||
onClick={handleReceiveFullAmountClick}
|
||||
href="#"
|
||||
className={'receive-full-amount'}
|
||||
>
|
||||
Receive full amount (
|
||||
<Money amount={fullAmountReceived} currency={baseCurrency} />)
|
||||
</a>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ------------ Payment receive no. ------------ */}
|
||||
<FastField name={'payment_receive_no'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'payment_receive_no'} />}
|
||||
inline={true}
|
||||
className={('form-group--payment_receive_no', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="payment_receive_no" />}
|
||||
>
|
||||
<ControlGroup fill={true}>
|
||||
<InputGroup
|
||||
intent={inputIntent({ error, touched })}
|
||||
minimal={true}
|
||||
{...field}
|
||||
/>
|
||||
<InputPrependButton
|
||||
buttonProps={{
|
||||
// onClick: handlePaymentReceiveNumberChange,
|
||||
icon: <Icon icon={'settings-18'} />,
|
||||
}}
|
||||
tooltip={true}
|
||||
tooltipProps={{
|
||||
content: 'Setting your auto-generated Payment Receive number',
|
||||
position: Position.BOTTOM_LEFT,
|
||||
}}
|
||||
/>
|
||||
</ControlGroup>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ------------ Deposit account ------------ */}
|
||||
<FastField name={'deposit_account_id'}>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'deposit_to'} />}
|
||||
className={classNames(
|
||||
'form-group--deposit_account_id',
|
||||
'form-group--select-list',
|
||||
CLASSES.FILL,
|
||||
)}
|
||||
inline={true}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name={'deposit_account_id'} />}
|
||||
>
|
||||
<AccountsSelectList
|
||||
accounts={accounts}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
onAccountSelected={(account) => {
|
||||
form.setFieldValue('deposit_account_id', account.id);
|
||||
}}
|
||||
defaultSelectText={<T id={'select_deposit_account'} />}
|
||||
selectedAccountId={value}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ------------ Reference No. ------------ */}
|
||||
<FastField name={'customer_name'}>
|
||||
{({ 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
|
||||
intent={inputIntent({ error, touched })}
|
||||
minimal={true}
|
||||
{...field}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withSettings(({ organizationSettings }) => ({
|
||||
baseCurrency: organizationSettings?.baseCurrency,
|
||||
})),
|
||||
withDialogActions,
|
||||
)(PaymentReceiveHeaderFields);
|
||||
@@ -0,0 +1,137 @@
|
||||
import React, { useState, useMemo, useEffect, useCallback } from 'react';
|
||||
import { CloudLoadingIndicator } from 'components';
|
||||
import { useQuery } from 'react-query';
|
||||
import { omit } from 'lodash';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
import withInvoices from '../Invoice/withInvoices';
|
||||
import PaymentReceiveItemsTableEditor from './PaymentReceiveItemsTableEditor';
|
||||
import withInvoiceActions from 'containers/Sales/Invoice/withInvoiceActions';
|
||||
|
||||
|
||||
function PaymentReceiveItemsTable({
|
||||
// #ownProps
|
||||
paymentReceiveId,
|
||||
customerId,
|
||||
fullAmount,
|
||||
onUpdateData,
|
||||
paymentReceiveEntries = [],
|
||||
errors,
|
||||
onClickClearAllLines,
|
||||
onFetchEntriesSuccess,
|
||||
|
||||
// #withInvoices
|
||||
customerInvoiceEntries,
|
||||
|
||||
// #withPaymentReceiveActions
|
||||
requestFetchDueInvoices
|
||||
}) {
|
||||
const isNewMode = !paymentReceiveId;
|
||||
|
||||
// Detarmines takes payment receive invoices entries from customer receivable
|
||||
// invoices or associated payment receive invoices.
|
||||
const computedTableData = useMemo(() => [
|
||||
...(!isNewMode ? (paymentReceiveEntries || []) : []),
|
||||
...(isNewMode ? (customerInvoiceEntries || []) : []),
|
||||
], [
|
||||
isNewMode,
|
||||
paymentReceiveEntries,
|
||||
customerInvoiceEntries,
|
||||
]);
|
||||
|
||||
const [tableData, setTableData] = useState(computedTableData);
|
||||
const [localEntries, setLocalEntries] = useState(computedTableData);
|
||||
|
||||
const [localAmount, setLocalAmount] = useState(fullAmount);
|
||||
|
||||
useEffect(() => {
|
||||
if (computedTableData !== localEntries) {
|
||||
setTableData(computedTableData);
|
||||
setLocalEntries(computedTableData);
|
||||
}
|
||||
}, [computedTableData, localEntries]);
|
||||
|
||||
// Triggers `onUpdateData` prop event.
|
||||
const triggerUpdateData = useCallback((entries) => {
|
||||
onUpdateData && onUpdateData(entries);
|
||||
}, [onUpdateData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (localAmount !== fullAmount) {
|
||||
let _fullAmount = fullAmount;
|
||||
|
||||
const newTableData = tableData.map((data) => {
|
||||
const amount = Math.min(data?.due_amount, _fullAmount);
|
||||
_fullAmount -= Math.max(amount, 0);
|
||||
|
||||
return {
|
||||
...data,
|
||||
payment_amount: amount,
|
||||
};
|
||||
});
|
||||
setTableData(newTableData);
|
||||
setLocalAmount(fullAmount);
|
||||
triggerUpdateData(newTableData);
|
||||
}
|
||||
}, [
|
||||
fullAmount,
|
||||
localAmount,
|
||||
tableData,
|
||||
triggerUpdateData,
|
||||
]);
|
||||
|
||||
// Fetches customer receivable invoices.
|
||||
const fetchCustomerDueInvoices = useQuery(
|
||||
['customer-due-invoices', customerId],
|
||||
(key, _customerId) => requestFetchDueInvoices(_customerId),
|
||||
{ enabled: isNewMode && customerId },
|
||||
);
|
||||
// No results message.
|
||||
const noResultsMessage = (customerId) ?
|
||||
'There is no receivable invoices for this customer that can be applied for this payment' :
|
||||
'Please select a customer to display all open invoices for it.';
|
||||
|
||||
const triggerOnFetchInvoicesSuccess = useCallback((bills) => {
|
||||
onFetchEntriesSuccess && onFetchEntriesSuccess(bills);
|
||||
}, [onFetchEntriesSuccess])
|
||||
|
||||
// Handle update data.
|
||||
const handleUpdateData = useCallback((rows) => {
|
||||
triggerUpdateData(rows);
|
||||
setTableData(rows);
|
||||
}, [triggerUpdateData]);
|
||||
|
||||
useEffect(() => {
|
||||
const enabled = isNewMode && customerId;
|
||||
|
||||
if (!fetchCustomerDueInvoices.isFetching && enabled) {
|
||||
triggerOnFetchInvoicesSuccess(computedTableData);
|
||||
}
|
||||
}, [
|
||||
isNewMode,
|
||||
customerId,
|
||||
fetchCustomerDueInvoices.isFetching,
|
||||
computedTableData,
|
||||
triggerOnFetchInvoicesSuccess,
|
||||
]);
|
||||
|
||||
return (
|
||||
<CloudLoadingIndicator isLoading={fetchCustomerDueInvoices.isFetching}>
|
||||
<PaymentReceiveItemsTableEditor
|
||||
noResultsMessage={noResultsMessage}
|
||||
data={tableData}
|
||||
errors={errors}
|
||||
onUpdateData={handleUpdateData}
|
||||
onClickClearAllLines={onClickClearAllLines}
|
||||
/>
|
||||
</CloudLoadingIndicator>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withInvoices(({ customerInvoiceEntries }) => ({
|
||||
customerInvoiceEntries,
|
||||
})),
|
||||
withInvoiceActions,
|
||||
)(PaymentReceiveItemsTable);
|
||||
@@ -0,0 +1,172 @@
|
||||
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { Button } from '@blueprintjs/core';
|
||||
import { FormattedMessage as T, useIntl } from 'react-intl';
|
||||
import moment from 'moment';
|
||||
import { sumBy } from 'lodash';
|
||||
import classNames from 'classnames';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { DataTableEditable, Money } from 'components';
|
||||
import { transformUpdatedRows } from 'utils';
|
||||
import {
|
||||
MoneyFieldCell,
|
||||
DivFieldCell,
|
||||
EmptyDiv,
|
||||
} from 'components/DataTableCells';
|
||||
|
||||
/**
|
||||
* Cell renderer guard.
|
||||
*/
|
||||
const CellRenderer = (content, type) => (props) => {
|
||||
if (props.data.length === props.row.index + 1) {
|
||||
return '';
|
||||
}
|
||||
return content(props);
|
||||
};
|
||||
|
||||
const TotalCellRederer = (content, type) => (props) => {
|
||||
if (props.data.length === props.row.index + 1) {
|
||||
return <Money amount={props.cell.row.original[type]} currency={'USD'} />;
|
||||
}
|
||||
return content(props);
|
||||
};
|
||||
|
||||
export default function PaymentReceiveItemsTableEditor({
|
||||
onClickClearAllLines,
|
||||
onUpdateData,
|
||||
data,
|
||||
errors,
|
||||
noResultsMessage,
|
||||
}) {
|
||||
const transformedData = useMemo(() => {
|
||||
const rows = [...data];
|
||||
const totalRow = {
|
||||
due_amount: sumBy(data, 'due_amount'),
|
||||
payment_amount: sumBy(data, 'payment_amount'),
|
||||
};
|
||||
if (rows.length > 0) {
|
||||
rows.push(totalRow);
|
||||
}
|
||||
return rows;
|
||||
}, [data]);
|
||||
|
||||
const [localData, setLocalData] = useState(transformedData);
|
||||
const { formatMessage } = useIntl();
|
||||
|
||||
useEffect(() => {
|
||||
if (localData !== transformedData) {
|
||||
setLocalData(transformedData);
|
||||
}
|
||||
}, [setLocalData, localData, transformedData]);
|
||||
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: '#',
|
||||
accessor: 'index',
|
||||
Cell: ({ row: { index } }) => <span>{index + 1}</span>,
|
||||
width: 40,
|
||||
disableResizing: true,
|
||||
disableSortBy: true,
|
||||
},
|
||||
{
|
||||
Header: formatMessage({ id: 'Date' }),
|
||||
id: 'invoice_date',
|
||||
accessor: (r) => moment(r.invoice_date).format('YYYY MMM DD'),
|
||||
Cell: CellRenderer(EmptyDiv, 'invoice_date'),
|
||||
disableSortBy: true,
|
||||
disableResizing: true,
|
||||
width: 250,
|
||||
},
|
||||
|
||||
{
|
||||
Header: formatMessage({ id: 'invocie_number' }),
|
||||
accessor: (row) => {
|
||||
const invNumber = row?.invoice_no || row?.id;
|
||||
return `#INV-${invNumber || ''}`;
|
||||
},
|
||||
Cell: CellRenderer(EmptyDiv, 'invoice_no'),
|
||||
disableSortBy: true,
|
||||
className: '',
|
||||
},
|
||||
{
|
||||
Header: formatMessage({ id: 'invoice_amount' }),
|
||||
accessor: 'balance',
|
||||
Cell: CellRenderer(DivFieldCell, 'balance'),
|
||||
disableSortBy: true,
|
||||
width: 100,
|
||||
className: '',
|
||||
},
|
||||
{
|
||||
Header: formatMessage({ id: 'amount_due' }),
|
||||
accessor: 'due_amount',
|
||||
Cell: TotalCellRederer(DivFieldCell, 'due_amount'),
|
||||
disableSortBy: true,
|
||||
width: 150,
|
||||
className: '',
|
||||
},
|
||||
{
|
||||
Header: formatMessage({ id: 'payment_amount' }),
|
||||
accessor: 'payment_amount',
|
||||
Cell: TotalCellRederer(MoneyFieldCell, 'payment_amount'),
|
||||
disableSortBy: true,
|
||||
width: 150,
|
||||
className: '',
|
||||
},
|
||||
],
|
||||
[formatMessage],
|
||||
);
|
||||
|
||||
// Handle click clear all lines button.
|
||||
const handleClickClearAllLines = () => {
|
||||
onClickClearAllLines && onClickClearAllLines();
|
||||
};
|
||||
|
||||
const rowClassNames = useCallback(
|
||||
(row) => ({ 'row--total': localData.length === row.index + 1 }),
|
||||
[localData],
|
||||
);
|
||||
|
||||
// Handle update data.
|
||||
const handleUpdateData = useCallback(
|
||||
(rowIndex, columnId, value) => {
|
||||
const newRows = transformUpdatedRows(
|
||||
localData,
|
||||
rowIndex,
|
||||
columnId,
|
||||
value,
|
||||
);
|
||||
if (newRows.length > 0) {
|
||||
newRows.splice(-1, 1);
|
||||
}
|
||||
setLocalData(newRows);
|
||||
onUpdateData && onUpdateData(newRows);
|
||||
},
|
||||
[localData, setLocalData, onUpdateData],
|
||||
);
|
||||
|
||||
return (
|
||||
<DataTableEditable
|
||||
className={classNames(CLASSES.DATATABLE_EDITOR_ITEMS_ENTRIES)}
|
||||
columns={columns}
|
||||
data={localData}
|
||||
rowClassNames={rowClassNames}
|
||||
spinnerProps={false}
|
||||
payload={{
|
||||
errors,
|
||||
updateData: handleUpdateData,
|
||||
}}
|
||||
noResults={noResultsMessage}
|
||||
actions={
|
||||
<Button
|
||||
small={true}
|
||||
className={'button--secondary button--clear-lines'}
|
||||
onClick={handleClickClearAllLines}
|
||||
>
|
||||
<T id={'clear_all_lines'} />
|
||||
</Button>
|
||||
}
|
||||
totalRow={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import moment from 'moment';
|
||||
import { transformToForm } from 'utils';
|
||||
|
||||
// Default payment receive entry.
|
||||
export const defaultPaymentReceiveEntry = {
|
||||
id: '',
|
||||
payment_amount: '',
|
||||
invoice_id: '',
|
||||
due_amount: '',
|
||||
};
|
||||
|
||||
// Form initial values.
|
||||
export const defaultPaymentReceive = {
|
||||
customer_id: '',
|
||||
deposit_account_id: '',
|
||||
payment_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
reference_no: '',
|
||||
payment_receive_no: '',
|
||||
description: '',
|
||||
full_amount: '',
|
||||
entries: [],
|
||||
};
|
||||
|
||||
export const transformToEditForm = (paymentReceive, paymentReceiveEntries) => {
|
||||
return {
|
||||
...transformToForm(paymentReceive, defaultPaymentReceive),
|
||||
entries: [
|
||||
...paymentReceiveEntries.map((paymentReceiveEntry) => ({
|
||||
...transformToForm(paymentReceiveEntry, defaultPaymentReceiveEntry),
|
||||
})),
|
||||
],
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user