chore: renmame payment receive term to payment received

This commit is contained in:
Ahmed Bouhuolia
2024-08-13 15:15:07 +02:00
parent 961e4b99e8
commit 038d4dd5a7
67 changed files with 181 additions and 184 deletions

View File

@@ -0,0 +1,43 @@
// @ts-nocheck
import React from 'react';
import { Dialog, DialogSuspense } from '@/components';
import withDialogRedux from '@/components/DialogReduxConnect';
import { compose } from '@/utils';
const PaymentMailDialogContent = React.lazy(
() => import('./PaymentMailDialogContent'),
);
/**
* Payment mail dialog.
*/
function PaymentMailDialog({
dialogName,
payload: {
paymentReceiveId = null,
// Redirects to the payments list on mail submitting.
redirectToPaymentsList = false,
},
isOpen,
}) {
return (
<Dialog
name={dialogName}
title={'Payment Mail'}
isOpen={isOpen}
canEscapeJeyClose={true}
autoFocus={true}
style={{ width: 600 }}
>
<DialogSuspense>
<PaymentMailDialogContent
dialogName={dialogName}
paymentReceiveId={paymentReceiveId}
redirectToPaymentsList={redirectToPaymentsList}
/>
</DialogSuspense>
</Dialog>
);
}
export default compose(withDialogRedux())(PaymentMailDialog);

View File

@@ -0,0 +1,47 @@
// @ts-nocheck
import React, { createContext } from 'react';
import { usePaymentReceiveDefaultOptions } from '@/hooks/query';
import { DialogContent } from '@/components';
interface PaymentMailDialogBootValues {
paymentReceiveId: number;
mailOptions: any;
}
const PaymentMailDialogBootContext =
createContext<PaymentMailDialogBootValues>();
interface PaymentMailDialogBootProps {
paymentReceiveId: number;
redirectToPaymentsList: boolean;
children: React.ReactNode;
}
/**
* Payment mail dialog boot provider.
*/
function PaymentMailDialogBoot({
paymentReceiveId,
...props
}: PaymentMailDialogBootProps) {
const { data: mailOptions, isLoading: isMailOptionsLoading } =
usePaymentReceiveDefaultOptions(paymentReceiveId);
const provider = {
mailOptions,
isMailOptionsLoading,
paymentReceiveId,
redirectToPaymentsList
};
return (
<DialogContent isLoading={isMailOptionsLoading}>
<PaymentMailDialogBootContext.Provider value={provider} {...props} />
</DialogContent>
);
}
const usePaymentMailDialogBoot = () =>
React.useContext<PaymentMailDialogBootValues>(PaymentMailDialogBootContext);
export { PaymentMailDialogBoot, usePaymentMailDialogBoot };

View File

@@ -0,0 +1,22 @@
import { PaymentMailDialogBoot } from './PaymentMailDialogBoot';
import { PaymentMailDialogForm } from './PaymentMailDialogForm';
interface PaymentMailDialogContentProps {
dialogName: string;
paymentReceiveId: number;
redirectToPaymentsList: boolean;
}
export default function PaymentMailDialogContent({
dialogName,
paymentReceiveId,
redirectToPaymentsList,
}: PaymentMailDialogContentProps) {
return (
<PaymentMailDialogBoot
paymentReceiveId={paymentReceiveId}
redirectToPaymentsList={redirectToPaymentsList}
>
<PaymentMailDialogForm />
</PaymentMailDialogBoot>
);
}

View File

@@ -0,0 +1,87 @@
// @ts-nocheck
import { Formik, FormikBag } from 'formik';
import * as R from 'ramda';
import { Intent } from '@blueprintjs/core';
import { usePaymentMailDialogBoot } from './PaymentMailDialogBoot';
import { DialogsName } from '@/constants/dialogs';
import { useSendPaymentReceiveMail } from '@/hooks/query';
import { PaymentMailDialogFormContent } from './PaymentMailDialogFormContent';
import {
MailNotificationFormValues,
initialMailNotificationValues,
transformMailFormToRequest,
transformMailFormToInitialValues,
} from '@/containers/SendMailNotification/utils';
import { AppToaster } from '@/components';
import { useHistory } from 'react-router-dom';
import withDialogActions from '@/containers/Dialog/withDialogActions';
const initialFormValues = {
...initialMailNotificationValues,
attachPayment: true,
};
interface PaymentMailFormValue extends MailNotificationFormValues {
attachPayment: boolean;
}
export function PaymentMailDialogFormRoot({
// #withDialogActions
closeDialog,
}) {
const { mailOptions, paymentReceiveId, redirectToPaymentsList } =
usePaymentMailDialogBoot();
const { mutateAsync: sendPaymentMail } = useSendPaymentReceiveMail();
const history = useHistory();
const initialValues = transformMailFormToInitialValues(
mailOptions,
initialFormValues,
);
// Handles the form submitting.
const handleSubmit = (
values: PaymentMailFormValue,
{ setSubmitting }: FormikBag<PaymentMailFormValue>,
) => {
const reqValues = transformMailFormToRequest(values);
setSubmitting(true);
sendPaymentMail([paymentReceiveId, reqValues])
.then(() => {
AppToaster.show({
message: 'The mail notification has been sent successfully.',
intent: Intent.SUCCESS,
});
setSubmitting(false);
closeDialog(DialogsName.PaymentMail);
// Redirects to payments list if the option is enabled.
if (redirectToPaymentsList) {
history.push('/payments-received');
}
})
.catch(() => {
AppToaster.show({
message: 'Something went wrong.',
intent: Intent.DANGER,
});
setSubmitting(false);
closeDialog(DialogsName.PaymentMail);
});
};
const handleClose = () => {
closeDialog(DialogsName.PaymentMail);
};
return (
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
<PaymentMailDialogFormContent onClose={handleClose} />
</Formik>
);
}
export const PaymentMailDialogForm = R.compose(withDialogActions)(
PaymentMailDialogFormRoot,
);

View File

@@ -0,0 +1,66 @@
// @ts-nocheck
import { Form, useFormikContext } from 'formik';
import { Button, Classes, Intent } from '@blueprintjs/core';
import styled from 'styled-components';
import { FFormGroup, FSwitch } from '@/components';
import { MailNotificationForm } from '@/containers/SendMailNotification';
import { saveInvoke } from '@/utils';
import { usePaymentMailDialogBoot } from './PaymentMailDialogBoot';
interface PaymentMailDialogFormContentProps {
onClose?: () => void;
}
export function PaymentMailDialogFormContent({
onClose,
}: PaymentMailDialogFormContentProps) {
const { mailOptions } = usePaymentMailDialogBoot();
const { isSubmitting } = useFormikContext();
const handleClose = () => {
saveInvoke(onClose);
};
return (
<Form>
<div className={Classes.DIALOG_BODY}>
<MailNotificationForm
fromAddresses={mailOptions.from_addresses}
toAddresses={mailOptions.to_addresses}
/>
<AttachFormGroup name={'attachPayment'} inline>
<FSwitch name={'attachPayment'} label={'Attach Payment'} />
</AttachFormGroup>
</div>
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button
disabled={isSubmitting}
onClick={handleClose}
style={{ minWidth: '65px' }}
>
Close
</Button>
<Button
intent={Intent.PRIMARY}
loading={isSubmitting}
style={{ minWidth: '75px' }}
type="submit"
>
Send
</Button>
</div>
</div>
</Form>
);
}
const AttachFormGroup = styled(FFormGroup)`
background: #f8f9fb;
margin-top: 0.6rem;
padding: 4px 14px;
border-radius: 5px;
border: 1px solid #dcdcdd;
`;

