refactoring: WIP payment receive and made form.

This commit is contained in:
a.bouhuolia
2021-02-16 14:03:43 +02:00
parent f6456db592
commit a75177b9d1
47 changed files with 1331 additions and 1723 deletions

View File

@@ -0,0 +1,13 @@
import React from 'react';
import PaymentReceiveDeleteAlert from 'containers/Alerts/PaymentReceives/PaymentReceiveDeleteAlert';
/**
* PaymentReceives alert.
*/
export default function EstimatesAlerts() {
return (
<div>
<PaymentReceiveDeleteAlert name={'payment-receive-delete'} />
</div>
);
}

View File

@@ -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>
);
}

View File

@@ -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);

View File

@@ -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;

View File

@@ -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>
);
}

View File

@@ -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);

View File

@@ -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>
);
}

View File

@@ -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 };

View File

@@ -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);

View File

@@ -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);

View File

@@ -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}
/>
);
}

View File

@@ -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),
})),
],
};
};

View File

@@ -0,0 +1,70 @@
import React, { createContext, useContext } from 'react';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import {
useResourceViews,
useResourceFields,
usePaymentReceives,
} from 'hooks/query';
import { isTableEmptyStatus } from 'utils';
const PaymentReceivesListContext = createContext();
/**
* Payment receives list data provider.
*/
function PaymentReceivesListProvider({ query, ...props }) {
// Fetch payment receives resource views and fields.
const {
data: paymentReceivesViews,
isFetching: isViewsLoading,
} = useResourceViews('payment_receives');
// Fetch the payment receives resource fields.
const {
data: paymentReceivesFields,
isFetching: isFieldsLoading,
} = useResourceFields('payment_receives');
// Fetch payment receives list according to the given custom view id.
const {
data: { paymentReceives, pagination, filterMeta },
isLoading: isPaymentReceivesLoading,
isFetching: isPaymentReceivesFetching,
} = usePaymentReceives(query);
// Detarmines the datatable empty status.
const isEmptyStatus =
isTableEmptyStatus({
data: paymentReceives,
pagination,
filterMeta,
}) && !isPaymentReceivesLoading;
// Provider payload.
const state = {
paymentReceives,
pagination,
paymentReceivesFields,
paymentReceivesViews,
isPaymentReceivesLoading,
isPaymentReceivesFetching,
isFieldsLoading,
isViewsLoading,
isEmptyStatus,
};
return (
<DashboardInsider
loading={isViewsLoading || isFieldsLoading}
name={'payment-receives'}
>
<PaymentReceivesListContext.Provider value={state} {...props} />
</DashboardInsider>
);
}
const usePaymentReceivesListContext = () =>
useContext(PaymentReceivesListContext);
export { PaymentReceivesListProvider, usePaymentReceivesListContext };

View File

@@ -0,0 +1,112 @@
import React from 'react';
import Icon from 'components/Icon';
import {
Button,
Classes,
Popover,
NavbarDivider,
NavbarGroup,
PopoverInteractionKind,
Position,
Intent,
} from '@blueprintjs/core';
import classNames from 'classnames';
import { useHistory } from 'react-router-dom';
import { FormattedMessage as T } from 'react-intl';
import DashboardActionsBar from 'components/Dashboard/DashboardActionsBar';
import { If, DashboardActionViewsList } from 'components';
import withPaymentReceivesActions from './withPaymentReceivesActions';
import withPaymentReceives from './withPaymentReceives';
import { compose } from 'utils';
import { usePaymentReceivesListContext } from './PaymentReceiptsListProvider';
/**
* Payment receives actions bar.
*/
function PaymentReceiveActionsBar({
// #withPaymentReceivesActions
setPaymentReceivesTableState,
}) {
// History context.
const history = useHistory();
// Payment receives list context.
const { paymentReceivesViews } = usePaymentReceivesListContext();
// Handle new payment button click.
const handleClickNewPaymentReceive = () => {
history.push('/payment-receives/new');
};
// Handle tab changing.
const handleTabChange = (viewId) => {
setPaymentReceivesTableState({ customViewId: viewId.id || null });
};
return (
<DashboardActionsBar>
<NavbarGroup>
<DashboardActionViewsList
resourceName={'payment_receives'}
views={paymentReceivesViews}
onChange={handleTabChange}
/>
<NavbarDivider />
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'plus'} />}
text={<T id={'new_payment_receive'} />}
onClick={handleClickNewPaymentReceive}
/>
<Popover
minimal={true}
// content={filterDropdown}
interactionKind={PopoverInteractionKind.CLICK}
position={Position.BOTTOM_LEFT}
>
<Button
className={classNames(Classes.MINIMAL)}
text={<T id={'filter'} />}
icon={<Icon icon={'filter-16'} iconSize={16} />}
/>
</Popover>
<If condition={false}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'trash-16'} iconSize={16} />}
text={<T id={'delete'} />}
intent={Intent.DANGER}
// onClick={handleBulkDelete}
/>
</If>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'print-16'} iconSize={'16'} />}
text={<T id={'print'} />}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'file-import-16'} />}
text={<T id={'import'} />}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'file-export-16'} iconSize={'16'} />}
text={<T id={'export'} />}
/>
</NavbarGroup>
</DashboardActionsBar>
);
}
export default compose(
withPaymentReceivesActions,
withPaymentReceives(({ paymentReceivesTableState }) => ({
paymentReceivesTableState,
})),
)(PaymentReceiveActionsBar);

