re-structure to monorepo.

This commit is contained in:
a.bouhuolia
2023-02-03 01:02:31 +02:00
parent 8242ec64ba
commit 7a0a13f9d5
10400 changed files with 46966 additions and 17223 deletions

View File

@@ -0,0 +1,74 @@
// @ts-nocheck
import React, { useCallback } from 'react';
import classNames from 'classnames';
import {
DataTableEditable,
CloudLoadingIndicator,
FormattedMessage as T,
} from '@/components';
import { CLASSES } from '@/constants/classes';
import { usePaymentMadeEntriesTableColumns } from './components';
import { usePaymentMadeInnerContext } from './PaymentMadeInnerProvider';
import { compose, updateTableCell } from '@/utils';
import { useFormikContext } from 'formik';
/**
* Payment made items table.
*/
export default function PaymentMadeEntriesTable({
onUpdateData,
entries,
currencyCode,
}) {
// Payment made inner context.
const { isNewEntriesFetching } = usePaymentMadeInnerContext();
// Payment entries table columns.
const columns = usePaymentMadeEntriesTableColumns();
// Formik context.
const {
values: { vendor_id },
} = useFormikContext();
// Handle update data.
const handleUpdateData = useCallback(
(rowIndex, columnId, value) => {
const newRows = compose(updateTableCell(rowIndex, columnId, value))(
entries,
);
onUpdateData(newRows);
},
[onUpdateData, entries],
);
// Detarmines the right no results message before selecting vendor and aftering
// selecting vendor id.
const noResultsMessage = vendor_id ? (
<T
id={
'there_is_no_payable_bills_for_this_vendor_that_can_be_applied_for_this_payment'
}
/>
) : (
<T id={'please_select_a_vendor_to_display_all_open_bills_for_it'} />
);
return (
<CloudLoadingIndicator isLoading={isNewEntriesFetching}>
<DataTableEditable
progressBarLoading={isNewEntriesFetching}
className={classNames(CLASSES.DATATABLE_EDITOR_ITEMS_ENTRIES)}
columns={columns}
data={entries}
spinnerProps={false}
payload={{
errors: [],
updateData: handleUpdateData,
currencyCode,
}}
noResults={noResultsMessage}
/>
</CloudLoadingIndicator>
);
}

View File

@@ -0,0 +1,111 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import {
Intent,
Button,
ButtonGroup,
Popover,
PopoverInteractionKind,
Position,
Menu,
MenuItem,
} from '@blueprintjs/core';
import { Icon, FormattedMessage as T } from '@/components';
import { useHistory } from 'react-router-dom';
import { useFormikContext } from 'formik';
import { usePaymentMadeFormContext } from './PaymentMadeFormProvider';
import { CLASSES } from '@/constants/classes';
/**
* Payment made floating actions bar.
*/
export default function PaymentMadeFloatingActions() {
// History context.
const history = useHistory();
// Formik context.
const { isSubmitting, resetForm } = useFormikContext();
// Payment made form context.
const { setSubmitPayload, paymentMadeId } = usePaymentMadeFormContext();
// 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 });
};
// handle submit & continue editing button click.
const handleSubmitContinueEditingBtnClick = (event) => {
setSubmitPayload({ redirect: false, publish: true });
};
return (
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
{/* ----------- Save and New ----------- */}
<ButtonGroup>
<Button
loading={isSubmitting}
intent={Intent.PRIMARY}
type="submit"
onClick={handleSubmitBtnClick}
style={{ minWidth: '85px' }}
text={paymentMadeId ? <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={paymentMadeId ? <T id={'reset'} /> : <T id={'clear'} />}
/>
{/* ----------- Cancel ----------- */}
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={handleCancelBtnClick}
text={<T id={'cancel'} />}
/>
</div>
);
}

View File