View File

@@ -0,0 +1 @@
export * from './PaymentMailDialog';

View File

@@ -0,0 +1,114 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import {
Intent,
Button,
ButtonGroup,
Popover,
PopoverInteractionKind,
Position,
Menu,
MenuItem,
} from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import { Group, Icon, FormattedMessage as T } from '@/components';
import { useFormikContext } from 'formik';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import { CLASSES } from '@/constants/classes';
/**
* 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 });
};
// 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 (
<Group
spacing={10}
className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}
>
{/* ----------- Save and New ----------- */}
<ButtonGroup>
<Button
disabled={isSubmitting}
loading={isSubmitting}
intent={Intent.PRIMARY}
type="submit"
onClick={handleSubmitBtnClick}
style={{ minWidth: '85px' }}
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'} />}
/>
</Group>
);
}

View File

@@ -0,0 +1,37 @@
// @ts-nocheck
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import { DATATYPES_LENGTH } from '@/constants/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_received_no_')),
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING).nullable(),
// statement: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
branch_id: Yup.string(),
exchange_rate: Yup.number(),
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,217 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import { isEmpty, defaultTo } from 'lodash';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { Formik, Form } from 'formik';
import { useHistory } from 'react-router-dom';
import { Intent } from '@blueprintjs/core';
import '@/style/pages/PaymentReceive/PageForm.scss';
import { CLASSES } from '@/constants/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 PaymentReceiveFormTopBar from './PaymentReceiveFormTopBar';
import { PaymentReceiveInnerProvider } from './PaymentReceiveInnerProvider';
import withSettings from '@/containers/Settings/withSettings';
import withCurrentOrganization from '@/containers/Organization/withCurrentOrganization';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import {
EditPaymentReceiveFormSchema,
CreatePaymentReceiveFormSchema,
} from './PaymentReceiveForm.schema';
import { AppToaster } from '@/components';
import { transactionNumber, compose } from '@/utils';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import {
defaultPaymentReceive,
transformToEditForm,
transformFormToRequest,
transformErrors,
resetFormState,
getExceededAmountFromValues,
} from './utils';
import { PaymentReceiveSyncIncrementSettingsToForm } from './components';
/**
* Payment Receive form.
*/
function PaymentReceiveForm({
// #withSettings
preferredDepositAccount,
paymentReceiveNextNumber,
paymentReceiveNumberPrefix,
paymentReceiveAutoIncrement,
// #withCurrentOrganization
organization: { base_currency },
// #withDialogActions
openDialog,
}) {
const history = useHistory();
// Payment receive form context.
const {
isNewMode,
paymentReceiveEditPage,
paymentEntriesEditPage,
paymentReceiveId,
submitPayload,
editPaymentReceiveMutate,
createPaymentReceiveMutate,
isExcessConfirmed,
} = usePaymentReceiveFormContext();
// Payment receive number.
const nextPaymentNumber = transactionNumber(
paymentReceiveNumberPrefix,
paymentReceiveNextNumber,
);
// Form initial values.
const initialValues = useMemo(
() => ({
...(!isEmpty(paymentReceiveEditPage)
? transformToEditForm(paymentReceiveEditPage, paymentEntriesEditPage)
: {
...defaultPaymentReceive,
// If the auto-increment mode is enabled, take the next payment
// number from the settings.
...(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);
const exceededAmount = getExceededAmountFromValues(values);
// Validates the amount should be bigger than zero.
if (values.amount <= 0) {
AppToaster.show({
message: intl.get('you_cannot_make_payment_with_zero_total_amount'),
intent: Intent.DANGER,
});
setSubmitting(false);
return;
}
// Show the confirm popup if the excessed amount bigger than zero and
// excess confirmation has not been confirmed yet.
if (exceededAmount > 0 && !isExcessConfirmed) {
setSubmitting(false);
openDialog('payment-received-excessed-payment');
return;
}
// Transformes the form values to request body.
const form = transformFormToRequest(values);
// Handle request response success.
const onSaved = () => {
setSubmitting(false);
AppToaster.show({
message: intl.get(
paymentReceiveId
? 'the_payment_received_transaction_has_been_edited'
: 'the_payment_received_transaction_has_been_created',
),
intent: Intent.SUCCESS,
});
if (submitPayload.redirect) {
history.push('/payments-received');
}
if (submitPayload.resetForm) {
resetFormState({ resetForm, initialValues, values });
}
};
// Handle request response errors.
const onError = ({
response: {
data: { errors },
},
}) => {
if (errors) {
transformErrors(errors, { setFieldError });
}
setSubmitting(false);
};
if (paymentReceiveId) {
return editPaymentReceiveMutate([paymentReceiveId, form])
.then(onSaved)
.catch(onError);
} else {
return 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>
<PaymentReceiveFormTopBar />
<PaymentReceiveHeader />
<PaymentReceiveFormBody />
<PaymentReceiveFormFooter />
<PaymentReceiveFloatingActions />
{/* ------- Effects ------- */}
<PaymentReceiveSyncIncrementSettingsToForm />
{/* ------- 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?.preferredDepositAccount,
})),
withCurrentOrganization(),
withDialogActions,
)(PaymentReceiveForm);

View File

@@ -0,0 +1,27 @@
// @ts-nocheck
import React from 'react';
import { useFormikContext } from 'formik';
import ClearingAllLinesAlert from '@/containers/Alerts/PaymentReceived/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,27 @@
// @ts-nocheck
import React from 'react';
import { FastField } from 'formik';
import PaymentReceiveItemsTable from './PaymentReceiveItemsTable';
import classNames from 'classnames';
import { CLASSES } from '@/constants/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,22 @@
// @ts-nocheck
import React from 'react';
import { BaseCurrency, BaseCurrencyRoot } from '@/components';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
/**
* Payment reecevie form currnecy tag.
* @returns
*/
export default function PaymentReceiveFormCurrencyTag() {
const { isForeignCustomer, selectCustomer } = usePaymentReceiveFormContext();
if (!isForeignCustomer) {
return null;
}
return (
<BaseCurrencyRoot>
<BaseCurrency currency={selectCustomer?.currency_code} />
</BaseCurrencyRoot>
);
}

View File

@@ -0,0 +1,33 @@
// @ts-nocheck
import React from 'react';
import { useFormikContext } from 'formik';
import PaymentReceiveNumberDialog from '@/containers/Dialogs/PaymentReceiveNumberDialog';
import { ExcessPaymentDialog } from './dialogs/ExcessPaymentDialog';
/**
* Payment receive form dialogs.
*/
export default function PaymentReceiveFormDialogs() {
const { setFieldValue } = useFormikContext();
const handleUpdatePaymentNumber = (settings) => {
// Set the payment transaction no. that cames from dialog to the form.
// the `payment_receive_no_manually` will be empty except the increment mode is not auto.
setFieldValue('payment_receive_no', settings.transactionNumber);
setFieldValue('payment_receive_no_manually', '');
if (settings.incrementMode !== 'auto') {
setFieldValue('payment_receive_no_manually', settings.transactionNumber);
}
};
return (
<>
<PaymentReceiveNumberDialog
dialogName={'payment-receive-number-form'}
onConfirm={handleUpdatePaymentNumber}
/>
<ExcessPaymentDialog dialogName={'payment-received-excessed-payment'} />
</>
);
}

View File

@@ -0,0 +1,36 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import styled from 'styled-components';
import { CLASSES } from '@/constants/classes';
import { Row, Col, Paper } from '@/components';
import { PaymentReceiveFormFootetLeft } from './PaymentReceiveFormFootetLeft';
import { PaymentReceiveFormFootetRight } from './PaymentReceiveFormFootetRight';
import { UploadAttachmentButton } from '@/containers/Attachments/UploadAttachmentButton';
/**
* Payment receive form footer.
*/
export default function PaymentReceiveFormFooter() {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<PaymentReceiveFooterPaper>
<Row>
<Col md={8}>
<PaymentReceiveFormFootetLeft />
<UploadAttachmentButton />
</Col>
<Col md={4}>
<PaymentReceiveFormFootetRight />
</Col>
</Row>
</PaymentReceiveFooterPaper>
</div>
);
}
const PaymentReceiveFooterPaper = styled(Paper)`
padding: 20px;
`;

View File

@@ -0,0 +1,39 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import styled from 'styled-components';
import { FFormGroup, FEditableText, FormattedMessage as T } from '@/components';
export function PaymentReceiveFormFootetLeft() {
return (
<React.Fragment>
{/* --------- Internal Note--------- */}
<TermsConditsFormGroup
name={'statement'}
label={<T id={'payment_receive_form.label.note'} />}
fastField={true}
>
<FEditableText
name={'statement'}
placeholder={intl.get(
'payment_receive_form.internal_note.placeholder',
)}
fastField
multiline
/>
</TermsConditsFormGroup>
</React.Fragment>
);
}
const TermsConditsFormGroup = styled(FFormGroup)`
&.bp4-form-group {
.bp4-label {
font-size: 12px;
margin-bottom: 12px;
}
.bp4-form-content {
margin-left: 10px;
}
}
`;

View File

@@ -0,0 +1,45 @@
// @ts-nocheck
import React from 'react';
import styled from 'styled-components';
import {
T,
TotalLines,
TotalLine,
TotalLineBorderStyle,
TotalLineTextStyle,
FormatNumber,
} from '@/components';
import {
usePaymentReceiveTotals,
usePaymentReceivedTotalExceededAmount,
} from './utils';
export function PaymentReceiveFormFootetRight() {
const { formattedSubtotal, formattedTotal } = usePaymentReceiveTotals();
const exceededAmount = usePaymentReceivedTotalExceededAmount();
return (
<PaymentReceiveTotalLines labelColWidth={'180px'} amountColWidth={'180px'}>
<TotalLine
title={<T id={'payment_receive_form.label.subtotal'} />}
value={formattedSubtotal}
borderStyle={TotalLineBorderStyle.None}
/>
<TotalLine
title={<T id={'payment_receive_form.label.total'} />}
value={formattedTotal}
textStyle={TotalLineTextStyle.Bold}
/>
<TotalLine
title={'Exceeded Amount'}
value={<FormatNumber value={exceededAmount} />}
textStyle={TotalLineTextStyle.Regular}
/>
</PaymentReceiveTotalLines>
);
}
const PaymentReceiveTotalLines = styled(TotalLines)`
width: 100%;
color: #555555;
`;

View File

@@ -0,0 +1,50 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import classNames from 'classnames';
import { sumBy } from 'lodash';
import { useFormikContext } from 'formik';
import { Money } from '@/components';
import { FormattedMessage as T } from '@/components';
import { CLASSES } from '@/constants/classes';
import PaymentReceiveHeaderFields from './PaymentReceiveHeaderFields';
/**
* Payment receive form header.
*/
function PaymentReceiveFormHeader() {
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}>
<PaymentReceiveHeaderFields />
<PaymentReceiveFormBigTotal />
</div>
</div>
);
}
/**
* Big total amount of payment receive form.
* @returns {React.ReactNode}
*/
function PaymentReceiveFormBigTotal() {
// Formik form context.
const {
values: { currency_code, amount },
} = useFormikContext();
return (
<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={amount} currency={currency_code} />
</h1>
</div>
</div>
);
}
export default PaymentReceiveFormHeader;

View File

@@ -0,0 +1,20 @@
// @ts-nocheck
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,120 @@
// @ts-nocheck
import React, { createContext, useContext, useState } from 'react';
import { Features } from '@/constants';
import { useFeatureCan } from '@/hooks/state';
import { DashboardInsider } from '@/components';
import { useProjects } from '@/containers/Projects/hooks';
import {
useSettingsPaymentReceives,
usePaymentReceiveEditPage,
useAccounts,
useCustomers,
useBranches,
useCreatePaymentReceive,
useEditPaymentReceive,
} from '@/hooks/query';
// Payment receive form context.
const PaymentReceiveFormContext = createContext();
/**
* Payment receive form provider.
*/
function PaymentReceiveFormProvider({ query, paymentReceiveId, ...props }) {
// Form state.
const [submitPayload, setSubmitPayload] = React.useState({});
// Features guard.
const { featureCan } = useFeatureCan();
const isBranchFeatureCan = featureCan(Features.Branches);
const isProjectsFeatureCan = featureCan(Features.Projects);
// 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 });
// Fetches the branches list.
const {
data: branches,
isLoading: isBranchesLoading,
isSuccess: isBranchesSuccess,
} = useBranches(query, { enabled: isBranchFeatureCan });
// Fetches the projects list.
const {
data: { projects },
isLoading: isProjectsLoading,
} = useProjects({}, { enabled: !!isProjectsFeatureCan });
// Detarmines whether the new mode.
const isNewMode = !paymentReceiveId;
const isFeatureLoading = isBranchesLoading;
// Create and edit payment receive mutations.
const { mutateAsync: editPaymentReceiveMutate } = useEditPaymentReceive();
const { mutateAsync: createPaymentReceiveMutate } = useCreatePaymentReceive();
const [isExcessConfirmed, setIsExcessConfirmed] = useState<boolean>(false);
// Provider payload.
const provider = {
paymentReceiveId,
paymentReceiveEditPage,
paymentEntriesEditPage,
accounts,
customers,
branches,
projects,
isPaymentLoading,
isAccountsLoading,
isPaymentFetching,
isCustomersLoading,
isFeatureLoading,
isBranchesSuccess,
isNewMode,
submitPayload,
setSubmitPayload,
editPaymentReceiveMutate,
createPaymentReceiveMutate,
isExcessConfirmed,
setIsExcessConfirmed,
};
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,61 @@
// @ts-nocheck
import React from 'react';
import { Alignment, NavbarGroup, Classes } from '@blueprintjs/core';
import { useSetPrimaryBranchToForm } from './utils';
import { useFeatureCan } from '@/hooks/state';
import {
BranchSelect,
FeatureCan,
FormTopbar,
DetailsBarSkeletonBase,
FormBranchSelectButton,
} from '@/components';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import { Features } from '@/constants';
/**
* Payment receive from top bar.
* @returns {JSX.Element}
*/
export default function PaymentReceiveFormTopBar() {
// Features guard.
const { featureCan } = useFeatureCan();
// Sets the primary branch to form.
useSetPrimaryBranchToForm();
// Can't display the navigation bar if branches feature is not enabled.
if (!featureCan(Features.Branches)) {
return null;
}
return (
<FormTopbar>
<NavbarGroup align={Alignment.LEFT}>
<FeatureCan feature={Features.Branches}>
<PaymentReceiveFormSelectBranch />
</FeatureCan>
</NavbarGroup>
</FormTopbar>
);
}
/**
* Branch select of payment receive form.
* @returns {JSX.Element}
*/
function PaymentReceiveFormSelectBranch() {
// payment receive form context.
const { branches, isBranchesLoading } = usePaymentReceiveFormContext();
return isBranchesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<BranchSelect
name={'branch_id'}
branches={branches}
input={FormBranchSelectButton}
popoverProps={{ minimal: true }}
fill={false}
/>
);
}

View File

@@ -0,0 +1,287 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import classNames from 'classnames';
import styled from 'styled-components';
import {
FormGroup,
InputGroup,
Position,
Classes,
ControlGroup,
Button,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { isEmpty, toSafeInteger } from 'lodash';
import { FastField, Field, useFormikContext, ErrorMessage } from 'formik';
import {
FeatureCan,
CustomersSelect,
FormattedMessage as T,
} from '@/components';
import { CLASSES } from '@/constants/classes';
import {
safeSumBy,
momentFormatter,
tansformDateValue,
handleDateChange,
inputIntent,
} from '@/utils';
import {
FFormGroup,
AccountsSelect,
FieldRequiredHint,
Icon,
MoneyInputGroup,
InputPrependText,
CustomerDrawerLink,
Hint,
Money,
} from '@/components';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import { ACCOUNT_TYPE } from '@/constants/accountTypes';
import { ProjectsSelect } from '@/containers/Projects/components';
import {
PaymentReceiveExchangeRateInputField,
PaymentReceiveProjectSelectButton,
} from './components';
import {
amountPaymentEntries,
fullAmountPaymentEntries,
customersFieldShouldUpdate,
accountsFieldShouldUpdate,
} from './utils';
import { Features } from '@/constants';
import { PaymentReceivePaymentNoField } from './PaymentReceivePaymentNoField';
/**
* Payment receive header fields.
*/
export default function PaymentReceiveHeaderFields() {
// Payment receive form context.
const { accounts, projects } = usePaymentReceiveFormContext();
// Formik form context.
const {
values: { entries },
setFieldValue,
} = useFormikContext();
// 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);
};
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
{/* ------------- Customer name ------------- */}
<PaymentReceiveCustomerSelect />
{/* ----------- Exchange rate ----------- */}
<PaymentReceiveExchangeRateInputField
name={'exchange_rate'}
formGroupProps={{ label: ' ', inline: true }}
/>
{/* ------------- 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={'amount'}>
{({
form: {
setFieldValue,
values: { currency_code, entries },
},
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={currency_code} />
<MoneyInputGroup
value={value}
onChange={(value) => {
setFieldValue('amount', value);
}}
onBlurValue={onFullAmountBlur}
/>
</ControlGroup>
{!isEmpty(entries) && (
<Button
onClick={handleReceiveFullAmountClick}
className={'receive-full-amount'}
small={true}
minimal={true}
>
<T id={'receive_full_amount'} /> (
<Money amount={totalDueAmount} currency={currency_code} />)
</Button>
)}
</FormGroup>
)}
</Field>
{/* ------------ Payment receive no. ------------ */}
<PaymentReceivePaymentNoField />
{/* ------------ Deposit account ------------ */}
<FFormGroup
name={'deposit_account_id'}
label={<T id={'deposit_to'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
items={accounts}
shouldUpdate={accountsFieldShouldUpdate}
fastField={true}
>
<AccountsSelect
name={'deposit_account_id'}
items={accounts}
labelInfo={<FieldRequiredHint />}
placeholder={<T id={'select_deposit_account'} />}
filterByTypes={[
ACCOUNT_TYPE.CASH,
ACCOUNT_TYPE.BANK,
ACCOUNT_TYPE.OTHER_CURRENT_ASSET,
]}
shouldUpdate={accountsFieldShouldUpdate}
fastField={true}
fill={true}
/>
</FFormGroup>
{/* ------------ 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>
{/*------------ Project name -----------*/}
<FeatureCan feature={Features.Projects}>
<FFormGroup
name={'project_id'}
label={<T id={'payment_receive.project_name.label'} />}
inline={true}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ProjectsSelect
name={'project_id'}
projects={projects}
input={PaymentReceiveProjectSelectButton}
popoverFill={true}
/>
</FFormGroup>
</FeatureCan>
</div>
);
}
const CustomerButtonLink = styled(CustomerDrawerLink)`
font-size: 11px;
margin-top: 6px;
`;
/**
* Customer select field of payment receive form.
* @returns {React.ReactNode}
*/
function PaymentReceiveCustomerSelect() {
// Payment receive form context.
const { customers, isNewMode } = usePaymentReceiveFormContext();
// Formik form context.
const { values, setFieldValue } = useFormikContext();
return (
<FFormGroup
label={<T id={'customer_name'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
name={'customer_id'}
fastField={true}
shouldUpdate={customersFieldShouldUpdate}
shouldUpdateDeps={{ items: customers }}
>
<CustomersSelect
name={'customer_id'}
items={customers}
placeholder={<T id={'select_customer_account'} />}
onItemChange={(customer) => {
setFieldValue('customer_id', customer.id);
setFieldValue('full_amount', '');
setFieldValue('currency_code', customer?.currency_code);
}}
popoverFill={true}
disabled={!isNewMode}
allowCreate={true}
fastField={true}
shouldUpdate={customersFieldShouldUpdate}
shouldUpdateDeps={{ items: customers }}
/>
{values.customer_id && (
<CustomerButtonLink customerId={values.customer_id}>
<T id={'view_customer_details'} />
</CustomerButtonLink>
)}
</FFormGroup>
);
}

View File

@@ -0,0 +1,51 @@
// @ts-nocheck
import React, { createContext, useContext, useEffect } from 'react';
import { useFormikContext } from 'formik';
import { useDueInvoices } from '@/hooks/query';
import { transformInvoicesNewPageEntries } from './utils';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
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,
keepPreviousData: true,
});
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,70 @@
// @ts-nocheck
import React, { useCallback } from 'react';
import classNames from 'classnames';
import { CloudLoadingIndicator } from '@/components';
import { useFormikContext } from 'formik';
import { FormattedMessage as T } from '@/components';
import { CLASSES } from '@/constants/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 },
errors,
} = 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: errors?.entries || [],
updateData: handleUpdateData,
currencyCode,
}}
noResults={noResultsMessage}
/>
</CloudLoadingIndicator>
);
}

View File

@@ -0,0 +1,99 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import { Position, ControlGroup } from '@blueprintjs/core';
import { useFormikContext } from 'formik';
import * as R from 'ramda';
import { FInputGroup, FormattedMessage as T } from '@/components';
import {
FFormGroup,
FieldRequiredHint,
Icon,
InputPrependButton,
} from '@/components';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import withSettings from '@/containers/Settings/withSettings';
/**
* Payment receive number field.
*/
export const PaymentReceivePaymentNoField = R.compose(
withSettings(({ paymentReceiveSettings }) => ({
paymentReceiveAutoIncrement: paymentReceiveSettings?.autoIncrement,
})),
withDialogActions,
)(
({
// #withDialogActions
openDialog,
// #withSettings
paymentReceiveAutoIncrement,
}) => {
const { values, setFieldValue } = useFormikContext();
// Handle click open payment receive number dialog.
const handleClickOpenDialog = () => {
openDialog('payment-receive-number-form');
};
// Handle payment number field blur.
const handlePaymentNoBlur = (event) => {
const newValue = event.target.value;
// Show the confirmation dialog if the value has changed and auto-increment
// mode is enabled.
if (
values.payment_receive_no !== newValue &&
paymentReceiveAutoIncrement
) {
openDialog('payment-receive-number-form', {
initialFormValues: {
onceManualNumber: newValue,
incrementMode: 'manual-transaction',
},
});
}
// Setting the payment number to the form will be manually in case
// auto-increment is disable.
if (!paymentReceiveAutoIncrement) {
setFieldValue('payment_receive_no', newValue);
setFieldValue('payment_receive_no_manually', newValue);
}
};
return (
<FFormGroup
name={'payment_receive_no'}
label={<T id={'payment_received_no'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
>
<ControlGroup fill={true}>
<FInputGroup
name={'payment_receive_no'}
minimal={true}
value={values.payment_receive_no}
asyncControl={true}
onBlur={handlePaymentNoBlur}
onChange={() => {}}
/>
<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>
</FFormGroup>
);
},
);
PaymentReceivePaymentNoField.displayName = 'PaymentReceivePaymentNoField';

View File

@@ -0,0 +1,152 @@
// @ts-nocheck
import React, { useEffect, useLayoutEffect } from 'react';
import moment from 'moment';
import intl from 'react-intl-universal';
import { Button } from '@blueprintjs/core';
import { useFormikContext } from 'formik';
import * as R from 'ramda';
import { Money, ExchangeRateInputGroup, MoneyFieldCell } from '@/components';
import { useCurrentOrganization } from '@/hooks/state';
import { useEstimateIsForeignCustomer } from './utils';
import { transactionNumber } from '@/utils';
import withSettings from '@/containers/Settings/withSettings';
/**
* Invoice date cell.
*/
function InvoiceDateCell({ value }) {
return <span>{moment(value).format('YYYY MMM DD')}</span>;
}
/**
* Invoice number table cell accessor.
*/
function InvNumberCellAccessor(row) {
return row?.invoice_no ? `#${row?.invoice_no || ''}` : '-';
}
/**
* Mobey table cell.
*/
function MoneyTableCell({ row: { original }, value }) {
return <Money amount={value} currency={original.currency_code} />;
}
/**
* Retrieve payment receive form entries columns.
*/
export const usePaymentReceiveEntriesColumns = () => {
return React.useMemo(
() => [
{
Header: 'Invoice date',
id: 'invoice_date',
accessor: 'invoice_date',
Cell: InvoiceDateCell,
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',
Cell: MoneyTableCell,
disableSortBy: true,
width: 100,
className: 'invoice_amount',
},
{
Header: intl.get('amount_due'),
accessor: 'due_amount',
Cell: MoneyTableCell,
disableSortBy: true,
width: 150,
className: 'amount_due',
},
{
Header: intl.get('payment_amount'),
accessor: 'payment_amount',
Cell: MoneyFieldCell,
disableSortBy: true,
width: 150,
className: 'payment_amount',
},
],
[],
);
};
/**
* payment receive exchange rate input field.
* @returns {JSX.Element}
*/
export function PaymentReceiveExchangeRateInputField({ ...props }) {
const currentOrganization = useCurrentOrganization();
const { values } = useFormikContext();
const isForeignCustomer = useEstimateIsForeignCustomer();
// Can't continue if the customer is not foreign.
if (!isForeignCustomer) {
return null;
}
return (
<ExchangeRateInputGroup
fromCurrency={values.currency_code}
toCurrency={currentOrganization.base_currency}
{...props}
/>
);
}
/**
* payment receive project select.
* @returns {JSX.Element}
*/
export function PaymentReceiveProjectSelectButton({ label }) {
return <Button text={label ?? intl.get('select_project')} />;
}
/**
* Syncs the auto-increment settings to payment receive form.
* @returns {React.ReactNode}
*/
export const PaymentReceiveSyncIncrementSettingsToForm = R.compose(
withSettings(({ paymentReceiveSettings }) => ({
paymentReceiveNextNumber: paymentReceiveSettings?.nextNumber,
paymentReceiveNumberPrefix: paymentReceiveSettings?.numberPrefix,
paymentReceiveAutoIncrement: paymentReceiveSettings?.autoIncrement,
})),
)(
({
paymentReceiveNextNumber,
paymentReceiveNumberPrefix,
paymentReceiveAutoIncrement,
}) => {
const { setFieldValue } = useFormikContext();
useLayoutEffect(() => {
if (!paymentReceiveAutoIncrement) return;
setFieldValue(
'payment_receive_no',
transactionNumber(paymentReceiveNumberPrefix, paymentReceiveNextNumber),
);
}, [
setFieldValue,
paymentReceiveNumberPrefix,
paymentReceiveNextNumber,
paymentReceiveAutoIncrement,
]);
return null;
},
);

View File

@@ -0,0 +1,37 @@
// @ts-nocheck
import React from 'react';
import { Dialog, DialogSuspense } from '@/components';
import withDialogRedux from '@/components/DialogReduxConnect';
import { compose } from '@/utils';
const ExcessPaymentDialogContent = React.lazy(() =>
import('./ExcessPaymentDialogContent').then((module) => ({
default: module.ExcessPaymentDialogContent,
})),
);
/**
* Excess payment dialog of the payment received form.
*/
function ExcessPaymentDialogRoot({ dialogName, isOpen }) {
return (
<Dialog
name={dialogName}
title={'Excess Payment'}
isOpen={isOpen}
canEscapeJeyClose={true}
autoFocus={true}
style={{ width: 500 }}
>
<DialogSuspense>
<ExcessPaymentDialogContent dialogName={dialogName} />
</DialogSuspense>
</Dialog>
);
}
export const ExcessPaymentDialog = compose(withDialogRedux())(
ExcessPaymentDialogRoot,
);
ExcessPaymentDialog.displayName = 'ExcessPaymentDialog';

View File

@@ -0,0 +1,86 @@
// @ts-nocheck
import * as Yup from 'yup';
import * as R from 'ramda';
import { Button, Classes, Intent } from '@blueprintjs/core';
import { Form, Formik, FormikHelpers, useFormikContext } from 'formik';
import { FormatNumber } from '@/components';
import { usePaymentReceiveFormContext } from '../../PaymentReceiveFormProvider';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import { usePaymentReceivedTotalExceededAmount } from '../../utils';
interface ExcessPaymentValues {}
export function ExcessPaymentDialogContentRoot({ dialogName, closeDialog }) {
const {
submitForm,
values: { currency_code: currencyCode },
} = useFormikContext();
const { setIsExcessConfirmed } = usePaymentReceiveFormContext();
const exceededAmount = usePaymentReceivedTotalExceededAmount();
const handleSubmit = (
values: ExcessPaymentValues,
{ setSubmitting }: FormikHelpers<ExcessPaymentValues>,
) => {
setSubmitting(true);
setIsExcessConfirmed(true);
submitForm().then(() => {
closeDialog(dialogName);
setSubmitting(false);
});
};
const handleClose = () => {
closeDialog(dialogName);
};
return (
<Formik initialValues={{}} onSubmit={handleSubmit}>
<Form>
<ExcessPaymentDialogContentForm
exceededAmount={
<FormatNumber value={exceededAmount} currency={currencyCode} />
}
onClose={handleClose}
/>
</Form>
</Formik>
);
}
export const ExcessPaymentDialogContent = R.compose(withDialogActions)(
ExcessPaymentDialogContentRoot,
);
function ExcessPaymentDialogContentForm({ onClose, exceededAmount }) {
const { submitForm, isSubmitting } = useFormikContext();
const handleCloseBtn = () => {
onClose && onClose();
};
return (
<>
<div className={Classes.DIALOG_BODY}>
<p style={{ marginBottom: 20 }}>
Would you like to record the excess amount of{' '}
<strong>{exceededAmount}</strong> as credit payment from the customer.
</p>
</div>
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button
intent={Intent.PRIMARY}
loading={isSubmitting}
disabled={isSubmitting}
onClick={() => submitForm()}
>
Save Payment as Credit
</Button>
<Button onClick={handleCloseBtn}>Cancel</Button>
</div>
</div>
</>
);
}

View File

@@ -0,0 +1 @@
export * from './ExcessPaymentDialog';

View File

@@ -0,0 +1,306 @@
// @ts-nocheck
import React from 'react';
import moment from 'moment';
import intl from 'react-intl-universal';
import { omit, pick, first, sumBy } from 'lodash';
import { useFormikContext } from 'formik';
import { Intent } from '@blueprintjs/core';
import { AppToaster } from '@/components';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import {
defaultFastFieldShouldUpdate,
transformToForm,
safeSumBy,
orderingLinesIndexes,
formattedAmount,
} from '@/utils';
import { useCurrentOrganization } from '@/hooks/state';
import {
transformAttachmentsToForm,
transformAttachmentsToRequest,
} from '@/containers/Attachments/utils';
// Default payment receive entry.
export const defaultPaymentReceiveEntry = {
index: '',
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: '',
// Holds the payment number that entered manually only.
payment_receive_no_manually: '',
statement: '',
amount: '',
currency_code: '',
branch_id: '',
exchange_rate: 1,
entries: [],
attachments: [],
};
export const defaultRequestPaymentEntry = {
index: '',
payment_amount: '',
invoice_id: '',
};
export const defaultRequestPayment = {
customer_id: '',
deposit_account_id: '',
payment_date: '',
payment_receive_no: '',
branch_id: '',
statement: '',
entries: [],
};
/**
* Transformes the edit payment receive to initial values of the form.
*/
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 || '',
})),
],
attachments: transformAttachmentsToForm(paymentReceive),
});
/**
* 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,
branch_id: invoice.branch_id,
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,
}));
};
/**
* Detarmines the customers fast-field should update.
*/
export const customersFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.shouldUpdateDeps.items !== oldProps.shouldUpdateDeps.items ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Detarmines the accounts fast-field should update.
*/
export const accountsFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.items !== oldProps.items ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Tranformes form values to request.
*/
export const transformFormToRequest = (form) => {
// Filters entries that have no `invoice_id` and `payment_amount`.
const entries = form.entries
.filter((entry) => entry.invoice_id && entry.payment_amount)
.map((entry) => ({
...pick(entry, Object.keys(defaultRequestPaymentEntry)),
}));
const attachments = transformAttachmentsToRequest(form);
return {
...omit(form, ['payment_receive_no_manually', 'payment_receive_no']),
// The `payment_receive_no_manually` will be presented just if the auto-increment
// is disable, always both attributes hold the same value in manual mode.
...(form.payment_receive_no_manually && {
payment_receive_no: form.payment_receive_no,
}),
entries: orderingLinesIndexes(entries),
attachments,
};
};
export const useSetPrimaryBranchToForm = () => {
const { setFieldValue } = useFormikContext();
const { branches, isBranchesSuccess } = usePaymentReceiveFormContext();
React.useEffect(() => {
if (isBranchesSuccess) {
const primaryBranch = branches.find((b) => b.primary) || first(branches);
if (primaryBranch) {
setFieldValue('branch_id', primaryBranch.id);
}
}
}, [isBranchesSuccess, setFieldValue, branches]);
};
/**
* Transformes the response errors types.
*/
export const transformErrors = (errors, { setFieldError }) => {
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_received.field.error.payment_receive_no_required'),
);
}
if (getError('PAYMENT_ACCOUNT_CURRENCY_INVALID')) {
AppToaster.show({
message: intl.get(
'payment_Receive.error.payment_account_currency_invalid',
),
intent: Intent.DANGER,
});
}
};
/**
* Retreives the payment receive totals.
*/
export const usePaymentReceiveTotals = () => {
const {
values: { entries, currency_code: currencyCode },
} = useFormikContext();
// Retrieves the invoice entries total.
const total = React.useMemo(
() => sumBy(entries, 'payment_amount'),
[entries],
);
// Retrieves the formatted total money.
const formattedTotal = React.useMemo(
() => formattedAmount(total, currencyCode),
[total, currencyCode],
);
// Retrieves the formatted subtotal.
const formattedSubtotal = React.useMemo(
() => formattedAmount(total, currencyCode, { money: false }),
[total, currencyCode],
);
return {
total,
formattedTotal,
formattedSubtotal,
};
};
export const usePaymentReceivedTotalAppliedAmount = () => {
const {
values: { entries },
} = useFormikContext();
// Retrieves the invoice entries total.
return React.useMemo(() => sumBy(entries, 'payment_amount'), [entries]);
};
export const usePaymentReceivedTotalAmount = () => {
const {
values: { amount },
} = useFormikContext();
return amount;
};
export const usePaymentReceivedTotalExceededAmount = () => {
const totalAmount = usePaymentReceivedTotalAmount();
const totalApplied = usePaymentReceivedTotalAppliedAmount();
return Math.abs(totalAmount - totalApplied);
};
/**
* Detarmines whether the payment has foreign customer.
* @returns {boolean}
*/
export const useEstimateIsForeignCustomer = () => {
const { values } = useFormikContext();
const currentOrganization = useCurrentOrganization();
const isForeignCustomer = React.useMemo(
() => values.currency_code !== currentOrganization.base_currency,
[values.currency_code, currentOrganization.base_currency],
);
return isForeignCustomer;
};
export const resetFormState = ({ initialValues, values, resetForm }) => {
resetForm({
values: {
// Reset the all values except the brand id.
...initialValues,
brand_id: values.brand_id,
},
});
};
export const getExceededAmountFromValues = (values) => {
const totalApplied = sumBy(values.entries, 'payment_amount');
const totalAmount = values.amount;
return totalAmount - totalApplied;
};