View File

@@ -0,0 +1,64 @@
import React from 'react';
import { useHistory } from 'react-router';
import { Alignment, Navbar, NavbarGroup } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
import { pick } from 'lodash';
import { DashboardViewsTabs } from 'components';
import withPaymentReceives from './withPaymentReceives';
import withPaymentReceivesActions from './withPaymentReceivesActions';
import { usePaymentReceivesListContext } from './PaymentReceiptsListProvider';
import { compose } from 'utils';
/**
* Payment receive view tabs.
*/
function PaymentReceiveViewTabs({
// #withPaymentReceivesActions
addPaymentReceivesTableQueries,
// #withPaymentReceives
paymentReceivesTableState,
}) {
const history = useHistory();
const { paymentReceivesViews, ...res } = usePaymentReceivesListContext();
const tabs = paymentReceivesViews.map((view) => ({
...pick(view, ['name', 'id']),
}));
// Handles click a new view tab.
const handleClickNewView = () => {
history.push('/custom_views/payment-receives/new');
};
// Handles the active tab chaing.
const handleTabsChange = (customView) => {
addPaymentReceivesTableQueries({
customViewId: customView || null,
});
};
return (
<Navbar className={'navbar--dashboard-views'}>
<NavbarGroup align={Alignment.LEFT}>
<DashboardViewsTabs
customViewId={paymentReceivesTableState.customViewId}
tabs={tabs}
defaultTabText={<T id={'all_payments'} />}
onNewViewTabClick={handleClickNewView}
onChange={handleTabsChange}
/>
</NavbarGroup>
</Navbar>
);
}
export default compose(
withPaymentReceivesActions,
withPaymentReceives(({ paymentReceivesTableState }) => ({
paymentReceivesTableState,
})),
)(PaymentReceiveViewTabs);

View File

@@ -0,0 +1,37 @@
import React from 'react';
import { Button, Intent } from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import { EmptyStatus } from 'components';
export default function PaymentReceivesEmptyStatus() {
const history = useHistory();
return (
<EmptyStatus
title={"The organization does't receive money, yet!"}
description={
<p>
It is a long established fact that a reader will be distracted by the
readable content of a page when looking at its layout.
</p>
}
action={
<>
<Button
intent={Intent.PRIMARY}
large={true}
onClick={() => {
history.push('/payment-receives/new');
}}
>
New payment receive
</Button>
<Button intent={Intent.NONE} large={true}>
Learn more
</Button>
</>
}
/>
);
}

View File

@@ -0,0 +1,57 @@
import React, { useEffect } from 'react';
import { useIntl } from 'react-intl';
import { DashboardContentTable, DashboardPageContent } from 'components';
import PaymentReceiveActionsBar from './PaymentReceiveActionsBar';
import PaymentReceiveAlerts from '../PaymentReceiveAlerts';
import { PaymentReceivesListProvider } from './PaymentReceiptsListProvider';
import PaymentReceiveViewTabs from './PaymentReceiveViewTabs';
import PaymentReceivesTable from './PaymentReceivesTable';
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withPaymentReceives from './withPaymentReceives';
import { compose, transformTableStateToQuery } from 'utils';
/**
* Payment receives list.
*/
function PaymentReceiveList({
// #withDashboardActions
changePageTitle,
// #withPaymentReceives
paymentReceivesTableState,
}) {
const { formatMessage } = useIntl();
// Changes the dashboard page title once the page mount.
useEffect(() => {
changePageTitle(formatMessage({ id: 'payment_Receives_list' }));
}, [changePageTitle, formatMessage]);
return (
<PaymentReceivesListProvider
query={transformTableStateToQuery(paymentReceivesTableState)}
>
<PaymentReceiveActionsBar />
<DashboardPageContent>
<PaymentReceiveViewTabs />
<DashboardContentTable>
<PaymentReceivesTable />
</DashboardContentTable>
</DashboardPageContent>
<PaymentReceiveAlerts />
</PaymentReceivesListProvider>
);
}
export default compose(
withDashboardActions,
withPaymentReceives(({ paymentReceivesTableState }) => ({
paymentReceivesTableState,
})),
)(PaymentReceiveList);