@@ -0,0 +1,34 @@
// @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 { PaymentMadeFormFooterLeft } from './PaymentMadeFormFooterLeft';
import { PaymentMadeFormFooterRight } from './PaymentMadeFormFooterRight';
/**
* Payment made form footer.
*/
export default function PaymentMadeFooter() {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<PaymentReceiveFooterPaper>
<Row>
<Col md={8}>
<PaymentMadeFormFooterLeft />
</Col>
<Col md={4}>
<PaymentMadeFormFooterRight />
</Col>
</Row>
</PaymentReceiveFooterPaper>
</div>
);
}
const PaymentReceiveFooterPaper = styled(Paper)`
padding: 20px;
`;

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({
vendor_id: Yup.string().label(intl.get('vendor_name_')).required(),
payment_date: Yup.date().required().label(intl.get('payment_date_')),
payment_account_id: Yup.number()
.required()
.label(intl.get('payment_account_')),
payment_number: Yup.string()
.nullable()
.max(DATATYPES_LENGTH.STRING)
.nullable()
.label(intl.get('payment_no_')),
reference: Yup.string().min(1).max(DATATYPES_LENGTH.STRING).nullable(),
description: Yup.string().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')),
bill_id: Yup.number()
.nullable()
.when(['payment_amount'], {
is: (payment_amount) => payment_amount,
then: Yup.number().required(),
}),
}),
),
});
export const CreatePaymentMadeFormSchema = Schema;
export const EditPaymentMadeFormSchema = Schema;

View File