View File

@@ -0,0 +1,91 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import { MenuItem } from '@blueprintjs/core';
import { RESOURCES_TYPES } from '@/constants/resourcesTypes';
import {
AbilitySubject,
PaymentReceiveAction,
} from '@/constants/abilityOption';
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
import { highlightText } from '@/utils';
import { Icon } from '@/components';
import { DRAWERS } from '@/constants/drawers';
/**
* Payment receive universal search item select action.
*/
function PaymentReceiveUniversalSearchSelectComponent({
// #ownProps
resourceType,
resourceId,
// #withDrawerActions
openDrawer,
}) {
if (resourceType === RESOURCES_TYPES.PAYMENT_RECEIVE) {
openDrawer(DRAWERS.PAYMENT_RECEIVED_DETAILS, {
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="bp4-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_received'),
selectItemAction: PaymentReceiveUniversalSearchSelect,
itemRenderer: PaymentReceiveUniversalSearchItem,
itemSelect: paymentReceivesToSearch,
permission: {
ability: PaymentReceiveAction.View,
subject: AbilitySubject.PaymentReceive,
},
});

View File

@@ -0,0 +1,71 @@
// @ts-nocheck
import React, { createContext } from 'react';
import { isEmpty } from 'lodash';
import { DashboardInsider } from '@/components/Dashboard';
import {
useResourceViews,
useResourceMeta,
usePaymentReceives,
} from '@/hooks/query';
import { getFieldsFromResourceMeta } from '@/utils';
const PaymentsReceivedListContext = createContext();
/**
* Payment receives data provider.
*/
function PaymentsReceivedListProvider({ 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'}
>
<PaymentsReceivedListContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const usePaymentsReceivedListContext = () =>
React.useContext(PaymentsReceivedListContext);
export { PaymentsReceivedListProvider, usePaymentsReceivedListContext };

View File

@@ -0,0 +1,194 @@
// @ts-nocheck
import React from 'react';
import {
Button,
Classes,
NavbarDivider,
NavbarGroup,
Intent,
Alignment,
} from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import {
Icon,
Can,
If,
DashboardFilterButton,
AdvancedFilterPopover,
FormattedMessage as T,
DashboardRowsHeightButton,
DashboardActionViewsList,
DashboardActionsBar,
} from '@/components';
import withPaymentsReceived from './withPaymentsReceived';
import withPaymentsReceivedActions from './withPaymentsReceivedActions';
import withSettings from '@/containers/Settings/withSettings';
import withSettingsActions from '@/containers/Settings/withSettingsActions';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import {
PaymentReceiveAction,
AbilitySubject,
} from '@/constants/abilityOption';
import { usePaymentsReceivedListContext } from './PaymentsReceivedListProvider';
import { useRefreshPaymentReceive } from '@/hooks/query/paymentReceives';
import { useDownloadExportPdf } from '@/hooks/query/FinancialReports/use-export-pdf';
import { compose } from '@/utils';
import { DialogsName } from '@/constants/dialogs';
/**
* Payment receives actions bar.
*/
function PaymentsReceivedActionsBar({
// #withPaymentsReceivedActions
setPaymentReceivesTableState,
// #withPaymentsReceived
paymentFilterConditions,
// #withSettings
paymentReceivesTableSize,
// #withSettingsActions
addSetting,
// #withDialogActions
openDialog,
}) {
// History context.
const history = useHistory();
// Payment receives list context.
const { paymentReceivesViews, fields } = usePaymentsReceivedListContext();
// Exports pdf document.
const { downloadAsync: downloadExportPdf } = useDownloadExportPdf();
// Handle new payment button click.
const handleClickNewPaymentReceive = () => {
history.push('/payment-received/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();
};
// Handle table row size change.
const handleTableRowSizeChange = (size) => {
addSetting('paymentReceives', 'tableSize', size);
};
// Handle the import button click.
const handleImportBtnClick = () => {
history.push('/payments-received/import');
};
// Handle the export button click.
const handleExportBtnClick = () => {
openDialog(DialogsName.Export, { resource: 'payment_receive' });
};
// Handles the print button click.
const handlePrintBtnClick = () => {
downloadExportPdf({ resource: 'PaymentReceive' });
};
return (
<DashboardActionsBar>
<NavbarGroup>
<DashboardActionViewsList
resourceName={'payment_receives'}
views={paymentReceivesViews}
onChange={handleTabChange}
/>
<NavbarDivider />
<Can I={PaymentReceiveAction.Create} a={AbilitySubject.PaymentReceive}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'plus'} />}
text={<T id={'new_payment_received'} />}
onClick={handleClickNewPaymentReceive}
/>
</Can>
<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'} />}
onClick={handlePrintBtnClick}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'file-import-16'} />}
text={<T id={'import'} />}
onClick={handleImportBtnClick}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'file-export-16'} iconSize={'16'} />}
text={<T id={'export'} />}
onClick={handleExportBtnClick}
/>
<NavbarDivider />
<DashboardRowsHeightButton
initialValue={paymentReceivesTableSize}
onChange={handleTableRowSizeChange}
/>
<NavbarDivider />
</NavbarGroup>
<NavbarGroup align={Alignment.RIGHT}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon="refresh-16" iconSize={14} />}
onClick={handleRefreshBtnClick}
/>
</NavbarGroup>
</DashboardActionsBar>
);
}
export default compose(
withPaymentsReceivedActions,
withSettingsActions,
withPaymentsReceived(({ paymentReceivesTableState }) => ({
paymentReceivesTableState,
paymentFilterConditions: paymentReceivesTableState.filterRoles,
})),
withSettings(({ paymentReceiveSettings }) => ({
paymentReceivesTableSize: paymentReceiveSettings?.tableSize,
})),
withDialogActions,
)(PaymentsReceivedActionsBar);