View File

@@ -0,0 +1,60 @@
import React, { createContext } from 'react';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import {
useResourceViews,
useResourceFields,
usePaymentReceives,
} from 'hooks/query';
const PaymentReceivesListContext = createContext();
/**
* Payment receives data provider.
*/
function PaymentReceivesListProvider({ query, ...props }) {
// Fetch accounts resource views and fields.
const {
data: paymentReceivesViews,
isFetching: isViewsLoading,
} = useResourceViews('payment_receives');
// Fetch the accounts resource fields.
const {
data: paymentReceivesFields,
isFetching: isFieldsLoading,
} = useResourceFields('payment_receives');
// Fetch accounts list according to the given custom view id.
const {
data: { paymentReceives, pagination, filterMeta },
isLoading: isPaymentReceivesLoading,
isFetching: isPaymentReceivesFetching,
} = usePaymentReceives(query);
// Provider payload.
const provider = {
paymentReceives,
paymentReceivesViews,
paymentReceivesFields,
pagination,
isViewsLoading,
isFieldsLoading,
isPaymentReceivesLoading,
isPaymentReceivesFetching
};
return (
<DashboardInsider
loading={isViewsLoading || isFieldsLoading}
name={'payment_receives'}
>
<PaymentReceivesListContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const usePaymentReceivesListContext = () =>
React.useContext(PaymentReceivesListContext);
export { PaymentReceivesListProvider, usePaymentReceivesListContext };

View File

@@ -0,0 +1,104 @@
import React, { useCallback } from 'react';
import classNames from 'classnames';
import { compose } from 'utils';
import { useHistory } from 'react-router-dom';
import { CLASSES } from 'common/classes';
import PaymentReceivesEmptyStatus from './PaymentReceivesEmptyStatus';
import { DataTable } from 'components';
import TableSkeletonRows from 'components/Datatable/TableSkeletonRows';
import TableSkeletonHeader from 'components/Datatable/TableHeaderSkeleton';
import withAlertsActions from 'containers/Alert/withAlertActions';
import withPaymentReceivesActions from './withPaymentReceivesActions';
import withSettings from 'containers/Settings/withSettings';
import { usePaymentReceivesColumns, ActionsMenu } from './components';
import { usePaymentReceivesListContext } from './PaymentReceiptsListProvider';
/**
* Payment receives datatable.
*/
function PaymentReceivesDataTable({
// #withPaymentReceivesActions
setPaymentReceivesTableState,
// #withAlertsActions
openAlert,
}) {
const history = useHistory();
// Payment receives list context.
const {
paymentReceives,
pagination,
isPaymentReceivesLoading,
isPaymentReceivesFetching,
isEmptyStatus,
} = usePaymentReceivesListContext();
// Payment receives columns.
const columns = usePaymentReceivesColumns();
// Handles edit payment receive.
const handleEditPaymentReceive = ({ id }) => {
history.push(`/payment-receives/${id}/edit`);
};
// Handles delete payment receive.
const handleDeletePaymentReceive = ({ id }) => {
openAlert('payment-receive-delete', { paymentReceiveId: id });
};
// Handle datatable fetch once the table's state changing.
const handleDataTableFetchData = useCallback(
({ pageIndex, pageSize, sortBy }) => {
setPaymentReceivesTableState({
pageIndex,
pageSize,
sortBy,
});
},
[setPaymentReceivesTableState],
);
// Display empty status instead of the table.
if (isEmptyStatus) {
return <PaymentReceivesEmptyStatus />;
}
return (
<DataTable
columns={columns}
data={paymentReceives}
loading={isPaymentReceivesLoading}
headerLoading={isPaymentReceivesLoading}
progressBarLoading={isPaymentReceivesFetching}
onFetchData={handleDataTableFetchData}
manualSortBy={true}
selectionColumn={true}
noInitialFetch={true}
sticky={true}
autoResetSortBy={false}
autoResetPage={false}
pagination={true}
pagesCount={pagination.pagesCount}
TableLoadingRenderer={TableSkeletonRows}
TableHeaderSkeletonRenderer={TableSkeletonHeader}
ContextMenu={ActionsMenu}
payload={{
onDelete: handleDeletePaymentReceive,
onEdit: handleEditPaymentReceive,
}}
/>
);
}
export default compose(
withPaymentReceivesActions,
withAlertsActions,
withSettings(({ organizationSettings }) => ({
baseCurrency: organizationSettings?.baseCurrency,
})),
)(PaymentReceivesDataTable);

View File

@@ -0,0 +1,137 @@
import React from 'react';
import {
Intent,
Button,
Popover,
Menu,
MenuItem,
MenuDivider,
Position,
} from '@blueprintjs/core';
import { FormattedMessage as T, useIntl } from 'react-intl';
import moment from 'moment';
import { Money, Icon } from 'components';
import { safeCallback } from 'utils';
/**
* Table actions menu.
*/
export function ActionsMenu({
row: { original: paymentReceive },
payload: { onEdit, onDelete },
}) {
const { formatMessage } = useIntl();
return (
<Menu>
<MenuItem
icon={<Icon icon="reader-18" />}
text={formatMessage({ id: 'view_details' })}
/>
<MenuDivider />
<MenuItem
icon={<Icon icon="pen-18" />}
text={formatMessage({ id: 'edit_payment_receive' })}
onClick={safeCallback(onEdit, paymentReceive)}
/>
<MenuItem
text={formatMessage({ id: 'delete_payment_receive' })}
intent={Intent.DANGER}
onClick={safeCallback(onDelete, paymentReceive)}
icon={<Icon icon="trash-16" iconSize={16} />}
/>
</Menu>
);
}
/**
* Amount accessor.
*/
export function AmountAccessor(row) {
return <Money amount={row.amount} currency={'USD'} />;
}
/**
* Payment date accessor.
*/
export function PaymentDateAccessor(row) {
return moment(row.payment_date).format('YYYY MMM DD');
}
/**
* Actions cell.
*/
export function ActionsCell(props) {
return (
<Popover
content={<ActionsMenu {...props} />}
position={Position.RIGHT_BOTTOM}
>
<Button icon={<Icon icon="more-h-16" iconSize={16} />} />
</Popover>
);
}
/**
* Retrieve payment receives columns.
*/
export function usePaymentReceivesColumns() {
const { formatMessage } = useIntl();
return React.useMemo(
() => [
{
id: 'payment_date',
Header: formatMessage({ id: 'payment_date' }),
accessor: PaymentDateAccessor,
width: 140,
className: 'payment_date',
},
{
id: 'customer_id',
Header: formatMessage({ id: 'customer_name' }),
accessor: 'customer.display_name',
width: 140,
className: 'customer_id',
},
{
id: 'payment_receive_no',
Header: formatMessage({ id: 'payment_receive_no' }),
accessor: (row) =>
row.payment_receive_no ? `#${row.payment_receive_no}` : null,
width: 140,
className: 'payment_receive_no',
},
{
id: 'amount',
Header: formatMessage({ id: 'amount' }),
accessor: AmountAccessor,
width: 140,
className: 'amount',
},
{
id: 'reference_no',
Header: formatMessage({ id: 'reference_no' }),
accessor: 'reference_no',
width: 140,
className: 'reference_no',
},
{
id: 'deposit_account_id',
Header: formatMessage({ id: 'deposit_account' }),
accessor: 'deposit_account.name',
width: 140,
className: 'deposit_account_id',
},
{
id: 'actions',
Header: '',
Cell: ActionsCell,
className: 'actions',
width: 50,
disableResizing: true,
},
],
[formatMessage],
);
}

View File

@@ -0,0 +1,16 @@
import { connect } from 'react-redux';
import {
getPaymentReceiveByIdFactory,
getPaymentReceiveEntriesFactory,
} from 'store/PaymentReceive/paymentReceive.selector';
export default () => {
const getPaymentReceiveById = getPaymentReceiveByIdFactory();
const getPaymentReceiveEntries = getPaymentReceiveEntriesFactory();
const mapStateToProps = (state, props) => ({
paymentReceive: getPaymentReceiveById(state, props),
paymentReceiveEntries: getPaymentReceiveEntries(state, props),
});
return connect(mapStateToProps);
};

View File

@@ -0,0 +1,16 @@
import { connect } from 'react-redux';
import {
getPaymentReceiveTableStateFactory
} from 'store/PaymentReceives/paymentReceives.selector';
export default (mapState) => {
const getPaymentReceiveTableState = getPaymentReceiveTableStateFactory();
const mapStateToProps = (state, props) => {
const mapped = {
paymentReceivesTableState: getPaymentReceiveTableState(state, props),
};
return mapState ? mapState(mapped, state, props) : mapped;
};
return connect(mapStateToProps);
};

View File

@@ -0,0 +1,9 @@
import { connect } from 'react-redux';
import { setPaymentReceivesTableState } from 'store/PaymentReceives/paymentReceives.actions';
const mapDispatchToProps = (dispatch) => ({
setPaymentReceivesTableState: (state) =>
dispatch(setPaymentReceivesTableState(state)),
});
export default connect(null, mapDispatchToProps);