@@ -0,0 +1,166 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { Formik, Form } from 'formik';
import { Intent } from '@blueprintjs/core';
import { sumBy, defaultTo } from 'lodash';
import { useHistory } from 'react-router-dom';
import { CLASSES } from '@/constants/classes';
import { AppToaster } from '@/components';
import PaymentMadeHeader from './PaymentMadeFormHeader';
import PaymentMadeFloatingActions from './PaymentMadeFloatingActions';
import PaymentMadeFooter from './PaymentMadeFooter';
import PaymentMadeFormBody from './PaymentMadeFormBody';
import PaymentMadeFormTopBar from './PaymentMadeFormTopBar';
import { PaymentMadeInnerProvider } from './PaymentMadeInnerProvider';
import { usePaymentMadeFormContext } from './PaymentMadeFormProvider';
import { compose, orderingLinesIndexes } from '@/utils';
import withSettings from '@/containers/Settings/withSettings';
import withCurrentOrganization from '@/containers/Organization/withCurrentOrganization';
import {
EditPaymentMadeFormSchema,
CreatePaymentMadeFormSchema,
} from './PaymentMadeForm.schema';
import {
defaultPaymentMade,
transformToEditForm,
transformErrors,
transformFormToRequest,
} from './utils';
/**
* Payment made form component.
*/
function PaymentMadeForm({
// #withSettings
preferredPaymentAccount,
// #withCurrentOrganization
organization: { base_currency },
}) {
const history = useHistory();
// Payment made form context.
const {
isNewMode,
paymentMadeId,
paymentMadeEditPage,
paymentEntriesEditPage,
submitPayload,
createPaymentMadeMutate,
editPaymentMadeMutate,
} = usePaymentMadeFormContext();
// Form initial values.
const initialValues = useMemo(
() => ({
...(!isNewMode
? {
...transformToEditForm(paymentMadeEditPage, paymentEntriesEditPage),
}
: {
...defaultPaymentMade,
payment_account_id: defaultTo(preferredPaymentAccount),
currency_code: base_currency,
entries: orderingLinesIndexes(defaultPaymentMade.entries),
}),
}),
[isNewMode, paymentMadeEditPage, paymentEntriesEditPage],
);
// Handle the form submit.
const handleSubmitForm = (
values,
{ setSubmitting, resetForm, setFieldError },
) => {
setSubmitting(true);
// Total payment amount of entries.
const totalPaymentAmount = sumBy(values.entries, 'payment_amount');
if (totalPaymentAmount <= 0) {
AppToaster.show({
message: intl.get('you_cannot_make_payment_with_zero_total_amount'),
intent: Intent.DANGER,
});
return;
}
// Transformes the form values to request body.
const form = transformFormToRequest(values);
// Triggers once the save request success.
const onSaved = (response) => {
AppToaster.show({
message: intl.get(
isNewMode
? 'the_payment_made_has_been_edited_successfully'
: 'the_payment_made_has_been_created_successfully',
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
submitPayload.redirect && history.push('/payment-mades');
submitPayload.resetForm && resetForm();
};
const onError = ({
response: {
data: { errors },
},
}) => {
if (errors) {
transformErrors(errors, { setFieldError });
}
setSubmitting(false);
};
if (!isNewMode) {
editPaymentMadeMutate([paymentMadeId, form]).then(onSaved).catch(onError);
} else {
createPaymentMadeMutate(form).then(onSaved).catch(onError);
}
};
return (
<div
className={classNames(
CLASSES.PAGE_FORM,
CLASSES.PAGE_FORM_STRIP_STYLE,
CLASSES.PAGE_FORM_PAYMENT_MADE,
)}
>
<Formik
initialValues={initialValues}
validationSchema={
isNewMode ? CreatePaymentMadeFormSchema : EditPaymentMadeFormSchema
}
onSubmit={handleSubmitForm}
>
<Form>
<PaymentMadeInnerProvider>
<PaymentMadeFormTopBar />
<PaymentMadeHeader />
<PaymentMadeFormBody />
<PaymentMadeFooter />
<PaymentMadeFloatingActions />
</PaymentMadeInnerProvider>
</Form>
</Formik>
</div>
);
}
export default compose(
withSettings(({ billPaymentSettings }) => ({
paymentNextNumber: billPaymentSettings?.next_number,
paymentNumberPrefix: billPaymentSettings?.number_prefix,
preferredPaymentAccount: parseInt(billPaymentSettings?.withdrawalAccount),
})),
withCurrentOrganization(),
)(PaymentMadeForm);

View File

@@ -0,0 +1,28 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import { FastField } from 'formik';
import { CLASSES } from '@/constants/classes';
import PaymentMadeEntriesTable from './PaymentMadeEntriesTable';
export default function PaymentMadeFormBody() {
return (
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
<FastField name={'entries'}>
{({
form: { setFieldValue, values },
field: { value },
meta: { error, touched },
}) => (
<PaymentMadeEntriesTable
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 { usePaymentMadeFormContext } from './PaymentMadeFormProvider';
/**
* Payment made form currency tag.
* @returns
*/
export default function PaymentMadeFormCurrencyTag() {
const { isForeignVendor, selectVendor } = usePaymentMadeFormContext();
if (!isForeignVendor) {
return null;
}
return (
<BaseCurrencyRoot>
<BaseCurrency currency={selectVendor?.currency_code} />
</BaseCurrencyRoot>
);
}

View File

@@ -0,0 +1,40 @@
// @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';
/**
* Payment made form footer left-side.
* @returns {JSX.Element}
*/
export function PaymentMadeFormFooterLeft() {
return (
<React.Fragment>
{/* --------- Internal Note--------- */}
<InternalNoteFormGroup
name={'internal_note'}
label={<T id={'payment_made.form.internal_note.label'} />}
>
<FEditableText
name={'internal_note'}
placeholder={intl.get('payment_made.form.internal_note.placeholder')}
/>
</InternalNoteFormGroup>
</React.Fragment>
);
}
const InternalNoteFormGroup = styled(FFormGroup)`
&.bp3-form-group {
margin-bottom: 40px;
.bp3-label {
font-size: 12px;
margin-bottom: 12px;
}
.bp3-form-content {
margin-left: 10px;
}
}
`;

View File

@@ -0,0 +1,35 @@
// @ts-nocheck
import React from 'react';
import styled from 'styled-components';
import {
T,
TotalLines,
TotalLine,
TotalLineBorderStyle,
TotalLineTextStyle,
} from '@/components';
import { usePaymentMadeTotals } from './utils';
export function PaymentMadeFormFooterRight() {
const { formattedSubtotal, formattedTotal } = usePaymentMadeTotals();
return (
<PaymentMadeTotalLines labelColWidth={'180px'} amountColWidth={'180px'}>
<TotalLine
title={<T id={'payment_made_form.label.subtotal'} />}
value={formattedSubtotal}
borderStyle={TotalLineBorderStyle.None}
/>
<TotalLine
title={<T id={'payment_made_form.label.total'} />}
value={formattedTotal}
textStyle={TotalLineTextStyle.Bold}
/>
</PaymentMadeTotalLines>
);
}
const PaymentMadeTotalLines = styled(TotalLines)`
width: 100%;
color: #555555;
`;

View File

@@ -0,0 +1,43 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import classNames from 'classnames';
import { useFormikContext } from 'formik';
import { sumBy } from 'lodash';
import { CLASSES } from '@/constants/classes';
import { Money, FormattedMessage as T } from '@/components';
import PaymentMadeFormHeaderFields from './PaymentMadeFormHeaderFields';
/**
* Payment made header form.
*/
function PaymentMadeFormHeader() {
// Formik form context.
const {
values: { entries, currency_code },
} = useFormikContext();
// Calculate the payment amount of the entries.
const amountPaid = useMemo(() => sumBy(entries, 'payment_amount'), [entries]);
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}>
<PaymentMadeFormHeaderFields />
<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={amountPaid} currency={currency_code} />
</h1>
</div>
</div>
</div>
</div>
);
}
export default PaymentMadeFormHeader;

View File

@@ -0,0 +1,277 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import styled from 'styled-components';
import classNames from 'classnames';
import {
FormGroup,
InputGroup,
Position,
Classes,
ControlGroup,
Button,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FastField, Field, useFormikContext, ErrorMessage } from 'formik';
import { FormattedMessage as T } from '@/components';
import { toSafeInteger } from 'lodash';
import { CLASSES } from '@/constants/classes';
import {
FFormGroup,
AccountsSelectList,
VendorSelectField,
FieldRequiredHint,
InputPrependText,
Money,
Hint,
Icon,
VendorDrawerLink,
MoneyInputGroup,
} from '@/components';
import withCurrentOrganization from '@/containers/Organization/withCurrentOrganization';
import { usePaymentMadeFormContext } from './PaymentMadeFormProvider';
import { ACCOUNT_TYPE } from '@/constants/accountTypes';
import { PaymentMadeExchangeRateInputField } from './components';
import {
momentFormatter,
tansformDateValue,
handleDateChange,
inputIntent,
compose,
safeSumBy,
fullAmountPaymentEntries,
amountPaymentEntries,
} from '@/utils';
import { accountsFieldShouldUpdate, vendorsFieldShouldUpdate } from './utils';
/**
* Payment made form header fields.
*/
function PaymentMadeFormHeaderFields({ organization: { base_currency } }) {
// Formik form context.
const {
values: { entries },
setFieldValue,
} = useFormikContext();
// Payment made form context.
const { vendors, accounts, isNewMode, setPaymentVendorId } =
usePaymentMadeFormContext();
// Sumation of payable full-amount.
const payableFullAmount = useMemo(
() => safeSumBy(entries, 'due_amount'),
[entries],
);
// Handle receive full-amount 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)}>
{/* ------------ Vendor name ------------ */}
<FastField
name={'vendor_id'}
vendors={vendors}
shouldUpdate={vendorsFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FFormGroup
name={'vendor_id'}
label={<T id={'vendor_name'} />}
inline={true}
className={classNames('form-group--select-list', Classes.FILL)}
labelInfo={<FieldRequiredHint />}
>
<VendorSelectField
contacts={vendors}
selectedContactId={value}
defaultSelectText={<T id={'select_vender_account'} />}
onContactSelected={(contact) => {
form.setFieldValue('vendor_id', contact.id);
form.setFieldValue('currency_code', contact?.currency_code);
setPaymentVendorId(contact.id);
}}
disabled={!isNewMode}
popoverFill={true}
allowCreate={true}
/>
{value && (
<VendorButtonLink vendorId={value}>
<T id={'view_vendor_details'} />
</VendorButtonLink>
)}
</FFormGroup>
)}
</FastField>
{/* ----------- Exchange rate ----------- */}
<PaymentMadeExchangeRateInputField
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={'full_amount'}>
{({
form: {
values: { currency_code },
},
field: { value },
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('full_amount', value);
}}
onBlurValue={onFullAmountBlur}
/>
</ControlGroup>
<Button
onClick={handleReceiveFullAmountClick}
className={'receive-full-amount'}
small={true}
minimal={true}
>
<T id={'receive_full_amount'} /> (
<Money amount={payableFullAmount} currency={currency_code} />)
</Button>
</FormGroup>
)}
</Field>
{/* ------------ Payment number ------------ */}
<FastField name={'payment_number'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'payment_no'} />}
inline={true}
className={('form-group--payment_number', Classes.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="payment_number" />}
>
<InputGroup
intent={inputIntent({ error, touched })}
minimal={true}
{...field}
/>
</FormGroup>
)}
</FastField>
{/* ------------ Payment account ------------ */}
<FastField
name={'payment_account_id'}
accounts={accounts}
shouldUpdate={accountsFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'payment_account'} />}
className={classNames(
'form-group--payment_account_id',
'form-group--select-list',
Classes.FILL,
)}
inline={true}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'payment_account_id'} />}
>
<AccountsSelectList
accounts={accounts}
labelInfo={<FieldRequiredHint />}
onAccountSelected={(account) => {
form.setFieldValue('payment_account_id', account.id);
}}
defaultSelectText={<T id={'select_payment_account'} />}
selectedAccountId={value}
filterByTypes={[
ACCOUNT_TYPE.CASH,
ACCOUNT_TYPE.BANK,
ACCOUNT_TYPE.OTHER_CURRENT_ASSET,
]}
/>
</FormGroup>
)}
</FastField>
{/* ------------ Reference ------------ */}
<FastField name={'reference'}>
{({ 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(withCurrentOrganization())(PaymentMadeFormHeaderFields);
const VendorButtonLink = styled(VendorDrawerLink)`
font-size: 11px;
margin-top: 6px;
`;

View File

@@ -0,0 +1,21 @@
// @ts-nocheck
import React from 'react';
import { useParams } from 'react-router-dom';
import PaymentMadeForm from './PaymentMadeForm';
import { PaymentMadeFormProvider } from './PaymentMadeFormProvider';
import '@/style/pages/PaymentMade/PageForm.scss';
/**
* Payment made - Page form.
*/
export default function PaymentMadeFormPage() {
const { id: paymentMadeId } = useParams();
return (
<PaymentMadeFormProvider paymentMadeId={paymentMadeId}>
<PaymentMadeForm />
</PaymentMadeFormProvider>
);
}

View File

@@ -0,0 +1,120 @@
// @ts-nocheck
import React, { createContext, useContext } from 'react';
import { Features } from '@/constants';
import { useFeatureCan } from '@/hooks/state';
import {
useAccounts,
useVendors,
useItems,
useBranches,
usePaymentMadeEditPage,
useSettings,
useCreatePaymentMade,
useEditPaymentMade,
} from '@/hooks/query';
import { DashboardInsider } from '@/components';
// Payment made form context.
const PaymentMadeFormContext = createContext();
/**
* Payment made form provider.
*/
function PaymentMadeFormProvider({ query, paymentMadeId, ...props }) {
const [submitPayload, setSubmitPayload] = React.useState({});
const [paymentVendorId, setPaymentVendorId] = React.useState(null);
// Features guard.
const { featureCan } = useFeatureCan();
const isBranchFeatureCan = featureCan(Features.Branches);
// Handle fetch accounts data.
const { data: accounts, isLoading: isAccountsLoading } = useAccounts();
// Handle fetch Items data table or list.
const {
data: { items },
isFetching: isItemsFetching,
isLoading: isItemsLoading,
} = useItems({ page_size: 10000 });
// Handle fetch venders data table or list.
const {
data: { vendors },
isLoading: isVendorsLoading,
} = useVendors({ page_size: 10000 });
// Handle fetch specific payment made details.
const {
data: { paymentMade: paymentMadeEditPage, entries: paymentEntriesEditPage },
isFetching: isPaymentFetching,
isLoading: isPaymentLoading,
} = usePaymentMadeEditPage(paymentMadeId, {
enabled: !!paymentMadeId,
});
// Fetches the branches list.
const {
data: branches,
isLoading: isBranchesLoading,
isSuccess: isBranchesSuccess,
} = useBranches(query, { enabled: isBranchFeatureCan });
// Fetch payment made settings.
useSettings();
// Create and edit payment made mutations.
const { mutateAsync: createPaymentMadeMutate } = useCreatePaymentMade();
const { mutateAsync: editPaymentMadeMutate } = useEditPaymentMade();
const isNewMode = !paymentMadeId;
const isFeatureLoading = isBranchesLoading;
// Provider payload.
const provider = {
paymentMadeId,
accounts,
paymentEntriesEditPage,
paymentMadeEditPage,
vendors,
items,
branches,
submitPayload,
paymentVendorId,
isNewMode,
isAccountsLoading,
isItemsFetching,
isItemsLoading,
isVendorsLoading,
isPaymentFetching,
isPaymentLoading,
isFeatureLoading,
isBranchesSuccess,
createPaymentMadeMutate,
editPaymentMadeMutate,
setSubmitPayload,
setPaymentVendorId,
};
return (
<DashboardInsider
loading={
isVendorsLoading ||
isItemsLoading ||
isAccountsLoading ||
isPaymentLoading
}
name={'payment-made'}
>
<PaymentMadeFormContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const usePaymentMadeFormContext = () => useContext(PaymentMadeFormContext);
export { PaymentMadeFormProvider, usePaymentMadeFormContext };

View File

@@ -0,0 +1,68 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import { Alignment, NavbarGroup, Button, Classes } from '@blueprintjs/core';
import { useSetPrimaryBranchToForm } from './utils';
import { useFeatureCan } from '@/hooks/state';
import {
Icon,
BranchSelect,
FeatureCan,
FormTopbar,
DetailsBarSkeletonBase,
} from '@/components';
import { usePaymentMadeFormContext } from './PaymentMadeFormProvider';
import { Features } from '@/constants';
/**
* Payment made from top bar.
* @returns
*/
export default function PaymentMadeFormTopBar() {
// 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}>
<PaymentMadeFormSelectBranch />
</FeatureCan>
</NavbarGroup>
</FormTopbar>
);
}
function PaymentMadeFormSelectBranch() {
// payment made form context.
const { branches, isBranchesLoading } = usePaymentMadeFormContext();
return isBranchesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<BranchSelect
name={'branch_id'}
branches={branches}
input={PaymentMadeBranchSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function PaymentMadeBranchSelectButton({ label }) {
return (
<Button
text={intl.get('payment_made.branch_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'branch-16'} iconSize={16} />}
/>
);
}

View File

@@ -0,0 +1,50 @@
// @ts-nocheck
import React, { createContext, useContext, useEffect } from 'react';
import { useFormikContext } from 'formik';
import { usePaymentMadeNewPageEntries } from '@/hooks/query';
import { usePaymentMadeFormContext } from './PaymentMadeFormProvider';
import { transformToNewPageEntries } from './utils';
const PaymentMadeInnerContext = createContext();
/**
* Payment made inner form provider.
*/
function PaymentMadeInnerProvider({ ...props }) {
// Payment made form context.
const { isNewMode } = usePaymentMadeFormContext();
// Formik context.
const {
values: { vendor_id: vendorId },
setFieldValue,
} = useFormikContext();
const {
data: newPageEntries,
isLoading: isNewEntriesLoading,
isFetching: isNewEntriesFetching,
} = usePaymentMadeNewPageEntries(vendorId, {
enabled: !!vendorId && isNewMode,
keepPreviousData: true,
});
useEffect(() => {
if (!isNewEntriesFetching && newPageEntries && isNewMode) {
setFieldValue('entries', transformToNewPageEntries(newPageEntries));
}
}, [isNewEntriesFetching, newPageEntries, isNewMode, setFieldValue]);
// Provider payload.
const provider = {
newPageEntries,
isNewEntriesLoading,
isNewEntriesFetching,
};
return <PaymentMadeInnerContext.Provider value={provider} {...props} />;
}
const usePaymentMadeInnerContext = () => useContext(PaymentMadeInnerContext);
export { PaymentMadeInnerProvider, usePaymentMadeInnerContext };

View File

@@ -0,0 +1,93 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import moment from 'moment';
import { Money, ExchangeRateInputGroup } from '@/components';
import { MoneyFieldCell } from '@/components/DataTableCells';
import { useFormikContext } from 'formik';
import { useCurrentOrganization } from '@/hooks/state';
import { usePaymentMadeIsForeignCustomer } from './utils';
function BillNumberAccessor(row) {
return row?.bill_no ? row?.bill_no : '-';
}
function BillDateCell({ value }) {
return moment(value).format('YYYY MMM DD');
}
/**
* Mobey table cell.
*/
function MoneyTableCell({ row: { original }, value }) {
return <Money amount={value} currency={original.currency_code} />;
}
/**
* Payment made entries table columns
*/
export function usePaymentMadeEntriesTableColumns() {
return React.useMemo(
() => [
{
Header: 'Bill date',
id: 'bill_date',
accessor: 'bill_date',
Cell: BillDateCell,
disableSortBy: true,
width: 120,
},
{
Header: intl.get('bill_number'),
accessor: BillNumberAccessor,
disableSortBy: true,
width: 120,
},
{
Header: intl.get('bill_amount'),
accessor: 'amount',
Cell: MoneyTableCell,
disableSortBy: true,
width: 150,
},
{
Header: intl.get('amount_due'),
accessor: 'due_amount',
Cell: MoneyTableCell,
disableSortBy: true,
width: 150,
},
{
Header: intl.get('payment_amount'),
accessor: 'payment_amount',
Cell: MoneyFieldCell,
disableSortBy: true,
width: 150,
},
],
[],
);
}
/**
* payment made exchange rate input field.
* @returns {JSX.Element}
*/
export function PaymentMadeExchangeRateInputField({ ...props }) {
const currentOrganization = useCurrentOrganization();
const { values } = useFormikContext();
const isForeignCustomer = usePaymentMadeIsForeignCustomer();
// Can't continue if the customer is not foreign.
if (!isForeignCustomer) {
return null;
}
return (
<ExchangeRateInputGroup
fromCurrency={values.currency_code}
toCurrency={currentOrganization.base_currency}
{...props}
/>
);
}

View File

@@ -0,0 +1,182 @@
// @ts-nocheck
import React from 'react';
import moment from 'moment';
import intl from 'react-intl-universal';
import { pick, first, sumBy } from 'lodash';
import { useFormikContext } from 'formik';
import { Intent } from '@blueprintjs/core';
import { AppToaster } from '@/components';
import { usePaymentMadeFormContext } from './PaymentMadeFormProvider';
import {
defaultFastFieldShouldUpdate,
safeSumBy,
transformToForm,
orderingLinesIndexes,
formattedAmount,
} from '@/utils';
import { useCurrentOrganization } from '@/hooks/state';
export const ERRORS = {
PAYMENT_NUMBER_NOT_UNIQUE: 'PAYMENT.NUMBER.NOT.UNIQUE',
};
// Default payment made entry values.
export const defaultPaymentMadeEntry = {
bill_id: '',
payment_amount: '',
currency_code: '',
id: null,
due_amount: null,
amount: '',
};
// Default initial values of payment made.
export const defaultPaymentMade = {
full_amount: '',
vendor_id: '',
payment_account_id: '',
payment_date: moment(new Date()).format('YYYY-MM-DD'),
reference: '',
payment_number: '',
statement: '',
currency_code: '',
branch_id: '',
exchange_rate: 1,
entries: [],
};
export const transformToEditForm = (paymentMade, paymentMadeEntries) => {
return {
...transformToForm(paymentMade, defaultPaymentMade),
full_amount: safeSumBy(paymentMadeEntries, 'payment_amount'),
entries: [
...paymentMadeEntries.map((paymentMadeEntry) => ({
...transformToForm(paymentMadeEntry, defaultPaymentMadeEntry),
payment_amount: paymentMadeEntry.payment_amount || '',
})),
],
};
};
/**
* Transform the new page entries.
*/
export const transformToNewPageEntries = (entries) => {
return entries.map((entry) => ({
...transformToForm(entry, defaultPaymentMadeEntry),
payment_amount: '',
currency_code: entry.currency_code,
}));
};
/**
* Detarmines vendors fast field when update.
*/
export const vendorsFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.vendors !== oldProps.vendors ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Detarmines accounts fast field when update.
*/
export const accountsFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.accounts !== oldProps.accounts ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Transformes the form values to request body.
*/
export const transformFormToRequest = (form) => {
// Filters entries that have no `bill_id` or `payment_amount`.
const entries = form.entries
.filter((item) => item.bill_id && item.payment_amount)
.map((entry) => ({
...pick(entry, ['payment_amount', 'bill_id']),
}));
return { ...form, entries: orderingLinesIndexes(entries) };
};
export const useSetPrimaryBranchToForm = () => {
const { setFieldValue } = useFormikContext();
const { branches, isBranchesSuccess } = usePaymentMadeFormContext();
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_NUMBER_NOT_UNIQUE')) {
setFieldError('payment_number', intl.get('payment_number_is_not_unique'));
}
if (getError('WITHDRAWAL_ACCOUNT_CURRENCY_INVALID')) {
AppToaster.show({
message: intl.get(
'payment_made.error.withdrawal_account_currency_invalid',
),
intent: Intent.DANGER,
});
}
};
export const usePaymentMadeTotals = () => {
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,
};
};
/**
* Detarmines whether the bill has foreign customer.
* @returns {boolean}
*/
export const usePaymentMadeIsForeignCustomer = () => {
const { values } = useFormikContext();
const currentOrganization = useCurrentOrganization();
const isForeignCustomer = React.useMemo(
() => values.currency_code !== currentOrganization.base_currency,
[values.currency_code, currentOrganization.base_currency],
);
return isForeignCustomer;
};