chrone: sperate client and server to different repos.

This commit is contained in:
a.bouhuolia
2021-09-21 17:13:53 +02:00
parent e011b2a82b
commit 18df5530c7
10015 changed files with 17686 additions and 97524 deletions

View File

@@ -0,0 +1,31 @@
import React, { lazy } from 'react';
import withDrawers from 'containers/Drawer/withDrawers';
import { Drawer, DrawerSuspense } from 'components';
import { compose } from 'utils';
const PaymentReceiveDrawerContent = lazy(() =>
import('./PaymentReceiveDrawerContent'),
);
/**
* payment receive drawer.
*/
function PaymentReceiveDrawer({
name,
//#withDrawer
isOpen,
payload: { paymentReceiveId },
}) {
return (
<Drawer isOpen={isOpen} name={name}>
<DrawerSuspense>
<PaymentReceiveDrawerContent paymentReceiveId={paymentReceiveId} />
</DrawerSuspense>
</Drawer>
);
}
export default compose(withDrawers())(PaymentReceiveDrawer);

View File

@@ -0,0 +1,17 @@
import React from 'react';
import { PaymentReceiveDrawerProvider } from './PaymentReceiveDrawerProvider';
import PaymentReceivePaper from './PaymentReceivePaper';
/**
* payment receive drawer content.
*/
export default function PaymentReceiveDrawerContent({
// #ownProp
paymentReceiveId,
}) {
return (
<PaymentReceiveDrawerProvider paymentReceiveId={paymentReceiveId}>
<PaymentReceivePaper />
</PaymentReceiveDrawerProvider>
);
}

View File