View File

@@ -0,0 +1,46 @@
// @ts-nocheck
import React from 'react';
import { Button, Intent } from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import { EmptyStatus } from '@/components';
import { Can, FormattedMessage as T } from '@/components';
import { PaymentReceiveAction, AbilitySubject } from '@/constants/abilityOption';
export default function PaymentsReceivedEmptyStatus() {
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={
<>
<Can
I={PaymentReceiveAction.Create}
a={AbilitySubject.PaymentReceive}
>
<Button
intent={Intent.PRIMARY}
large={true}
onClick={() => {
history.push('/payment-received/new');
}}
>
<T id={'new_payment_received'} />
</Button>
<Button intent={Intent.NONE} large={true}>
<T id={'learn_more'} />
</Button>
</Can>
</>
}
/>
);
}

View File

@@ -0,0 +1,54 @@
// @ts-nocheck
import React from 'react';
import '@/style/pages/PaymentReceive/List.scss';
import { DashboardPageContent } from '@/components';
import { PaymentsReceivedListProvider } from './PaymentsReceivedListProvider';
import PaymentReceivesTable from './PaymentsReceivedTable';
import PaymentsReceivedActionsBar from './PaymentsReceivedActionsBar';
import withPaymentsReceived from './withPaymentsReceived';
import withPaymentsReceivedActions from './withPaymentsReceivedActions';
import { compose, transformTableStateToQuery } from '@/utils';
function PaymentsReceivedList({
// #withPaymentsReceived
paymentReceivesTableState,
paymentsTableStateChanged,
// #withPaymentsReceivedActions
resetPaymentReceivesTableState,
}) {
// Resets the payment receives table state once the page unmount.
React.useEffect(
() => () => {
resetPaymentReceivesTableState();
},
[resetPaymentReceivesTableState],
);
return (
<PaymentsReceivedListProvider
query={transformTableStateToQuery(paymentReceivesTableState)}
tableStateChanged={paymentsTableStateChanged}
>
<PaymentsReceivedActionsBar />
<DashboardPageContent>
<PaymentReceivesTable />
</DashboardPageContent>
</PaymentsReceivedListProvider>
);
}
export default compose(
withPaymentsReceived(
({ paymentReceivesTableState, paymentsTableStateChanged }) => ({
paymentReceivesTableState,
paymentsTableStateChanged,
}),
),
withPaymentsReceivedActions,
)(PaymentsReceivedList);