@@ -0,0 +1,31 @@
import React, { createContext, useContext } from 'react';
import { usePaymentReceive } from 'hooks/query';
import { DrawerHeaderContent, DashboardInsider } from 'components';
const PaymentReceiveDrawerContext = createContext();
function PaymentReceiveDrawerProvider({ paymentReceiveId, ...props }) {
const {
data: paymentReceive,
isFetching: isPaymentReceiveLoading,
} = usePaymentReceive(paymentReceiveId, {
enabled: !!paymentReceiveId,
});
// Provider payload.
const provider = {
paymentReceiveId,
paymentReceive,
};
return (
<DashboardInsider loading={isPaymentReceiveLoading}>
<DrawerHeaderContent name={'payment-receive-drawer'} />
<PaymentReceiveDrawerContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const usePaymentReceiveDrawerContext = () =>
useContext(PaymentReceiveDrawerContext);
export { PaymentReceiveDrawerProvider, usePaymentReceiveDrawerContext };

View File

@@ -0,0 +1,9 @@
import React from 'react';
import PaymentPaperTemplate from 'containers/Drawers/PaymentPaperTemplate/PaymentPaperTemplate';
import { usePaymentReceiveDrawerContext } from './PaymentReceiveDrawerProvider';
export default function PaymentReceivePaper() {
const { paymentReceive } = usePaymentReceiveDrawerContext();
return <PaymentPaperTemplate paperData={paymentReceive} />;
}

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,116 @@
import React from 'react';
import {
Intent,
Button,
ButtonGroup,
Popover,
PopoverInteractionKind,
Position,
Menu,
MenuItem,
} from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
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, submitForm, resetForm } = useFormikContext();
// History context.
const history = useHistory();
// Handle submit button click.
const handleSubmitBtnClick = (event) => {
setSubmitPayload({ redirect: true });
submitForm();
};
// Handle clear button click.
const handleClearBtnClick = (event) => {
resetForm();
};
// Handle cancel button click.
const handleCancelBtnClick = (event) => {
history.goBack();
};
// Handle submit & new button click.
const handleSubmitAndNewClick = (event) => {
setSubmitPayload({ redirect: false, resetForm: true });
submitForm();
};
// Handle submit & continue editing button click.
const handleSubmitContinueEditingBtnClick = (event) => {
setSubmitPayload({ redirect: false, publish: true });
submitForm();
};
return (
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
{/* ----------- Save and New ----------- */}
<ButtonGroup>
<Button
disabled={isSubmitting}
loading={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'}
disabled={isSubmitting}
onClick={handleCancelBtnClick}
text={<T id={'cancel'} />}
/>
</div>
);
}

View File

@@ -0,0 +1,212 @@
import React, { useMemo } from 'react';
import { Formik, Form } from 'formik';
import intl from 'react-intl-universal';
import { omit, sumBy, pick, isEmpty, defaultTo } from 'lodash';
import { Intent } from '@blueprintjs/core';
import classNames from 'classnames';
import { useHistory } from 'react-router-dom';
import 'style/pages/PaymentReceive/PageForm.scss';
import { CLASSES } from 'common/classes';
import PaymentReceiveHeader from './PaymentReceiveFormHeader';
import PaymentReceiveFormBody from './PaymentReceiveFormBody';
import PaymentReceiveFloatingActions from './PaymentReceiveFloatingActions';
import PaymentReceiveFormFooter from './PaymentReceiveFormFooter';
import PaymentReceiveFormAlerts from './PaymentReceiveFormAlerts';
import PaymentReceiveFormDialogs from './PaymentReceiveFormDialogs';
import { PaymentReceiveInnerProvider } from './PaymentReceiveInnerProvider';
import withSettings from 'containers/Settings/withSettings';
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
import {
EditPaymentReceiveFormSchema,
CreatePaymentReceiveFormSchema,
} from './PaymentReceiveForm.schema';
import { AppToaster } from 'components';
import { transactionNumber, compose } from 'utils';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import { defaultPaymentReceive, transformToEditForm } from './utils';
/**
* Payment Receive form.
*/
function PaymentReceiveForm({
// #withSettings
preferredDepositAccount,
paymentReceiveNextNumber,
paymentReceiveNumberPrefix,
paymentReceiveAutoIncrement,
// #withCurrentOrganization
organization: { base_currency },
}) {
const history = useHistory();
// Payment receive form context.
const {
isNewMode,
paymentReceiveEditPage,
paymentEntriesEditPage,
paymentReceiveId,
submitPayload,
editPaymentReceiveMutate,
createPaymentReceiveMutate,
} = usePaymentReceiveFormContext();
// Payment receive number.
const nextPaymentNumber = transactionNumber(
paymentReceiveNumberPrefix,
paymentReceiveNextNumber,
);
// Form initial values.
const initialValues = useMemo(
() => ({
...(!isEmpty(paymentReceiveEditPage)
? transformToEditForm(paymentReceiveEditPage, paymentEntriesEditPage)
: {
...defaultPaymentReceive,
...(paymentReceiveAutoIncrement && {
payment_receive_no: nextPaymentNumber,
deposit_account_id: defaultTo(preferredDepositAccount, ''),
}),
currency_code: base_currency,
}),
}),
[
paymentReceiveEditPage,
nextPaymentNumber,
paymentEntriesEditPage,
paymentReceiveAutoIncrement,
preferredDepositAccount,
],
);
// 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) => ({
...pick(entry, ['invoice_id', 'payment_amount']),
}));
// Calculates the total payment amount of entries.
const totalPaymentAmount = sumBy(entries, 'payment_amount');
if (totalPaymentAmount <= 0) {
AppToaster.show({
message: intl.get('you_cannot_make_payment_with_zero_total_amount'),
intent: Intent.DANGER,
});
return;
}
const form = {
...omit(values, ['payment_receive_no_manually', 'payment_receive_no']),
...(values.payment_receive_no_manually && {
payment_receive_no: values.payment_receive_no,
}),
entries,
};
// Handle request response success.
const onSaved = (response) => {
AppToaster.show({
message: intl.get(
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 = ({
response: {
data: { errors },
},
}) => {
const getError = (errorType) => errors.find((e) => e.type === errorType);
if (getError('PAYMENT_RECEIVE_NO_EXISTS')) {
setFieldError(
'payment_receive_no',
intl.get('payment_number_is_not_unique'),
);
}
if (getError('PAYMENT_RECEIVE_NO_REQUIRED')) {
setFieldError(
'payment_receive_no',
intl.get('payment_receive.field.error.payment_receive_no_required'),
);
}
setSubmitting(false);
};
if (paymentReceiveId) {
editPaymentReceiveMutate([paymentReceiveId, form])
.then(onSaved)
.catch(onError);
} else {
createPaymentReceiveMutate(form).then(onSaved).catch(onError);
}
};
return (
<div
className={classNames(
CLASSES.PAGE_FORM,
CLASSES.PAGE_FORM_STRIP_STYLE,
CLASSES.PAGE_FORM_PAYMENT_RECEIVE,
)}
>
<Formik
initialValues={initialValues}
onSubmit={handleSubmitForm}
validationSchema={
isNewMode
? CreatePaymentReceiveFormSchema
: EditPaymentReceiveFormSchema
}
>
<Form>
<PaymentReceiveInnerProvider>
<PaymentReceiveHeader />
<PaymentReceiveFormBody />
<PaymentReceiveFormFooter />
<PaymentReceiveFloatingActions />
{/* ------- Alerts & Dialogs ------- */}
<PaymentReceiveFormAlerts />
<PaymentReceiveFormDialogs />
</PaymentReceiveInnerProvider>
</Form>
</Formik>
</div>
);
}
export default compose(
withSettings(({ paymentReceiveSettings }) => ({
paymentReceiveSettings,
paymentReceiveNextNumber: paymentReceiveSettings?.nextNumber,
paymentReceiveNumberPrefix: paymentReceiveSettings?.numberPrefix,
paymentReceiveAutoIncrement: paymentReceiveSettings?.autoIncrement,
preferredDepositAccount: paymentReceiveSettings?.depositAccount,
})),
withCurrentOrganization(),
)(PaymentReceiveForm);

View File

@@ -0,0 +1,38 @@
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import { DATATYPES_LENGTH } from 'common/dataTypes';
const Schema = Yup.object().shape({
customer_id: Yup.string()
.label(intl.get('customer_name_'))
.required(),
payment_date: Yup.date()
.required()
.label(intl.get('payment_date_')),
deposit_account_id: Yup.number()
.required()
.label(intl.get('deposit_account_')),
full_amount: Yup.number().nullable(),
payment_receive_no: Yup.string()
.nullable()
.max(DATATYPES_LENGTH.STRING)
.label(intl.get('payment_receive_no_')),
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING).nullable(),
// statement: 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,26 @@
import React from 'react';
import { useFormikContext } from 'formik';
import ClearingAllLinesAlert from 'containers/Alerts/PaymentReceives/ClearingAllLinesAlert';
import { clearAllPaymentEntries } from './utils';
/**
* Payment receive form alerts.
*/
export default function PaymentReceiveFormAlerts() {
const { values: { entries }, setFieldValue } = useFormikContext();
const handleClearingAllLines = () => {
const newEntries = clearAllPaymentEntries(entries);
setFieldValue('entries', newEntries);
setFieldValue('full_amount', '');
};
return (
<>
<ClearingAllLinesAlert
name={'clear-all-lines-payment-receive'}
onConfirm={handleClearingAllLines}
/>
</>
);
}

View File

@@ -0,0 +1,26 @@
import React from 'react';
import { FastField } from 'formik';
import PaymentReceiveItemsTable from './PaymentReceiveItemsTable';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
/**
* Payment Receive form body.
*/
export default function PaymentReceiveFormBody() {
return (
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
<FastField name={'entries'}>
{({ form: { values, setFieldValue }, field: { value } }) => (
<PaymentReceiveItemsTable
entries={value}
onUpdateData={(newEntries) => {
setFieldValue('entries', newEntries);
}}
currencyCode={values.currency_code}
/>
)}
</FastField>
</div>
);
}

View File

@@ -0,0 +1,24 @@
import React from 'react';
import { useFormikContext } from 'formik';
import PaymentReceiveNumberDialog from 'containers/Dialogs/PaymentReceiveNumberDialog';
/**
* Payment receive form dialogs.
*/
export default function PaymentReceiveFormDialogs() {
const { setFieldValue } = useFormikContext();
const handleUpdatePaymentNumber = ({ incrementNumber, manually }) => {
setFieldValue('payment_receive_no', incrementNumber);
setFieldValue('payment_receive_no_manually', manually)
};
return (
<>
<PaymentReceiveNumberDialog
dialogName={'payment-receive-number-form'}
onConfirm={handleUpdatePaymentNumber}
/>
</>
);
}

View File

@@ -0,0 +1,34 @@
import React from 'react';
import classNames from 'classnames';
import { FormGroup, TextArea } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { FastField } from 'formik';
import { Row, Col, Postbox } from 'components';
import { CLASSES } from 'common/classes';
/**
* Payment receive form footer.
*/
export default function PaymentReceiveFormFooter({ getFieldProps }) {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Postbox title={<T id={'payment_receive_details'} />} defaultOpen={false}>
<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>
</Postbox>
</div>
);
}

View File

@@ -0,0 +1,50 @@
import React, { useMemo } from 'react';
import { sumBy } from 'lodash';
import { useFormikContext } from 'formik';
import classNames from 'classnames';
import { Money } from 'components';
import { FormattedMessage as T } from 'components';
import { CLASSES } from 'common/classes';
import PaymentReceiveHeaderFields from './PaymentReceiveHeaderFields';
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
import { compose } from 'utils';
/**
* Payment receive form header.
*/
function PaymentReceiveFormHeader({
// #withCurrentOrganization
organization: { base_currency },
}) {
// Formik form context.
const { values } = useFormikContext();
// Calculates the total payment amount from due amount.
const paymentFullAmount = useMemo(
() => sumBy(values.entries, 'payment_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">
<T id={'amount_received'} />
</span>
<h1 class="big-amount__number">
<Money amount={paymentFullAmount} currency={base_currency} />
</h1>
</div>
</div>
</div>
</div>
);
}
export default compose(withCurrentOrganization())(PaymentReceiveFormHeader);

View File

@@ -0,0 +1,19 @@
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();
const paymentReceiveIdInt = parseInt(paymentReceiveId, 10);
return (
<PaymentReceiveFormProvider paymentReceiveId={paymentReceiveIdInt}>
<PaymentReceiveForm paymentReceiveId={paymentReceiveIdInt} />
</PaymentReceiveFormProvider>
);
}

View File

@@ -0,0 +1,86 @@
import React, { createContext, useContext } from 'react';
import { DashboardInsider } from 'components';
import {
useSettingsPaymentReceives,
usePaymentReceiveEditPage,
useAccounts,
useCustomers,
useCreatePaymentReceive,
useEditPaymentReceive,
} from 'hooks/query';
// Payment receive form context.
const PaymentReceiveFormContext = createContext();
/**
* Payment receive form provider.
*/
function PaymentReceiveFormProvider({ paymentReceiveId, ...props }) {
// Form state.
const [submitPayload, setSubmitPayload] = React.useState({});
// Fetches payment recevie details.
const {
data: {
paymentReceive: paymentReceiveEditPage,
entries: paymentEntriesEditPage,
},
isLoading: isPaymentLoading,
isFetching: isPaymentFetching,
} = usePaymentReceiveEditPage(paymentReceiveId, {
enabled: !!paymentReceiveId,
});
// Handle fetch accounts data.
const { data: accounts, isLoading: isAccountsLoading } = useAccounts();
// Fetch payment made settings.
const fetchSettings = useSettingsPaymentReceives();
// Fetches customers list.
const {
data: { customers },
isLoading: isCustomersLoading,
} = useCustomers({ page_size: 10000 });
// Detarmines whether the new mode.
const isNewMode = !paymentReceiveId;
// Create and edit payment receive mutations.
const { mutateAsync: editPaymentReceiveMutate } = useEditPaymentReceive();
const { mutateAsync: createPaymentReceiveMutate } = useCreatePaymentReceive();
// Provider payload.
const provider = {
paymentReceiveId,
paymentReceiveEditPage,
paymentEntriesEditPage,
accounts,
customers,
isPaymentLoading,
isAccountsLoading,
isPaymentFetching,
isCustomersLoading,
isNewMode,
submitPayload,
setSubmitPayload,
editPaymentReceiveMutate,
createPaymentReceiveMutate,
};
return (
<DashboardInsider
loading={isPaymentLoading || isAccountsLoading || isCustomersLoading}
name={'payment-receive-form'}
>
<PaymentReceiveFormContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const usePaymentReceiveFormContext = () =>
useContext(PaymentReceiveFormContext);
export { PaymentReceiveFormProvider, usePaymentReceiveFormContext };

View File

@@ -0,0 +1,325 @@
import React, { useMemo } from 'react';
import {
FormGroup,
InputGroup,
Position,
ControlGroup,
Button,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FormattedMessage as T } from 'components';
import { FastField, Field, useFormikContext, ErrorMessage } from 'formik';
import { useAutofocus } from 'hooks';
import { CLASSES } from 'common/classes';
import classNames from 'classnames';
import {
compose,
safeSumBy,
momentFormatter,
tansformDateValue,
handleDateChange,
inputIntent,
} from 'utils';
import {
AccountsSelectList,
ContactSelecetList,
FieldRequiredHint,
Icon,
InputPrependButton,
MoneyInputGroup,
InputPrependText,
Hint,
Money,
} from 'components';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import { ACCOUNT_TYPE } from 'common/accountTypes';
import withDialogActions from 'containers/Dialog/withDialogActions';
import withSettings from 'containers/Settings/withSettings';
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
import {
useObservePaymentNoSettings,
amountPaymentEntries,
fullAmountPaymentEntries,
customersFieldShouldUpdate,
accountsFieldShouldUpdate,
} from './utils';
import { toSafeInteger } from 'lodash';
/**
* Payment receive header fields.
*/
function PaymentReceiveHeaderFields({
// #withCurrentOrganization
organization: { base_currency },
// #withDialogActions
openDialog,
// #withSettings
paymentReceiveAutoIncrement,
paymentReceiveNumberPrefix,
paymentReceiveNextNumber,
}) {
// Payment receive form context.
const { customers, accounts, isNewMode } = usePaymentReceiveFormContext();
// Formik form context.
const {
values: { entries },
setFieldValue,
} = useFormikContext();
const customerFieldRef = useAutofocus();
// Calculates the full-amount received.
const totalDueAmount = useMemo(
() => safeSumBy(entries, 'due_amount'),
[entries],
);
// Handle receive full-amount link click.
const handleReceiveFullAmountClick = () => {
const newEntries = fullAmountPaymentEntries(entries);
const fullAmount = safeSumBy(newEntries, 'payment_amount');
setFieldValue('entries', newEntries);
setFieldValue('full_amount', fullAmount);
};
// Handles the full-amount field blur.
const onFullAmountBlur = (value) => {
const newEntries = amountPaymentEntries(toSafeInteger(value), entries);
setFieldValue('entries', newEntries);
};
// Handle click open payment receive number dialog.
const handleClickOpenDialog = () => {
openDialog('payment-receive-number-form');
};
// Handle payment number field blur.
const handlePaymentNoBlur = (form, field) => (event) => {
const newValue = event.target.value;
if (field.value !== newValue && paymentReceiveAutoIncrement) {
openDialog('payment-receive-number-form', {
initialFormValues: {
manualTransactionNo: newValue,
incrementMode: 'manual-transaction',
},
});
}
};
// Syncs payment receive number from settings to the form.
useObservePaymentNoSettings(
paymentReceiveNumberPrefix,
paymentReceiveNextNumber,
);
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('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={(customer) => {
form.setFieldValue('customer_id', customer.id);
form.setFieldValue('full_amount', '');
}}
popoverFill={true}
disabled={!isNewMode}
buttonProps={{
elementRef: (ref) => (customerFieldRef.current = ref),
}}
/>
</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((formattedDate) => {
form.setFieldValue('payment_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
inputProps={{
leftIcon: <Icon icon={'date-range'} />,
}}
/>
</FormGroup>
)}
</FastField>
{/* ------------ Full amount ------------ */}
<Field name={'full_amount'}>
{({
form: { setFieldValue },
field: { value, onChange },
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={base_currency} />
<MoneyInputGroup
value={value}
onChange={(value) => {
setFieldValue('full_amount', value);
}}
onBlurValue={onFullAmountBlur}
/>
</ControlGroup>
<Button
onClick={handleReceiveFullAmountClick}
className={'receive-full-amount'}
small={true}
minimal={true}
>
<T id={'receive_full_amount'} /> (
<Money amount={totalDueAmount} currency={base_currency} />)
</Button>
</FormGroup>
)}
</Field>
{/* ------------ 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}
value={field.value}
asyncControl={true}
onBlur={handlePaymentNoBlur(form, field)}
/>
<InputPrependButton
buttonProps={{
onClick: handleClickOpenDialog,
icon: <Icon icon={'settings-18'} />,
}}
tooltip={true}
tooltipProps={{
content: (
<T
id={'setting_your_auto_generated_payment_receive_number'}
/>
),
position: Position.BOTTOM_LEFT,
}}
/>
</ControlGroup>
</FormGroup>
)}
</FastField>
{/* ------------ Deposit account ------------ */}
<FastField
name={'deposit_account_id'}
accounts={accounts}
shouldUpdate={accountsFieldShouldUpdate}
>
{({ 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}
filterByTypes={[
ACCOUNT_TYPE.CASH,
ACCOUNT_TYPE.BANK,
ACCOUNT_TYPE.OTHER_CURRENT_ASSET,
]}
/>
</FormGroup>
)}
</FastField>
{/* ------------ Reference No. ------------ */}
<FastField name={'reference_no'}>
{({ 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(({ paymentReceiveSettings }) => ({
paymentReceiveNextNumber: paymentReceiveSettings?.nextNumber,
paymentReceiveNumberPrefix: paymentReceiveSettings?.numberPrefix,
paymentReceiveAutoIncrement: paymentReceiveSettings?.autoIncrement,
})),
withDialogActions,
withCurrentOrganization(),
)(PaymentReceiveHeaderFields);

View File

@@ -0,0 +1,50 @@
import React, { createContext, useContext, useEffect } from 'react';
import { useFormikContext } from 'formik';
import { useDueInvoices } from 'hooks/query';
import { transformInvoicesNewPageEntries } from './utils';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import { isEmpty } from 'lodash';
const PaymentReceiveInnerContext = createContext();
/**
* Payment receive inner form provider.
*/
function PaymentReceiveInnerProvider({ ...props }) {
const { isNewMode } = usePaymentReceiveFormContext();
// Formik context.
const {
values: { customer_id: customerId },
setFieldValue,
} = useFormikContext();
// Fetches customer receivable invoices.
const {
data: dueInvoices,
isLoading: isDueInvoicesLoading,
isFetching: isDueInvoicesFetching,
} = useDueInvoices(customerId, {
enabled: !!customerId && isNewMode,
});
useEffect(() => {
if (!isDueInvoicesFetching && dueInvoices && isNewMode) {
setFieldValue('entries', transformInvoicesNewPageEntries(dueInvoices));
}
}, [isDueInvoicesFetching, dueInvoices, isNewMode, setFieldValue]);
// Provider payload.
const provider = {
dueInvoices,
isDueInvoicesLoading,
isDueInvoicesFetching,
};
return <PaymentReceiveInnerContext.Provider value={provider} {...props} />;
}
const usePaymentReceiveInnerContext = () =>
useContext(PaymentReceiveInnerContext);
export { PaymentReceiveInnerProvider, usePaymentReceiveInnerContext };

View File

@@ -0,0 +1,69 @@
import React, { useCallback } from 'react';
import { CloudLoadingIndicator } from 'components';
import classNames from 'classnames';
import { useFormikContext } from 'formik';
import { FormattedMessage as T } from 'components';
import { CLASSES } from 'common/classes';
import { usePaymentReceiveInnerContext } from './PaymentReceiveInnerProvider';
import { DataTableEditable } from 'components';
import { usePaymentReceiveEntriesColumns } from './components';
import { compose, updateTableCell } from 'utils';
/**
* Payment receive items table.
*/
export default function PaymentReceiveItemsTable({
entries,
onUpdateData,
currencyCode,
}) {
// Payment receive form context.
const { isDueInvoicesFetching } = usePaymentReceiveInnerContext();
// Payment receive entries form context.
const columns = usePaymentReceiveEntriesColumns();
// Formik context.
const {
values: { customer_id },
} = useFormikContext();
// No results message.
const noResultsMessage = customer_id ? (
<T id={'there_is_no_receivable_invoices_for_this_customer'} />
) : (
<T id={'please_select_a_customer_to_display_all_open_invoices_for_it'} />
);
// Handle update data.
const handleUpdateData = useCallback(
(rowIndex, columnId, value) => {
const newRows = compose(updateTableCell(rowIndex, columnId, value))(
entries,
);
onUpdateData(newRows);
},
[entries, onUpdateData],
);
return (
<CloudLoadingIndicator isLoading={isDueInvoicesFetching}>
<DataTableEditable
progressBarLoading={isDueInvoicesFetching}
className={classNames(CLASSES.DATATABLE_EDITOR_ITEMS_ENTRIES)}
columns={columns}
data={entries}
spinnerProps={false}
payload={{
errors: [],
updateData: handleUpdateData,
currencyCode,
}}
noResults={noResultsMessage}
footer={true}
/>
</CloudLoadingIndicator>
);
}

View File

@@ -0,0 +1,129 @@
import React from 'react';
import moment from 'moment';
import intl from 'react-intl-universal';
import { Money } from 'components';
import { MoneyFieldCell } from 'components/DataTableCells';
import { safeSumBy, formattedAmount } from 'utils';
/**
* Invoice date cell.
*/
function InvoiceDateCell({ value }) {
return <span>{moment(value).format('YYYY MMM DD')}</span>;
}
/**
* Index table cell.
*/
function IndexCell({ row: { index } }) {
return <span>{index + 1}</span>;
}
/**
* Invoice number table cell accessor.
*/
function InvNumberCellAccessor(row) {
return row?.invoice_no ? `#${row?.invoice_no || ''}` : '-';
}
/**
* Balance footer cell.
*/
function BalanceFooterCell({ payload: { currencyCode }, rows }) {
const total = safeSumBy(rows, 'original.amount');
return <span>{formattedAmount(total, currencyCode)}</span>;
}
/**
* Due amount footer cell.
*/
function DueAmountFooterCell({ payload: { currencyCode }, rows }) {
const totalDueAmount = safeSumBy(rows, 'original.due_amount');
return <span>{formattedAmount(totalDueAmount, currencyCode)}</span>;
}
/**
* Payment amount footer cell.
*/
function PaymentAmountFooterCell({ payload: { currencyCode }, rows }) {
const totalPaymentAmount = safeSumBy(rows, 'original.payment_amount');
return <span>{formattedAmount(totalPaymentAmount, currencyCode)}</span>;
}
/**
* Mobey table cell.
*/
function MoneyTableCell({ row: { original }, value }) {
return <Money amount={value} currency={original.currency_code} />;
}
function DateFooterCell() {
return intl.get('total')
}
/**
* Retrieve payment receive form entries columns.
*/
export const usePaymentReceiveEntriesColumns = () => {
return React.useMemo(
() => [
{
Header: '#',
accessor: 'index',
Cell: IndexCell,
width: 40,
disableResizing: true,
disableSortBy: true,
className: 'index',
},
{
Header: intl.get('Date'),
id: 'invoice_date',
accessor: 'invoice_date',
Cell: InvoiceDateCell,
Footer: DateFooterCell,
disableSortBy: true,
disableResizing: true,
width: 250,
className: 'date',
},
{
Header: intl.get('invocie_number'),
accessor: InvNumberCellAccessor,
disableSortBy: true,
className: 'invoice_number',
},
{
Header: intl.get('invoice_amount'),
accessor: 'amount',
Footer: BalanceFooterCell,
Cell: MoneyTableCell,
disableSortBy: true,
width: 100,
className: 'invoice_amount',
},
{
Header: intl.get('amount_due'),
accessor: 'due_amount',
Footer: DueAmountFooterCell,
Cell: MoneyTableCell,
disableSortBy: true,
width: 150,
className: 'amount_due',
},
{
Header: intl.get('payment_amount'),
accessor: 'payment_amount',
Cell: MoneyFieldCell,
Footer: PaymentAmountFooterCell,
disableSortBy: true,
width: 150,
className: 'payment_amount',
},
],
[],
);
};

View File

@@ -0,0 +1,126 @@
import React from 'react';
import { useFormikContext } from 'formik';
import moment from 'moment';
import {
defaultFastFieldShouldUpdate,
transactionNumber,
transformToForm,
safeSumBy,
} from 'utils';
// Default payment receive entry.
export const defaultPaymentReceiveEntry = {
payment_amount: '',
invoice_id: '',
invoice_no: '',
due_amount: '',
date: '',
amount: '',
currency_code: '',
};
// 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: '',
statement: '',
full_amount: '',
currency_code: '',
entries: [],
};
/**
*
*/
export const transformToEditForm = (paymentReceive, paymentReceiveEntries) => ({
...transformToForm(paymentReceive, defaultPaymentReceive),
full_amount: safeSumBy(paymentReceiveEntries, 'payment_amount'),
entries: [
...paymentReceiveEntries.map((paymentReceiveEntry) => ({
...transformToForm(paymentReceiveEntry, defaultPaymentReceiveEntry),
payment_amount: paymentReceiveEntry.payment_amount || '',
})),
],
});
/**
* Transformes the given invoices to the new page receivable entries.
*/
export const transformInvoicesNewPageEntries = (invoices) => [
...invoices.map((invoice, index) => ({
index: index + 1,
invoice_id: invoice.id,
entry_type: 'invoice',
due_amount: invoice.due_amount,
date: invoice.invoice_date,
amount: invoice.balance,
currency_code: invoice.currency_code,
payment_amount: '',
invoice_no: invoice.invoice_no,
total_payment_amount: invoice.payment_amount,
})),
];
export const transformEntriesToEditForm = (receivableEntries) => [
...transformInvoicesNewPageEntries([...(receivableEntries || [])]),
];
export const clearAllPaymentEntries = (entries) => [
...entries.map((entry) => ({ ...entry, payment_amount: 0 })),
];
export const amountPaymentEntries = (amount, entries) => {
let total = amount;
return entries.map((item) => {
const diff = Math.min(item.due_amount, total);
total -= Math.max(diff, 0);
return {
...item,
payment_amount: diff,
};
});
};
export const fullAmountPaymentEntries = (entries) => {
return entries.map((item) => ({
...item,
payment_amount: item.due_amount,
}));
};
/**
* Syncs payment receive number settings with form.
*/
export const useObservePaymentNoSettings = (prefix, nextNumber) => {
const { setFieldValue } = useFormikContext();
React.useEffect(() => {
const invoiceNo = transactionNumber(prefix, nextNumber);
setFieldValue('payment_receive_no', invoiceNo);
}, [setFieldValue, prefix, nextNumber]);
};
/**
* Detarmines the customers fast-field should update.
*/
export const customersFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.customers !== oldProps.customers ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Detarmines the accounts fast-field should update.
*/
export const accountsFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.accounts !== oldProps.accounts ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};

View File

@@ -0,0 +1,79 @@
import React from 'react';
import { MenuItem } from '@blueprintjs/core';
import intl from 'react-intl-universal';
import { RESOURCES_TYPES } from "../../../common/resourcesTypes";
import withDrawerActions from "../../Drawer/withDrawerActions";
import { highlightText } from 'utils';
import { Icon } from 'components';
/**
* Payment receive universal search item select action.
*/
function PaymentReceiveUniversalSearchSelectComponent({
// #ownProps
resourceType,
resourceId,
// #withDrawerActions
openDrawer,
}) {
if (resourceType === RESOURCES_TYPES.PAYMENT_RECEIVE) {
openDrawer('payment-receive-detail-drawer', { paymentReceiveId: resourceId });
}
return null;
}
export const PaymentReceiveUniversalSearchSelect = withDrawerActions(
PaymentReceiveUniversalSearchSelectComponent,
);
/**
* Payment receive universal search item.
*/
export function PaymentReceiveUniversalSearchItem(
item,
{ handleClick, modifiers, query },
) {
return (
<MenuItem
active={modifiers.active}
text={
<div>
<div>{highlightText(item.text, query)}</div>
<span class="bp3-text-muted">
{highlightText(item.reference.payment_receive_no, query)}{' '}
<Icon icon={'caret-right-16'} iconSize={16} />
{highlightText(item.reference.formatted_payment_date, query)}
</span>
</div>
}
label={<div class="amount">{item.reference.formatted_amount}</div>}
onClick={handleClick}
className={'universal-search__item--invoice'}
/>
);
}
/**
* Transformes payment receives to search.
*/
const paymentReceivesToSearch = (payment) => ({
id: payment.id,
text: payment.customer.display_name,
subText: payment.formatted_payment_date,
label: payment.formatted_amount,
reference: payment,
});
/**
* Binds universal search payment receive configure.
*/
export const universalSearchPaymentReceiveBind = () => ({
resourceType: RESOURCES_TYPES.PAYMENT_RECEIVE,
optionItemLabel: intl.get('payment_receives'),
selectItemAction: PaymentReceiveUniversalSearchSelect,
itemRenderer: PaymentReceiveUniversalSearchItem,
itemSelect: paymentReceivesToSearch,
});

View File

@@ -0,0 +1,75 @@
import React, { createContext, useContext } from 'react';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import {
useResourceViews,
useResourceMeta,
usePaymentReceives,
} from 'hooks/query';
import { isTableEmptyStatus, getFieldsFromResourceMeta } 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: resourceMeta,
isLoading: isResourceLoading,
isFetching: isResourceFetching,
} = useResourceMeta('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,
resourceMeta,
fields: getFieldsFromResourceMeta(resourceMeta.fields),
paymentReceivesViews,
isPaymentReceivesLoading,
isPaymentReceivesFetching,
isResourceFetching,
isResourceLoading,
isViewsLoading,
isEmptyStatus,
};
return (
<DashboardInsider
loading={isViewsLoading || isResourceLoading}
name={'payment-receives-list'}
>
<PaymentReceivesListContext.Provider value={state} {...props} />
</DashboardInsider>
);
}
const usePaymentReceivesListContext = () =>
useContext(PaymentReceivesListContext);
export { PaymentReceivesListProvider, usePaymentReceivesListContext };

View File

@@ -0,0 +1,136 @@
import React from 'react';
import Icon from 'components/Icon';
import {
Button,
Classes,
NavbarDivider,
NavbarGroup,
Intent,
Alignment,
} from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import {
DashboardFilterButton,
AdvancedFilterPopover,
FormattedMessage as T,
} from 'components';
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';
import { useRefreshPaymentReceive } from 'hooks/query/paymentReceives';
/**
* Payment receives actions bar.
*/
function PaymentReceiveActionsBar({
// #withPaymentReceivesActions
setPaymentReceivesTableState,
// #withPaymentReceives
paymentFilterConditions
}) {
// History context.
const history = useHistory();
// Payment receives list context.
const { paymentReceivesViews, fields } = usePaymentReceivesListContext();
// Handle new payment button click.
const handleClickNewPaymentReceive = () => {
history.push('/payment-receives/new');
};
// Payment receive refresh action.
const { refresh } = useRefreshPaymentReceive();
// Handle tab changing.
const handleTabChange = (viewId) => {
setPaymentReceivesTableState({ customViewId: viewId.id || null });
};
// Handle click a refresh payment receives
const handleRefreshBtnClick = () => {
refresh();
};
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}
/>
<AdvancedFilterPopover
advancedFilterProps={{
conditions: paymentFilterConditions,
defaultFieldKey: 'payment_receive_no',
fields: fields,
onFilterChange: (filterConditions) => {
setPaymentReceivesTableState({ filterRoles: filterConditions });
},
}}
>
<DashboardFilterButton
conditionsCount={paymentFilterConditions.length}
/>
</AdvancedFilterPopover>
<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>
<NavbarGroup align={Alignment.RIGHT}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon="refresh-16" iconSize={14} />}
onClick={handleRefreshBtnClick}
/>
</NavbarGroup>
</DashboardActionsBar>
);
}
export default compose(
withPaymentReceivesActions,
withPaymentReceives(({ paymentReceivesTableState }) => ({
paymentReceivesTableState,
paymentFilterConditions: paymentReceivesTableState.filterRoles,
})),
)(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 'components';
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';
import { FormattedMessage as T } from 'components';
export default function PaymentReceivesEmptyStatus() {
const history = useHistory();
return (
<EmptyStatus
title={<T id={'the_organization_doesn_t_receive_money_yet'} />}
description={
<p>
<T id={'receiving_customer_payments_is_one_pleasant_accounting_tasks'} />
</p>
}
action={
<>
<Button
intent={Intent.PRIMARY}
large={true}
onClick={() => {
history.push('/payment-receives/new');
}}
>
<T id={'new_payment_receive'} />
</Button>
<Button intent={Intent.NONE} large={true}>
<T id={'learn_more'} />
</Button>
</>
}
/>
);
}

View File

@@ -0,0 +1,61 @@
import React from 'react';
import 'style/pages/PaymentReceive/List.scss';
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 withPaymentReceives from './withPaymentReceives';
import withPaymentReceivesActions from './withPaymentReceivesActions';
import { compose, transformTableStateToQuery } from 'utils';
/**
* Payment receives list.
*/
function PaymentReceiveList({
// #withPaymentReceives
paymentReceivesTableState,
paymentsTableStateChanged,
// #withPaymentReceivesActions
resetPaymentReceivesTableState,
}) {
// Resets the payment receives table state once the page unmount.
React.useEffect(
() => () => {
resetPaymentReceivesTableState();
},
[resetPaymentReceivesTableState],
);
return (
<PaymentReceivesListProvider
query={transformTableStateToQuery(paymentReceivesTableState)}
tableStateChanged={paymentsTableStateChanged}
>
<PaymentReceiveActionsBar />
<DashboardPageContent>
<PaymentReceiveViewTabs />
<PaymentReceivesTable />
</DashboardPageContent>
<PaymentReceiveAlerts />
</PaymentReceivesListProvider>
);
}
export default compose(
withPaymentReceives(
({ paymentReceivesTableState, paymentsTableStateChanged }) => ({
paymentReceivesTableState,
paymentsTableStateChanged,
}),
),
withPaymentReceivesActions,
)(PaymentReceiveList);

View File

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

View File

@@ -0,0 +1,141 @@
import React, { useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import { compose } from 'utils';
import { TABLES } from 'common/tables';
import { DataTable, DashboardContentTable } from 'components';
import PaymentReceivesEmptyStatus from './PaymentReceivesEmptyStatus';
import TableSkeletonRows from 'components/Datatable/TableSkeletonRows';
import TableSkeletonHeader from 'components/Datatable/TableHeaderSkeleton';
import withPaymentReceives from './withPaymentReceives';
import withPaymentReceivesActions from './withPaymentReceivesActions';
import withAlertsActions from 'containers/Alert/withAlertActions';
import withDrawerActions from 'containers/Drawer/withDrawerActions';
import { usePaymentReceivesColumns, ActionsMenu } from './components';
import { usePaymentReceivesListContext } from './PaymentReceiptsListProvider';
import { useMemorizedColumnsWidths } from 'hooks';
/**
* Payment receives datatable.
*/
function PaymentReceivesDataTable({
// #withPaymentReceivesActions
setPaymentReceivesTableState,
// #withPaymentReceives
paymentReceivesTableState,
// #withAlertsActions
openAlert,
// #withDrawerActions
openDrawer,
}) {
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 drawer payment receive.
const handleDrawerPaymentReceive = ({ id }) => {
openDrawer('payment-receive-drawer', { paymentReceiveId: id });
};
// Handle view detail payment receive..
const handleViewDetailPaymentReceive = ({ id }) => {
openDrawer('payment-receive-detail-drawer', { paymentReceiveId: id });
};
// Handle cell click.
const handleCellClick = (cell, event) => {
openDrawer('payment-receive-detail-drawer', {
paymentReceiveId: cell.row.original.id,
});
};
// Local storage memorizing columns widths.
const [initialColumnsWidths, , handleColumnResizing] =
useMemorizedColumnsWidths(TABLES.PAYMENT_RECEIVES);
// 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 (
<DashboardContentTable>
<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}
onCellClick={handleCellClick}
initialColumnsWidths={initialColumnsWidths}
onColumnResizing={handleColumnResizing}
payload={{
onDelete: handleDeletePaymentReceive,
onEdit: handleEditPaymentReceive,
onDrawer: handleDrawerPaymentReceive,
onViewDetails: handleViewDetailPaymentReceive,
}}
/>
</DashboardContentTable>
);
}
export default compose(
withPaymentReceivesActions,
withAlertsActions,
withDrawerActions,
withPaymentReceives(({ paymentReceivesTableState }) => ({
paymentReceivesTableState,
})),
)(PaymentReceivesDataTable);

View File

@@ -0,0 +1,140 @@
import React from 'react';
import {
Intent,
Button,
Popover,
Menu,
MenuItem,
MenuDivider,
Position,
} from '@blueprintjs/core';
import intl from 'react-intl-universal';
import clsx from 'classnames';
import { FormatDateCell, Money, Icon } from 'components';
import { safeCallback } from 'utils';
import { CLASSES } from '../../../../common/classes';
/**
* Table actions menu.
*/
export function ActionsMenu({
row: { original: paymentReceive },
payload: { onEdit, onDelete, onDrawer, onViewDetails },
}) {
return (
<Menu>
<MenuItem
icon={<Icon icon="reader-18" />}
text={intl.get('view_details')}
onClick={safeCallback(onViewDetails, paymentReceive)}
/>
<MenuDivider />
<MenuItem
icon={<Icon icon="pen-18" />}
text={intl.get('edit_payment_receive')}
onClick={safeCallback(onEdit, paymentReceive)}
/>
<MenuItem
icon={<Icon icon={'receipt-24'} iconSize={16} />}
text={intl.get('payment_receive_paper')}
onClick={safeCallback(onDrawer, paymentReceive)}
/>
<MenuItem
text={intl.get('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={row.currency_code} />;
}
/**
* 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() {
return React.useMemo(
() => [
{
id: 'payment_date',
Header: intl.get('payment_date'),
accessor: 'payment_date',
Cell: FormatDateCell,
width: 140,
className: 'payment_date',
clickable: true,
textOverview: true,
},
{
id: 'customer',
Header: intl.get('customer_name'),
accessor: 'customer.display_name',
width: 160,
className: 'customer_id',
clickable: true,
textOverview: true,
},
{
id: 'amount',
Header: intl.get('amount'),
accessor: AmountAccessor,
width: 120,
align: 'right',
clickable: true,
textOverview: true,
className: clsx(CLASSES.FONT_BOLD),
},
{
id: 'payment_receive_no',
Header: intl.get('payment_receive_no'),
accessor: (row) =>
row.payment_receive_no ? `${row.payment_receive_no}` : null,
width: 140,
className: 'payment_receive_no',
clickable: true,
textOverview: true,
},
{
id: 'deposit_account',
Header: intl.get('deposit_account'),
accessor: 'deposit_account.name',
width: 140,
className: 'deposit_account_id',
clickable: true,
textOverview: true,
},
{
id: 'reference_no',
Header: intl.get('reference_no'),
accessor: 'reference_no',
width: 140,
className: 'reference_no',
clickable: true,
textOverview: true,
},
],
[],
);
}

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,19 @@
import { connect } from 'react-redux';
import {
getPaymentReceiveTableStateFactory,
paymentsTableStateChangedFactory
} from 'store/PaymentReceives/paymentReceives.selector';
export default (mapState) => {
const getPaymentReceiveTableState = getPaymentReceiveTableStateFactory();
const paymentsTableStateChanged = paymentsTableStateChangedFactory();
const mapStateToProps = (state, props) => {
const mapped = {
paymentReceivesTableState: getPaymentReceiveTableState(state, props),
paymentsTableStateChanged: paymentsTableStateChanged(state, props),
};
return mapState ? mapState(mapped, state, props) : mapped;
};
return connect(mapStateToProps);
};

View File

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