View File

@@ -0,0 +1,72 @@
// @ts-nocheck
import React, { createContext, useContext } from 'react';
import { isEmpty } from 'lodash';
import { DashboardInsider } from '@/components/Dashboard';
import {
useResourceViews,
useResourceMeta,
usePaymentReceives,
} from '@/hooks/query';
import { getFieldsFromResourceMeta } from '@/utils';
const PaymentsReceivedListContext = createContext();
/**
* Payment receives list data provider.
*/
function PaymentsReceivedListProvider({ query, tableStateChanged, ...props }) {
// Fetch payment receives resource views and fields.
const { data: paymentReceivesViews, isLoading: 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 =
isEmpty(paymentReceives) && !isPaymentReceivesLoading && !tableStateChanged;
// 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'}
>
<PaymentsReceivedListContext.Provider value={state} {...props} />
</DashboardInsider>
);
}
const usePaymentsReceivedListContext = () =>
useContext(PaymentsReceivedListContext);
export { PaymentsReceivedListProvider, usePaymentsReceivedListContext };

View File

@@ -0,0 +1,157 @@
// @ts-nocheck
import React, { useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import { compose } from '@/utils';
import { TABLES } from '@/constants/tables';
import {
DataTable,
DashboardContentTable,
TableSkeletonRows,
TableSkeletonHeader,
} from '@/components';
import PaymentReceivesEmptyStatus from './PaymentsReceivedEmptyStatus';
import withPaymentsReceived from './withPaymentsReceived';
import withPaymentsReceivedActions from './withPaymentsReceivedActions';
import withAlertsActions from '@/containers/Alert/withAlertActions';
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import withSettings from '@/containers/Settings/withSettings';
import { usePaymentReceivesColumns, ActionsMenu } from './components';
import { usePaymentsReceivedListContext } from './PaymentsReceivedListProvider';
import { useMemorizedColumnsWidths } from '@/hooks';
import { DRAWERS } from '@/constants/drawers';
import { DialogsName } from '@/constants/dialogs';
/**
* Payment receives datatable.
*/
function PaymentsReceivedDataTable({
// #withPaymentsReceivedActions
setPaymentReceivesTableState,
// #withAlertsActions
openAlert,
// #withDrawerActions
openDrawer,
// #withDialogActions
openDialog,
// #withSettings
paymentReceivesTableSize,
}) {
const history = useHistory();
// Payment receives list context.
const {
paymentReceives,
pagination,
isPaymentReceivesLoading,
isPaymentReceivesFetching,
isEmptyStatus,
} = usePaymentsReceivedListContext();
// Payment receives columns.
const columns = usePaymentReceivesColumns();
// Handles edit payment receive.
const handleEditPaymentReceive = ({ id }) => {
history.push(`/payments-received/${id}/edit`);
};
// Handles delete payment receive.
const handleDeletePaymentReceive = ({ id }) => {
openAlert('payment-received-delete', { paymentReceiveId: id });
};
// Handle view detail payment receive..
const handleViewDetailPaymentReceive = ({ id }) => {
openDrawer(DRAWERS.PAYMENT_RECEIVED_DETAILS, { paymentReceiveId: id });
};
// Handle mail send payment receive.
const handleSendMailPayment = ({ id }) => {
openDialog(DialogsName.PaymentMail, { paymentReceiveId: id });
};
// Handle cell click.
const handleCellClick = (cell, event) => {
openDrawer(DRAWERS.PAYMENT_RECEIVED_DETAILS, {
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}
size={paymentReceivesTableSize}
payload={{
onDelete: handleDeletePaymentReceive,
onEdit: handleEditPaymentReceive,
onViewDetails: handleViewDetailPaymentReceive,
onSendMail: handleSendMailPayment,
}}
/>
</DashboardContentTable>
);
}
export default compose(
withPaymentsReceivedActions,
withAlertsActions,
withDrawerActions,
withDialogActions,
withPaymentsReceived(({ paymentReceivesTableState }) => ({
paymentReceivesTableState,
})),
withSettings(({ paymentReceiveSettings }) => ({
paymentReceivesTableSize: paymentReceiveSettings?.tableSize,
})),
)(PaymentsReceivedDataTable);

View File

@@ -0,0 +1,63 @@
// @ts-nocheck
import React from 'react';
import { useHistory } from 'react-router';
import { Alignment, Navbar, NavbarGroup } from '@blueprintjs/core';
import { FormattedMessage as T, DashboardViewsTabs } from '@/components';
import { pick } from 'lodash';
import withPaymentsReceived from './withPaymentsReceived';
import withPaymentsReceivedActions from './withPaymentsReceivedActions';
import { usePaymentsReceivedListContext } from './PaymentsReceivedListProvider';
import { compose } from '@/utils';
/**
* Payment receive view tabs.
*/
function PaymentsReceivedViewTabs({
// #withPaymentsReceivedActions
addPaymentReceivesTableQueries,
// #withPaymentsReceived
paymentReceivesTableState,
}) {
const history = useHistory();
const { paymentReceivesViews, ...res } = usePaymentsReceivedListContext();
const tabs = paymentReceivesViews.map((view) => ({
...pick(view, ['name', 'id']),
}));
// Handles click a new view tab.
const handleClickNewView = () => {
history.push('/custom_views/payment-received/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(
withPaymentsReceivedActions,
withPaymentsReceived(({ paymentReceivesTableState }) => ({
paymentReceivesTableState,
})),
)(PaymentsReceivedViewTabs);

View File

@@ -0,0 +1,149 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import clsx from 'classnames';
import {
Intent,
Button,
Popover,
Menu,
MenuItem,
MenuDivider,
Position,
} from '@blueprintjs/core';
import { Money, Icon, Can } from '@/components';
import { safeCallback } from '@/utils';
import { CLASSES } from '@/constants/classes';
import {
PaymentReceiveAction,
AbilitySubject,
} from '@/constants/abilityOption';
/**
* Table actions menu.
*/
export function ActionsMenu({
row: { original: paymentReceive },
payload: { onEdit, onDelete, onViewDetails, onSendMail },
}) {
return (
<Menu>
<MenuItem
icon={<Icon icon="reader-18" />}
text={intl.get('view_details')}
onClick={safeCallback(onViewDetails, paymentReceive)}
/>
<MenuItem
icon={<Icon icon={'envelope'} iconSize={16} />}
text={'Send Mail'}
onClick={safeCallback(onSendMail, paymentReceive)}
/>
<Can I={PaymentReceiveAction.Edit} a={AbilitySubject.PaymentReceive}>
<MenuDivider />
<MenuItem
icon={<Icon icon="pen-18" />}
text={intl.get('edit_payment_received')}
onClick={safeCallback(onEdit, paymentReceive)}
/>
</Can>
<Can I={PaymentReceiveAction.Delete} a={AbilitySubject.PaymentReceive}>
<MenuDivider />
<MenuItem
text={intl.get('delete_payment_received')}
intent={Intent.DANGER}
onClick={safeCallback(onDelete, paymentReceive)}
icon={<Icon icon="trash-16" iconSize={16} />}
/>
</Can>
</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: 'formatted_payment_date',
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_received_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,17 @@
// @ts-nocheck
import { connect } from 'react-redux';
import {
getPaymentReceiveByIdFactory,
getPaymentReceiveEntriesFactory,
} from '@/store/PaymentReceives/paymentReceives.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,20 @@
// @ts-nocheck
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,16 @@
// @ts-nocheck
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);

View File

@@ -0,0 +1,13 @@
// @ts-nocheck
import React from 'react';
const PaymentReceivedDeleteAlert = React.lazy(
() => import('@/containers/Alerts/PaymentReceived/PaymentReceivedDeleteAlert'),
);
/**
* PaymentReceives alert.
*/
export default [
{ name: 'payment-received-delete', component: PaymentReceivedDeleteAlert },
];

View File

@@ -0,0 +1,25 @@
// @ts-nocheck
import { useHistory } from 'react-router-dom';
import { DashboardInsider } from '@/components';
import { ImportView } from '@/containers/Import';
export default function PaymentsReceiveImport() {
const history = useHistory();
const handleCancelBtnClick = () => {
history.push('/payments-received');
};
const handleImportSuccess = () => {
history.push('/payments-received');
};
return (
<DashboardInsider name={'import-accounts'}>
<ImportView
resource={'payment_receive'}
onCancelClick={handleCancelBtnClick}
onImportSuccess={handleImportSuccess}
/>
</DashboardInsider>
);
}