mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-18 13:50:31 +00:00
chrone: sperate client and server to different repos.
This commit is contained in:
296
src/containers/Sales/Estimate/EstimatesDataTable.js
Normal file
296
src/containers/Sales/Estimate/EstimatesDataTable.js
Normal file
@@ -0,0 +1,296 @@
|
||||
import React, { useCallback, useMemo } from 'react';
|
||||
import {
|
||||
Intent,
|
||||
Button,
|
||||
Popover,
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuDivider,
|
||||
Position,
|
||||
Tag,
|
||||
} from '@blueprintjs/core';
|
||||
import classNames from 'classnames';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import intl from 'react-intl-universal';
|
||||
import moment from 'moment';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { compose, saveInvoke } from 'utils';
|
||||
import { useIsValuePassed } from 'hooks';
|
||||
|
||||
import LoadingIndicator from 'components/LoadingIndicator';
|
||||
import { DataTable, Money, Choose, Icon, If } from 'components';
|
||||
import EstimatesEmptyStatus from './EstimatesEmptyStatus';
|
||||
import { statusAccessor } from './components';
|
||||
import withEstimates from './withEstimates';
|
||||
import withEstimateActions from './withEstimateActions';
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
// Estimates transactions datatable.
|
||||
function EstimatesDataTable({
|
||||
// #withEstimates
|
||||
estimatesCurrentPage,
|
||||
estimatesLoading,
|
||||
estimatesPageination,
|
||||
estimatesTableQuery,
|
||||
estimatesCurrentViewId,
|
||||
|
||||
// #withEstimatesActions
|
||||
addEstimatesTableQueries,
|
||||
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
|
||||
// #ownProps
|
||||
onEditEstimate,
|
||||
onDeleteEstimate,
|
||||
onDeliverEstimate,
|
||||
onApproveEstimate,
|
||||
onRejectEstimate,
|
||||
onDrawerEstimate,
|
||||
onSelectedRowsChange,
|
||||
}) {
|
||||
const isLoaded = useIsValuePassed(estimatesLoading, false);
|
||||
|
||||
const handleEditEstimate = useCallback(
|
||||
(estimate) => () => {
|
||||
saveInvoke(onEditEstimate, estimate);
|
||||
},
|
||||
[onEditEstimate],
|
||||
);
|
||||
|
||||
const handleDeleteEstimate = useCallback(
|
||||
(estimate) => () => {
|
||||
saveInvoke(onDeleteEstimate, estimate);
|
||||
},
|
||||
[onDeleteEstimate],
|
||||
);
|
||||
|
||||
const actionMenuList = useCallback(
|
||||
(estimate) => (
|
||||
<Menu>
|
||||
<MenuItem
|
||||
icon={<Icon icon="reader-18" />}
|
||||
text={intl.get('view_details')}
|
||||
/>
|
||||
<MenuDivider />
|
||||
<MenuItem
|
||||
icon={<Icon icon="pen-18" />}
|
||||
text={intl.get('edit_estimate')}
|
||||
onClick={handleEditEstimate(estimate)}
|
||||
/>
|
||||
<If condition={!estimate.is_delivered}>
|
||||
<MenuItem
|
||||
text={intl.get('mark_as_delivered')}
|
||||
onClick={() => onDeliverEstimate(estimate)}
|
||||
/>
|
||||
</If>
|
||||
<Choose>
|
||||
<Choose.When
|
||||
condition={estimate.is_delivered && estimate.is_approved}
|
||||
>
|
||||
<MenuItem
|
||||
text={intl.get('mark_as_rejected')}
|
||||
onClick={() => onRejectEstimate(estimate)}
|
||||
/>
|
||||
</Choose.When>
|
||||
<Choose.When
|
||||
condition={estimate.is_delivered && estimate.is_rejected}
|
||||
>
|
||||
<MenuItem
|
||||
text={intl.get('mark_as_approved')}
|
||||
onClick={() => onApproveEstimate(estimate)}
|
||||
/>
|
||||
</Choose.When>
|
||||
<Choose.When condition={estimate.is_delivered}>
|
||||
<MenuItem
|
||||
text={intl.get('mark_as_approved')}
|
||||
onClick={() => onApproveEstimate(estimate)}
|
||||
/>
|
||||
<MenuItem
|
||||
text={intl.get('mark_as_rejected')}
|
||||
onClick={() => onRejectEstimate(estimate)}
|
||||
/>
|
||||
</Choose.When>
|
||||
</Choose>
|
||||
<MenuItem
|
||||
text={intl.get('estimate_paper')}
|
||||
onClick={() => onDrawerEstimate()}
|
||||
/>
|
||||
|
||||
<MenuItem
|
||||
text={intl.get('delete_estimate')}
|
||||
intent={Intent.DANGER}
|
||||
onClick={handleDeleteEstimate(estimate)}
|
||||
icon={<Icon icon="trash-16" iconSize={16} />}
|
||||
/>
|
||||
</Menu>
|
||||
),
|
||||
[handleDeleteEstimate, handleEditEstimate],
|
||||
);
|
||||
|
||||
const onRowContextMenu = useCallback(
|
||||
(cell) => {
|
||||
return actionMenuList(cell.row.original);
|
||||
},
|
||||
[actionMenuList],
|
||||
);
|
||||
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{
|
||||
id: 'estimate_date',
|
||||
Header: intl.get('estimate_date'),
|
||||
accessor: (r) => moment(r.estimate_date).format('YYYY MMM DD'),
|
||||
width: 140,
|
||||
className: 'estimate_date',
|
||||
},
|
||||
{
|
||||
id: 'customer_id',
|
||||
Header: intl.get('customer_name'),
|
||||
accessor: 'customer.display_name',
|
||||
width: 140,
|
||||
className: 'customer_id',
|
||||
},
|
||||
{
|
||||
id: 'expiration_date',
|
||||
Header: intl.get('expiration_date'),
|
||||
accessor: (r) => moment(r.expiration_date).format('YYYY MMM DD'),
|
||||
width: 140,
|
||||
className: 'expiration_date',
|
||||
},
|
||||
{
|
||||
id: 'estimate_number',
|
||||
Header: intl.get('estimate_number'),
|
||||
accessor: (row) =>
|
||||
row.estimate_number ? `#${row.estimate_number}` : null,
|
||||
width: 140,
|
||||
className: 'estimate_number',
|
||||
},
|
||||
{
|
||||
id: 'amount',
|
||||
Header: intl.get('amount'),
|
||||
accessor: (r) => <Money amount={r.amount} currency={base_currency} />,
|
||||
|
||||
width: 140,
|
||||
className: 'amount',
|
||||
},
|
||||
|
||||
{
|
||||
id: 'status',
|
||||
Header: intl.get('status'),
|
||||
accessor: (row) => statusAccessor(row),
|
||||
width: 140,
|
||||
className: 'status',
|
||||
},
|
||||
|
||||
{
|
||||
id: 'reference',
|
||||
Header: intl.get('reference_no'),
|
||||
accessor: 'reference',
|
||||
width: 140,
|
||||
className: 'reference',
|
||||
},
|
||||
|
||||
{
|
||||
id: 'actions',
|
||||
Header: '',
|
||||
Cell: ({ cell }) => (
|
||||
<Popover
|
||||
content={actionMenuList(cell.row.original)}
|
||||
position={Position.RIGHT_BOTTOM}
|
||||
>
|
||||
<Button icon={<Icon icon="more-h-16" iconSize={16} />} />
|
||||
</Popover>
|
||||
),
|
||||
className: 'actions',
|
||||
width: 50,
|
||||
disableResizing: true,
|
||||
},
|
||||
],
|
||||
[actionMenuList],
|
||||
);
|
||||
|
||||
const handleFetchData = useCallback(
|
||||
({ pageIndex, pageSize, sortBy }) => {
|
||||
const page = pageIndex + 1;
|
||||
|
||||
addEstimatesTableQueries({
|
||||
...(sortBy.length > 0
|
||||
? {
|
||||
column_sort_by: sortBy[0].id,
|
||||
sort_order: sortBy[0].desc ? 'desc' : 'asc',
|
||||
}
|
||||
: {}),
|
||||
page_size: pageSize,
|
||||
page,
|
||||
});
|
||||
},
|
||||
[addEstimatesTableQueries],
|
||||
);
|
||||
|
||||
const handleSelectedRowsChange = useCallback(
|
||||
(selectedRows) => {
|
||||
saveInvoke(
|
||||
onSelectedRowsChange,
|
||||
selectedRows.map((s) => s.original),
|
||||
);
|
||||
},
|
||||
[onSelectedRowsChange],
|
||||
);
|
||||
|
||||
const showEmptyStatus = [
|
||||
estimatesCurrentPage.length === 0,
|
||||
estimatesCurrentViewId === -1,
|
||||
].every((d) => d === true);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.DASHBOARD_DATATABLE)}>
|
||||
<LoadingIndicator loading={estimatesLoading && !isLoaded} mount={false}>
|
||||
<Choose>
|
||||
<Choose.When condition={showEmptyStatus}>
|
||||
<EstimatesEmptyStatus />
|
||||
</Choose.When>
|
||||
|
||||
<Choose.Otherwise>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={estimatesCurrentPage}
|
||||
onFetchData={handleFetchData}
|
||||
manualSortBy={true}
|
||||
selectionColumn={true}
|
||||
noInitialFetch={true}
|
||||
sticky={true}
|
||||
onSelectedRowsChange={handleSelectedRowsChange}
|
||||
rowContextMenu={onRowContextMenu}
|
||||
pagination={true}
|
||||
pagesCount={estimatesPageination.pagesCount}
|
||||
initialPageSize={estimatesTableQuery.page_size}
|
||||
initialPageIndex={estimatesTableQuery.page - 1}
|
||||
/>
|
||||
</Choose.Otherwise>
|
||||
</Choose>
|
||||
</LoadingIndicator>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withEstimateActions,
|
||||
withEstimates(
|
||||
({
|
||||
estimatesCurrentPage,
|
||||
estimatesLoading,
|
||||
estimatesPageination,
|
||||
estimatesTableQuery,
|
||||
estimatesCurrentViewId,
|
||||
}) => ({
|
||||
estimatesCurrentPage,
|
||||
estimatesLoading,
|
||||
estimatesPageination,
|
||||
estimatesTableQuery,
|
||||
estimatesCurrentViewId,
|
||||
}),
|
||||
),
|
||||
withCurrentOrganization(),
|
||||
)(EstimatesDataTable);
|
||||
@@ -0,0 +1,27 @@
|
||||
import React, { lazy } from 'react';
|
||||
import { Drawer, DrawerSuspense } from 'components';
|
||||
import withDrawers from 'containers/Drawer/withDrawers';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
const EstimateDrawerContent = lazy(() => import('./EstimateDrawerContent'));
|
||||
|
||||
/**
|
||||
* Estimate drawer.
|
||||
*/
|
||||
function EstimateDrawer({
|
||||
name,
|
||||
//#withDrawer
|
||||
isOpen,
|
||||
payload: { estimateId },
|
||||
}) {
|
||||
return (
|
||||
<Drawer isOpen={isOpen} name={name}>
|
||||
<DrawerSuspense>
|
||||
<EstimateDrawerContent estimateId={estimateId} />
|
||||
</DrawerSuspense>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withDrawers())(EstimateDrawer);
|
||||
@@ -0,0 +1,17 @@
|
||||
import React from 'react';
|
||||
import { EstimateDrawerProvider } from './EstimateDrawerProvider';
|
||||
import EstimatePaper from './EstimatePaper';
|
||||
|
||||
/**
|
||||
* Estimate drawer content.
|
||||
*/
|
||||
export default function EstimateDrawerContent({
|
||||
// #ownProp
|
||||
estimateId,
|
||||
}) {
|
||||
return (
|
||||
<EstimateDrawerProvider estimateId={estimateId}>
|
||||
<EstimatePaper />
|
||||
</EstimateDrawerProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import React, { createContext } from 'react';
|
||||
import { useEstimate } from 'hooks/query';
|
||||
import { DrawerHeaderContent, DashboardInsider } from 'components';
|
||||
|
||||
const EstimateDrawerContext = createContext();
|
||||
|
||||
/**
|
||||
* Estimate drawer provider.
|
||||
*/
|
||||
|
||||
function EstimateDrawerProvider({ estimateId, ...props }) {
|
||||
const {
|
||||
data: { entries, ...estimate },
|
||||
isLoading: isEstimateLoading,
|
||||
} = useEstimate(estimateId, { enabled: !!estimateId });
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
estimateId,
|
||||
estimate,
|
||||
entries,
|
||||
isEstimateLoading,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider loading={isEstimateLoading}>
|
||||
<DrawerHeaderContent name={'estimate-drawer'} />
|
||||
<EstimateDrawerContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
const useEstimateDrawerContext = () => React.useContext(EstimateDrawerContext);
|
||||
|
||||
export { EstimateDrawerProvider, useEstimateDrawerContext };
|
||||
@@ -0,0 +1,11 @@
|
||||
import React from 'react';
|
||||
import { useEstimateDrawerContext } from './EstimateDrawerProvider';
|
||||
import PaperTemplate from 'containers/Drawers/PaperTemplate/PaperTemplate';
|
||||
|
||||
/**
|
||||
* Estimate paper.
|
||||
*/
|
||||
export default function EstimatePaper() {
|
||||
const { estimate, entries } = useEstimateDrawerContext();
|
||||
return <PaperTemplate paperData={estimate} entries={entries} />;
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Intent,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
Popover,
|
||||
PopoverInteractionKind,
|
||||
Position,
|
||||
Menu,
|
||||
MenuItem,
|
||||
} from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import classNames from 'classnames';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { If, Icon } from 'components';
|
||||
import { useEstimateFormContext } from './EstimateFormProvider';
|
||||
|
||||
/**
|
||||
* Estimate floating actions bar.
|
||||
*/
|
||||
export default function EstimateFloatingActions() {
|
||||
const history = useHistory();
|
||||
const { resetForm, submitForm, isSubmitting } = useFormikContext();
|
||||
|
||||
// Estimate form context.
|
||||
const { estimate, setSubmitPayload } = useEstimateFormContext();
|
||||
|
||||
// Handle submit & deliver button click.
|
||||
const handleSubmitDeliverBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, deliver: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, deliver & new button click.
|
||||
const handleSubmitDeliverAndNewBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, deliver: true, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, deliver & continue editing button click.
|
||||
const handleSubmitDeliverContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, deliver: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit as draft button click.
|
||||
const handleSubmitDraftBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, deliver: false });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit as draft & new button click.
|
||||
const handleSubmitDraftAndNewBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, deliver: false, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit as draft & continue editing button click.
|
||||
const handleSubmitDraftContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, deliver: false });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
const handleCancelBtnClick = (event) => {
|
||||
history.goBack();
|
||||
|
||||
};
|
||||
|
||||
const handleClearBtnClick = (event) => {
|
||||
resetForm();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
|
||||
{/* ----------- Save And Deliver ----------- */}
|
||||
<If condition={!estimate || !estimate?.is_delivered}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
onClick={handleSubmitDeliverBtnClick}
|
||||
text={<T id={'save_and_deliver'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'deliver_and_new'} />}
|
||||
onClick={handleSubmitDeliverAndNewBtnClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'deliver_continue_editing'} />}
|
||||
onClick={handleSubmitDeliverContinueEditingBtnClick}
|
||||
/>
|
||||
</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>
|
||||
|
||||
{/* ----------- Save As Draft ----------- */}
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
className={'ml1'}
|
||||
onClick={handleSubmitDraftBtnClick}
|
||||
text={<T id={'save_as_draft'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitDraftAndNewBtnClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'save_continue_editing'} />}
|
||||
onClick={handleSubmitDraftContinueEditingBtnClick}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
minimal={true}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
|
||||
/>
|
||||
</Popover>
|
||||
</ButtonGroup>
|
||||
</If>
|
||||
|
||||
{/* ----------- Save and New ----------- */}
|
||||
<If condition={estimate && estimate?.is_delivered}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
onClick={handleSubmitDeliverBtnClick}
|
||||
text={<T id={'save'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitDeliverAndNewBtnClick}
|
||||
/>
|
||||
</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>
|
||||
</If>
|
||||
|
||||
{/* ----------- Clear & Reset----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
disabled={isSubmitting}
|
||||
onClick={handleClearBtnClick}
|
||||
text={estimate ? <T id={'reset'} /> : <T id={'clear'} />}
|
||||
/>
|
||||
|
||||
{/* ----------- Cancel ----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
disabled={isSubmitting}
|
||||
onClick={handleCancelBtnClick}
|
||||
text={<T id={'cancel'} />}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
191
src/containers/Sales/Estimates/EstimateForm/EstimateForm.js
Normal file
191
src/containers/Sales/Estimates/EstimateForm/EstimateForm.js
Normal file
@@ -0,0 +1,191 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Formik, Form } from 'formik';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import intl from 'react-intl-universal';
|
||||
import { omit, sumBy, isEmpty } from 'lodash';
|
||||
import classNames from 'classnames';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import {
|
||||
CreateEstimateFormSchema,
|
||||
EditEstimateFormSchema,
|
||||
} from './EstimateForm.schema';
|
||||
|
||||
import EstimateFormHeader from './EstimateFormHeader';
|
||||
import EstimateItemsEntriesField from './EstimateItemsEntriesField';
|
||||
import EstimateFloatingActions from './EstimateFloatingActions';
|
||||
import EstimateFormFooter from './EstimateFormFooter';
|
||||
import EstimateFormDialogs from './EstimateFormDialogs';
|
||||
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import { AppToaster } from 'components';
|
||||
import { ERROR } from 'common/errors';
|
||||
import { compose, transactionNumber, orderingLinesIndexes } from 'utils';
|
||||
import { useEstimateFormContext } from './EstimateFormProvider';
|
||||
import { transformToEditForm, defaultEstimate } from './utils';
|
||||
|
||||
/**
|
||||
* Estimate form.
|
||||
*/
|
||||
function EstimateForm({
|
||||
// #withSettings
|
||||
estimateNextNumber,
|
||||
estimateNumberPrefix,
|
||||
estimateIncrementMode,
|
||||
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
const history = useHistory();
|
||||
const {
|
||||
estimate,
|
||||
isNewMode,
|
||||
submitPayload,
|
||||
createEstimateMutate,
|
||||
editEstimateMutate,
|
||||
} = useEstimateFormContext();
|
||||
|
||||
const estimateNumber = transactionNumber(
|
||||
estimateNumberPrefix,
|
||||
estimateNextNumber,
|
||||
);
|
||||
|
||||
// Initial values in create and edit mode.
|
||||
const initialValues = useMemo(
|
||||
() => ({
|
||||
...(!isEmpty(estimate)
|
||||
? { ...transformToEditForm(estimate), currency_code: base_currency }
|
||||
: {
|
||||
...defaultEstimate,
|
||||
...(estimateIncrementMode && {
|
||||
estimate_number: estimateNumber,
|
||||
}),
|
||||
entries: orderingLinesIndexes(defaultEstimate.entries),
|
||||
currency_code: base_currency,
|
||||
}),
|
||||
}),
|
||||
[estimate, estimateNumber, estimateIncrementMode],
|
||||
);
|
||||
|
||||
// Transform response errors to fields.
|
||||
const handleErrors = (errors, { setErrors }) => {
|
||||
if (errors.some((e) => e.type === ERROR.ESTIMATE_NUMBER_IS_NOT_UNQIUE)) {
|
||||
setErrors({
|
||||
estimate_number: intl.get('estimate_number_is_not_unqiue'),
|
||||
});
|
||||
}
|
||||
if (
|
||||
errors.some((error) => error.type === ERROR.SALE_ESTIMATE_NO_IS_REQUIRED)
|
||||
) {
|
||||
setErrors({
|
||||
estimate_number: intl.get('estimate.field.error.estimate_number_required'),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Handles form submit.
|
||||
const handleFormSubmit = (
|
||||
values,
|
||||
{ setSubmitting, setErrors, resetForm },
|
||||
) => {
|
||||
setSubmitting(true);
|
||||
|
||||
const entries = values.entries.filter(
|
||||
(item) => item.item_id && item.quantity,
|
||||
);
|
||||
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
|
||||
|
||||
// Validate the entries quantity should be bigger than zero.
|
||||
if (totalQuantity === 0) {
|
||||
AppToaster.show({
|
||||
message: intl.get('quantity_cannot_be_zero_or_empty'),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
const form = {
|
||||
...omit(values, ['estimate_number_manually', 'estimate_number']),
|
||||
...(values.estimate_number_manually && {
|
||||
estimate_number: values.estimate_number,
|
||||
}),
|
||||
delivered: submitPayload.deliver,
|
||||
entries: entries.map((entry) => ({ ...omit(entry, ['total']) })),
|
||||
};
|
||||
const onSuccess = (response) => {
|
||||
AppToaster.show({
|
||||
message: intl.get(
|
||||
isNewMode
|
||||
? 'the_estimate_has_been_created_successfully'
|
||||
: 'the_estimate_has_been_edited_successfully',
|
||||
{ number: values.estimate_number },
|
||||
),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
|
||||
if (submitPayload.redirect) {
|
||||
history.push('/estimates');
|
||||
}
|
||||
if (submitPayload.resetForm) {
|
||||
resetForm();
|
||||
}
|
||||
};
|
||||
|
||||
const onError = ({
|
||||
response: {
|
||||
data: { errors },
|
||||
},
|
||||
}) => {
|
||||
if (errors) {
|
||||
handleErrors(errors, { setErrors });
|
||||
}
|
||||
setSubmitting(false);
|
||||
};
|
||||
if (!isNewMode) {
|
||||
editEstimateMutate([estimate.id, form]).then(onSuccess).catch(onError);
|
||||
} else {
|
||||
createEstimateMutate(form).then(onSuccess).catch(onError);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
CLASSES.PAGE_FORM,
|
||||
CLASSES.PAGE_FORM_STRIP_STYLE,
|
||||
CLASSES.PAGE_FORM_ESTIMATE,
|
||||
)}
|
||||
>
|
||||
<Formik
|
||||
validationSchema={
|
||||
isNewMode ? CreateEstimateFormSchema : EditEstimateFormSchema
|
||||
}
|
||||
initialValues={initialValues}
|
||||
onSubmit={handleFormSubmit}
|
||||
>
|
||||
<Form>
|
||||
<EstimateFormHeader />
|
||||
<EstimateItemsEntriesField />
|
||||
<EstimateFormFooter />
|
||||
<EstimateFloatingActions />
|
||||
|
||||
<EstimateFormDialogs />
|
||||
</Form>
|
||||
</Formik>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withSettings(({ estimatesSettings }) => ({
|
||||
estimateNextNumber: estimatesSettings?.nextNumber,
|
||||
estimateNumberPrefix: estimatesSettings?.numberPrefix,
|
||||
estimateIncrementMode: estimatesSettings?.autoIncrement,
|
||||
})),
|
||||
withCurrentOrganization(),
|
||||
)(EstimateForm);
|
||||
@@ -0,0 +1,54 @@
|
||||
import * as Yup from 'yup';
|
||||
import intl from 'react-intl-universal';
|
||||
import { DATATYPES_LENGTH } from 'common/dataTypes';
|
||||
import { isBlank } from 'utils';
|
||||
|
||||
const Schema = Yup.object().shape({
|
||||
customer_id: Yup.number()
|
||||
.label(intl.get('customer_name_'))
|
||||
.required(),
|
||||
estimate_date: Yup.date()
|
||||
.required()
|
||||
.label(intl.get('estimate_date_')),
|
||||
expiration_date: Yup.date()
|
||||
.required()
|
||||
.label(intl.get('expiration_date_')),
|
||||
estimate_number: Yup.string()
|
||||
.max(DATATYPES_LENGTH.STRING)
|
||||
.label(intl.get('estimate_number_')),
|
||||
reference: Yup.string().min(1).max(DATATYPES_LENGTH.STRING).nullable(),
|
||||
note: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(DATATYPES_LENGTH.STRING)
|
||||
.label(intl.get('note')),
|
||||
terms_conditions: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(DATATYPES_LENGTH.TEXT)
|
||||
.label(intl.get('note')),
|
||||
delivered: Yup.boolean(),
|
||||
entries: Yup.array().of(
|
||||
Yup.object().shape({
|
||||
quantity: Yup.number()
|
||||
.nullable()
|
||||
.max(DATATYPES_LENGTH.INT_10)
|
||||
.when(['rate'], {
|
||||
is: (rate) => rate,
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
rate: Yup.number().nullable().max(DATATYPES_LENGTH.INT_10),
|
||||
item_id: Yup.number()
|
||||
.nullable()
|
||||
.when(['quantity', 'rate'], {
|
||||
is: (quantity, rate) => !isBlank(quantity) && !isBlank(rate),
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
discount: Yup.number().nullable().min(0).max(100),
|
||||
description: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export const CreateEstimateFormSchema = Schema;
|
||||
export const EditEstimateFormSchema = Schema;
|
||||
@@ -0,0 +1,25 @@
|
||||
import React from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import EstimateNumberDialog from 'containers/Dialogs/EstimateNumberDialog';
|
||||
|
||||
/**
|
||||
* Estimate form dialogs.
|
||||
*/
|
||||
export default function EstimateFormDialogs() {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
|
||||
// Update the form once the invoice number form submit confirm.
|
||||
const handleEstimateNumberFormConfirm = ({ incrementNumber, manually }) => {
|
||||
setFieldValue('estimate_number', incrementNumber || '');
|
||||
setFieldValue('estimate_number_manually', manually);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<EstimateNumberDialog
|
||||
dialogName={'estimate-number-form'}
|
||||
onConfirm={handleEstimateNumberFormConfirm}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import React from 'react';
|
||||
import { FormGroup, TextArea } from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { FastField } from 'formik';
|
||||
import classNames from 'classnames';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { Row, Col, Postbox } from 'components';
|
||||
import Dragzone from 'components/Dragzone';
|
||||
|
||||
import { inputIntent } from 'utils';
|
||||
|
||||
/**
|
||||
* Estimate form footer.
|
||||
*/
|
||||
export default function EstiamteFormFooter({}) {
|
||||
return (
|
||||
<div class={classNames(CLASSES.PAGE_FORM_FOOTER)}>
|
||||
<Postbox title={<T id={'estimate_details'} />} defaultOpen={false}>
|
||||
<Row>
|
||||
<Col md={8}>
|
||||
{/* --------- Customer Note --------- */}
|
||||
<FastField name={'note'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'customer_note'} />}
|
||||
className={'form-group--customer_note'}
|
||||
intent={inputIntent({ error, touched })}
|
||||
>
|
||||
<TextArea growVertically={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* --------- Terms and conditions --------- */}
|
||||
<FastField name={'terms_conditions'}>
|
||||
{({ field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'terms_conditions'} />}
|
||||
className={'form-group--terms_conditions'}
|
||||
intent={inputIntent({ error, touched })}
|
||||
>
|
||||
<TextArea growVertically={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</Col>
|
||||
|
||||
<Col md={4}>
|
||||
<Dragzone
|
||||
initialFiles={[]}
|
||||
// onDrop={handleDropFiles}
|
||||
// onDeleteFile={handleDeleteFile}
|
||||
hint={<T id={'attachments_maximum'} />}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</Postbox>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { useFormikContext } from 'formik';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import EstimateFormHeaderFields from './EstimateFormHeaderFields';
|
||||
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import { getEntriesTotal } from 'containers/Entries/utils';
|
||||
import { PageFormBigNumber } from 'components';
|
||||
import { compose } from 'utils';
|
||||
|
||||
// Estimate form top header.
|
||||
function EstimateFormHeader({
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
const { values } = useFormikContext();
|
||||
|
||||
// Calculate the total due amount of bill entries.
|
||||
const totalDueAmount = useMemo(
|
||||
() => getEntriesTotal(values.entries),
|
||||
[values.entries],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
|
||||
<EstimateFormHeaderFields />
|
||||
|
||||
<PageFormBigNumber
|
||||
label={intl.get('amount')}
|
||||
amount={totalDueAmount}
|
||||
currencyCode={base_currency}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withCurrentOrganization())(EstimateFormHeader);
|
||||
@@ -0,0 +1,215 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
FormGroup,
|
||||
InputGroup,
|
||||
Position,
|
||||
ControlGroup,
|
||||
} from '@blueprintjs/core';
|
||||
import { DateInput } from '@blueprintjs/datetime';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { FastField, ErrorMessage } from 'formik';
|
||||
import {
|
||||
momentFormatter,
|
||||
compose,
|
||||
tansformDateValue,
|
||||
inputIntent,
|
||||
handleDateChange,
|
||||
} from 'utils';
|
||||
import { customersFieldShouldUpdate } from './utils';
|
||||
import classNames from 'classnames';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import {
|
||||
ContactSelecetList,
|
||||
FieldRequiredHint,
|
||||
Icon,
|
||||
InputPrependButton,
|
||||
} from 'components';
|
||||
|
||||
import withDialogActions from 'containers/Dialog/withDialogActions';
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
|
||||
import { useObserveEstimateNoSettings } from './utils';
|
||||
import { useEstimateFormContext } from './EstimateFormProvider';
|
||||
|
||||
/**
|
||||
* Estimate form header.
|
||||
*/
|
||||
function EstimateFormHeader({
|
||||
// #withDialogActions
|
||||
openDialog,
|
||||
|
||||
// #withSettings
|
||||
estimateAutoIncrement,
|
||||
estimateNumberPrefix,
|
||||
estimateNextNumber,
|
||||
}) {
|
||||
const { customers } = useEstimateFormContext();
|
||||
|
||||
const handleEstimateNumberBtnClick = () => {
|
||||
openDialog('estimate-number-form', {});
|
||||
};
|
||||
|
||||
const handleEstimateNoBlur = (form, field) => (event) => {
|
||||
const newValue = event.target.value;
|
||||
|
||||
if (field.value !== newValue && estimateAutoIncrement) {
|
||||
openDialog('estimate-number-form', {
|
||||
initialFormValues: {
|
||||
manualTransactionNo: newValue,
|
||||
incrementMode: 'manual-transaction',
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Syncs estimate number settings with the form.
|
||||
useObserveEstimateNoSettings(estimateNumberPrefix, estimateNextNumber);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
|
||||
{/* ----------- Customer name ----------- */}
|
||||
<FastField
|
||||
name={'customer_id'}
|
||||
customers={customers}
|
||||
shouldUpdate={customersFieldShouldUpdate}
|
||||
>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'customer_name'} />}
|
||||
inline={true}
|
||||
className={classNames(CLASSES.FILL, 'form-group--customer')}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name={'customer_id'} />}
|
||||
>
|
||||
<ContactSelecetList
|
||||
contactsList={customers}
|
||||
selectedContactId={value}
|
||||
defaultSelectText={<T id={'select_customer_account'} />}
|
||||
onContactSelected={(customer) => {
|
||||
form.setFieldValue('customer_id', customer.id);
|
||||
}}
|
||||
popoverFill={true}
|
||||
intent={inputIntent({ error, touched })}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Estimate date ----------- */}
|
||||
<FastField name={'estimate_date'}>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'estimate_date'} />}
|
||||
inline={true}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
className={classNames(CLASSES.FILL, 'form-group--estimate-date')}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="estimate_date" />}
|
||||
>
|
||||
<DateInput
|
||||
{...momentFormatter('YYYY/MM/DD')}
|
||||
value={tansformDateValue(value)}
|
||||
onChange={handleDateChange((formattedDate) => {
|
||||
form.setFieldValue('estimate_date', formattedDate);
|
||||
})}
|
||||
popoverProps={{ position: Position.BOTTOM, minimal: true }}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Expiration date ----------- */}
|
||||
<FastField name={'expiration_date'}>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'expiration_date'} />}
|
||||
inline={true}
|
||||
className={classNames(
|
||||
CLASSES.FORM_GROUP_LIST_SELECT,
|
||||
CLASSES.FILL,
|
||||
'form-group--expiration-date',
|
||||
)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="expiration_date" />}
|
||||
>
|
||||
<DateInput
|
||||
{...momentFormatter('YYYY/MM/DD')}
|
||||
value={tansformDateValue(value)}
|
||||
onChange={handleDateChange((formattedDate) => {
|
||||
form.setFieldValue('expiration_date', formattedDate);
|
||||
})}
|
||||
popoverProps={{ position: Position.BOTTOM, minimal: true }}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Estimate number ----------- */}
|
||||
<FastField name={'estimate_number'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'estimate'} />}
|
||||
inline={true}
|
||||
className={('form-group--estimate-number', CLASSES.FILL)}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="estimate_number" />}
|
||||
>
|
||||
<ControlGroup fill={true}>
|
||||
<InputGroup
|
||||
minimal={true}
|
||||
value={field.value}
|
||||
asyncControl={true}
|
||||
onBlur={handleEstimateNoBlur(form, field)}
|
||||
/>
|
||||
<InputPrependButton
|
||||
buttonProps={{
|
||||
onClick: handleEstimateNumberBtnClick,
|
||||
icon: <Icon icon={'settings-18'} />,
|
||||
}}
|
||||
tooltip={true}
|
||||
tooltipProps={{
|
||||
content: (
|
||||
<T id={'setting_your_auto_generated_estimate_number'} />
|
||||
),
|
||||
position: Position.BOTTOM_LEFT,
|
||||
}}
|
||||
/>
|
||||
</ControlGroup>
|
||||
</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 minimal={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withDialogActions,
|
||||
withSettings(({ estimatesSettings }) => ({
|
||||
estimateNextNumber: estimatesSettings?.nextNumber,
|
||||
estimateNumberPrefix: estimatesSettings?.numberPrefix,
|
||||
estimateAutoIncrement: estimatesSettings?.autoIncrement,
|
||||
})),
|
||||
)(EstimateFormHeader);
|
||||
@@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
import 'style/pages/SaleEstimate/PageForm.scss';
|
||||
|
||||
import EstimateForm from './EstimateForm';
|
||||
import { EstimateFormProvider } from './EstimateFormProvider';
|
||||
|
||||
/**
|
||||
* Estimate form page.
|
||||
*/
|
||||
export default function EstimateFormPage() {
|
||||
const { id } = useParams();
|
||||
const idInteger = parseInt(id, 10);
|
||||
|
||||
return (
|
||||
<EstimateFormProvider estimateId={idInteger}>
|
||||
<EstimateForm />
|
||||
</EstimateFormProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import DashboardInsider from 'components/Dashboard/DashboardInsider';
|
||||
import {
|
||||
useEstimate,
|
||||
useCustomers,
|
||||
useItems,
|
||||
useSettingsEstimates,
|
||||
useCreateEstimate,
|
||||
useEditEstimate,
|
||||
} from 'hooks/query';
|
||||
import { ITEMS_FILTER_ROLES } from './utils';
|
||||
|
||||
const EstimateFormContext = createContext();
|
||||
|
||||
/**
|
||||
* Estimate form provider.
|
||||
*/
|
||||
function EstimateFormProvider({ estimateId, ...props }) {
|
||||
const {
|
||||
data: estimate,
|
||||
isFetching: isEstimateFetching,
|
||||
isLoading: isEstimateLoading,
|
||||
} = useEstimate(estimateId, { enabled: !!estimateId });
|
||||
|
||||
// Handle fetch Items data table or list
|
||||
const {
|
||||
data: { items },
|
||||
isFetching: isItemsFetching,
|
||||
isLoading: isItemsLoading,
|
||||
} = useItems({
|
||||
page_size: 10000,
|
||||
stringified_filter_roles: ITEMS_FILTER_ROLES,
|
||||
});
|
||||
|
||||
// Handle fetch customers data table or list
|
||||
const {
|
||||
data: { customers },
|
||||
isFetch: isCustomersFetching,
|
||||
isLoading: isCustomersLoading,
|
||||
} = useCustomers({ page_size: 10000 });
|
||||
|
||||
// Handle fetch settings.
|
||||
useSettingsEstimates();
|
||||
|
||||
// Form submit payload.
|
||||
const [submitPayload, setSubmitPayload] = React.useState({});
|
||||
|
||||
// Create and edit estimate form.
|
||||
const { mutateAsync: createEstimateMutate } = useCreateEstimate();
|
||||
const { mutateAsync: editEstimateMutate } = useEditEstimate();
|
||||
|
||||
const isNewMode = !estimateId;
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
estimateId,
|
||||
estimate,
|
||||
items,
|
||||
customers,
|
||||
isNewMode,
|
||||
|
||||
isItemsFetching,
|
||||
isEstimateFetching,
|
||||
|
||||
isCustomersLoading,
|
||||
isItemsLoading,
|
||||
isEstimateLoading,
|
||||
|
||||
submitPayload,
|
||||
setSubmitPayload,
|
||||
|
||||
createEstimateMutate,
|
||||
editEstimateMutate,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={isCustomersLoading || isItemsLoading || isEstimateLoading}
|
||||
name={'estimate-form'}
|
||||
>
|
||||
<EstimateFormContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const useEstimateFormContext = () => useContext(EstimateFormContext);
|
||||
|
||||
export { EstimateFormProvider, useEstimateFormContext };
|
||||
@@ -0,0 +1,41 @@
|
||||
import React from 'react';
|
||||
import { FastField } from 'formik';
|
||||
import classNames from 'classnames';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import ItemsEntriesTable from 'containers/Entries/ItemsEntriesTable';
|
||||
import { useEstimateFormContext } from './EstimateFormProvider';
|
||||
import { entriesFieldShouldUpdate } from './utils';
|
||||
|
||||
/**
|
||||
* Estimate form items entries editor.
|
||||
*/
|
||||
export default function EstimateFormItemsEntriesField() {
|
||||
const { items } = useEstimateFormContext();
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
|
||||
<FastField
|
||||
name={'entries'}
|
||||
items={items}
|
||||
shouldUpdate={entriesFieldShouldUpdate}
|
||||
>
|
||||
{({
|
||||
form: { values, setFieldValue },
|
||||
field: { value },
|
||||
meta: { error, touched },
|
||||
}) => (
|
||||
<ItemsEntriesTable
|
||||
entries={value}
|
||||
onUpdateData={(entries) => {
|
||||
setFieldValue('entries', entries);
|
||||
}}
|
||||
items={items}
|
||||
errors={error}
|
||||
linesNumber={4}
|
||||
currencyCode={values.currency_code}
|
||||
/>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
108
src/containers/Sales/Estimates/EstimateForm/utils.js
Normal file
108
src/containers/Sales/Estimates/EstimateForm/utils.js
Normal file
@@ -0,0 +1,108 @@
|
||||
import React from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import moment from 'moment';
|
||||
import * as R from 'ramda';
|
||||
import {
|
||||
defaultFastFieldShouldUpdate,
|
||||
transactionNumber,
|
||||
repeatValue,
|
||||
transformToForm,
|
||||
} from 'utils';
|
||||
import {
|
||||
updateItemsEntriesTotal,
|
||||
ensureEntriesHaveEmptyLine,
|
||||
} from 'containers/Entries/utils';
|
||||
|
||||
export const MIN_LINES_NUMBER = 4;
|
||||
|
||||
export const defaultEstimateEntry = {
|
||||
index: 0,
|
||||
item_id: '',
|
||||
rate: '',
|
||||
discount: '',
|
||||
quantity: '',
|
||||
description: '',
|
||||
amount: '',
|
||||
};
|
||||
|
||||
export const defaultEstimate = {
|
||||
customer_id: '',
|
||||
estimate_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
expiration_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
estimate_number: '',
|
||||
delivered: '',
|
||||
reference: '',
|
||||
note: '',
|
||||
terms_conditions: '',
|
||||
entries: [...repeatValue(defaultEstimateEntry, MIN_LINES_NUMBER)],
|
||||
};
|
||||
|
||||
export const transformToEditForm = (estimate) => {
|
||||
const initialEntries = [
|
||||
...estimate.entries.map((estimate) => ({
|
||||
...transformToForm(estimate, defaultEstimateEntry),
|
||||
})),
|
||||
...repeatValue(
|
||||
defaultEstimateEntry,
|
||||
Math.max(MIN_LINES_NUMBER - estimate.entries.length, 0),
|
||||
),
|
||||
];
|
||||
const entries = R.compose(
|
||||
ensureEntriesHaveEmptyLine(defaultEstimateEntry),
|
||||
updateItemsEntriesTotal,
|
||||
)(initialEntries);
|
||||
|
||||
return {
|
||||
...transformToForm(estimate, defaultEstimate),
|
||||
entries
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Syncs estimate number of the settings with the context form.
|
||||
*/
|
||||
export const useObserveEstimateNoSettings = (prefix, nextNumber) => {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
|
||||
React.useEffect(() => {
|
||||
const estimateNo = transactionNumber(prefix, nextNumber);
|
||||
setFieldValue('estimate_number', estimateNo);
|
||||
}, [setFieldValue, prefix, nextNumber]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines customers fast field when update.
|
||||
*/
|
||||
export const customersFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.customers !== oldProps.customers ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines entries fast field should update.
|
||||
*/
|
||||
export const entriesFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.items !== oldProps.items ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
|
||||
export const ITEMS_FILTER_ROLES = JSON.stringify([
|
||||
{
|
||||
index: 1,
|
||||
fieldKey: 'sellable',
|
||||
value: true,
|
||||
condition: '&&',
|
||||
comparator: 'equals',
|
||||
},
|
||||
{
|
||||
index: 2,
|
||||
fieldKey: 'active',
|
||||
value: true,
|
||||
condition: '&&',
|
||||
comparator: 'equals',
|
||||
},
|
||||
]);
|
||||
19
src/containers/Sales/Estimates/EstimatesAlerts.js
Normal file
19
src/containers/Sales/Estimates/EstimatesAlerts.js
Normal file
@@ -0,0 +1,19 @@
|
||||
import React from 'react';
|
||||
import EstimateDeleteAlert from 'containers/Alerts/Estimates/EstimateDeleteAlert';
|
||||
import EstimateDeliveredAlert from 'containers/Alerts/Estimates/EstimateDeliveredAlert';
|
||||
import EstimateApproveAlert from 'containers/Alerts/Estimates/EstimateApproveAlert';
|
||||
import EstimateRejectAlert from 'containers/Alerts/Estimates/EstimateRejectAlert';
|
||||
|
||||
/**
|
||||
* Estimates alert.
|
||||
*/
|
||||
export default function EstimatesAlerts() {
|
||||
return (
|
||||
<div>
|
||||
<EstimateDeleteAlert name={'estimate-delete'} />
|
||||
<EstimateDeliveredAlert name={'estimate-deliver'} />
|
||||
<EstimateApproveAlert name={'estimate-Approve'} />
|
||||
<EstimateRejectAlert name={'estimate-reject'} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import React from 'react';
|
||||
import { MenuItem } from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
import { Choose, T, Icon } from 'components';
|
||||
|
||||
import { RESOURCES_TYPES } from "common/resourcesTypes";
|
||||
import withDrawerActions from "../../../Drawer/withDrawerActions";
|
||||
|
||||
/**
|
||||
* Estimate universal search item select action.
|
||||
*/
|
||||
function EstimateUniversalSearchSelectComponent({
|
||||
// #ownProps
|
||||
resourceType,
|
||||
resourceId,
|
||||
|
||||
// #withDrawerActions
|
||||
openDrawer,
|
||||
}) {
|
||||
if (resourceType === RESOURCES_TYPES.ESTIMATE) {
|
||||
openDrawer('estimate-detail-drawer', { estimateId: resourceId });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const EstimateUniversalSearchSelect = withDrawerActions(
|
||||
EstimateUniversalSearchSelectComponent,
|
||||
);
|
||||
|
||||
/**
|
||||
* Status accessor.
|
||||
*/
|
||||
export const EstimateStatus = ({ estimate }) => (
|
||||
<Choose>
|
||||
<Choose.When condition={estimate.is_delivered && estimate.is_approved}>
|
||||
<span class="approved">
|
||||
<T id={'approved'} />
|
||||
</span>
|
||||
</Choose.When>
|
||||
<Choose.When condition={estimate.is_delivered && estimate.is_rejected}>
|
||||
<span class="reject">
|
||||
<T id={'rejected'} />
|
||||
</span>
|
||||
</Choose.When>
|
||||
<Choose.When
|
||||
condition={
|
||||
estimate.is_delivered && !estimate.is_rejected && !estimate.is_approved
|
||||
}
|
||||
>
|
||||
<span class="delivered">
|
||||
<T id={'delivered'} />
|
||||
</span>
|
||||
</Choose.When>
|
||||
<Choose.Otherwise>
|
||||
<span class="draft">
|
||||
<T id={'draft'} />
|
||||
</span>
|
||||
</Choose.Otherwise>
|
||||
</Choose>
|
||||
);
|
||||
|
||||
/**
|
||||
* Estimate universal search item.
|
||||
*/
|
||||
export function EstimateUniversalSearchItem(
|
||||
item,
|
||||
{ handleClick, modifiers, query },
|
||||
) {
|
||||
return (
|
||||
<MenuItem
|
||||
active={modifiers.active}
|
||||
text={
|
||||
<div>
|
||||
<div>{item.text}</div>
|
||||
<span class="bp3-text-muted">
|
||||
{item.reference.estimate_number}{' '}
|
||||
<Icon icon={'caret-right-16'} iconSize={16} />
|
||||
{item.reference.formatted_estimate_date}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
label={
|
||||
<>
|
||||
<div class="amount">{item.reference.formatted_amount}</div>
|
||||
<EstimateStatus estimate={item.reference} />
|
||||
</>
|
||||
}
|
||||
onClick={handleClick}
|
||||
className={'universal-search__item--estimate'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformes the estimates to search items.
|
||||
*/
|
||||
const transformEstimatesToSearch = (estimate) => ({
|
||||
id: estimate.id,
|
||||
text: estimate.customer.display_name,
|
||||
label: estimate.formatted_balance,
|
||||
reference: estimate,
|
||||
});
|
||||
|
||||
/**
|
||||
* Estimate resource universal search bind configure.
|
||||
*/
|
||||
export const universalSearchEstimateBind = () => ({
|
||||
resourceType: RESOURCES_TYPES.ESTIMATE,
|
||||
optionItemLabel: intl.get('estimates'),
|
||||
selectItemAction: EstimateUniversalSearchSelect,
|
||||
itemRenderer: EstimateUniversalSearchItem,
|
||||
itemSelect: transformEstimatesToSearch
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import React from 'react';
|
||||
import Icon from 'components/Icon';
|
||||
import {
|
||||
Button,
|
||||
Classes,
|
||||
NavbarDivider,
|
||||
NavbarGroup,
|
||||
Intent,
|
||||
Alignment,
|
||||
} from '@blueprintjs/core';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
|
||||
import {
|
||||
AdvancedFilterPopover,
|
||||
If,
|
||||
DashboardActionViewsList,
|
||||
DashboardFilterButton,
|
||||
} from 'components';
|
||||
import DashboardActionsBar from 'components/Dashboard/DashboardActionsBar';
|
||||
|
||||
import withEstimatesActions from './withEstimatesActions';
|
||||
import withEstimates from './withEstimates';
|
||||
|
||||
import { useEstimatesListContext } from './EstimatesListProvider';
|
||||
import { useRefreshEstimates } from 'hooks/query/estimates';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
/**
|
||||
* Estimates list actions bar.
|
||||
*/
|
||||
function EstimateActionsBar({
|
||||
// #withEstimateActions
|
||||
setEstimatesTableState,
|
||||
|
||||
// #withEstimates
|
||||
estimatesFilterRoles,
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Estimates list context.
|
||||
const { estimatesViews, fields } = useEstimatesListContext();
|
||||
|
||||
// Handle click a new sale estimate.
|
||||
const onClickNewEstimate = () => {
|
||||
history.push('/estimates/new');
|
||||
};
|
||||
// Estimates refresh action.
|
||||
const { refresh } = useRefreshEstimates();
|
||||
|
||||
// Handle tab change.
|
||||
const handleTabChange = (view) => {
|
||||
setEstimatesTableState({
|
||||
viewSlug: view ? view.slug : null,
|
||||
});
|
||||
};
|
||||
|
||||
// Handle click a refresh sale estimates
|
||||
const handleRefreshBtnClick = () => {
|
||||
refresh();
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardActionsBar>
|
||||
<NavbarGroup>
|
||||
<DashboardActionViewsList
|
||||
resourceName={'estimates'}
|
||||
allMenuItem={true}
|
||||
allMenuItemText={<T id={'all'} />}
|
||||
views={estimatesViews}
|
||||
onChange={handleTabChange}
|
||||
/>
|
||||
<NavbarDivider />
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'plus'} />}
|
||||
text={<T id={'new_estimate'} />}
|
||||
onClick={onClickNewEstimate}
|
||||
/>
|
||||
<AdvancedFilterPopover
|
||||
advancedFilterProps={{
|
||||
conditions: estimatesFilterRoles,
|
||||
defaultFieldKey: 'estimate_number',
|
||||
fields: fields,
|
||||
onFilterChange: (filterConditions) => {
|
||||
setEstimatesTableState({ filterRoles: filterConditions });
|
||||
},
|
||||
}}
|
||||
>
|
||||
<DashboardFilterButton
|
||||
conditionsCount={estimatesFilterRoles.length}
|
||||
/>
|
||||
</AdvancedFilterPopover>
|
||||
|
||||
<If condition={false}>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'trash-16'} iconSize={16} />}
|
||||
text={<T id={'delete'} />}
|
||||
intent={Intent.DANGER}
|
||||
// onClick={handleBulkDelete}
|
||||
/>
|
||||
</If>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'print-16'} iconSize={'16'} />}
|
||||
text={<T id={'print'} />}
|
||||
/>
|
||||
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'file-import-16'} />}
|
||||
text={<T id={'import'} />}
|
||||
/>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'file-export-16'} iconSize={'16'} />}
|
||||
text={<T id={'export'} />}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
<NavbarGroup align={Alignment.RIGHT}>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon="refresh-16" iconSize={14} />}
|
||||
onClick={handleRefreshBtnClick}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
</DashboardActionsBar>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withEstimatesActions,
|
||||
withEstimates(({ estimatesTableState }) => ({
|
||||
estimatesFilterRoles: estimatesTableState.filterRoles,
|
||||
})),
|
||||
)(EstimateActionsBar);
|
||||
@@ -0,0 +1,158 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
import { DataTable, DashboardContentTable } from 'components';
|
||||
import EstimatesEmptyStatus from './EstimatesEmptyStatus';
|
||||
import TableSkeletonRows from 'components/Datatable/TableSkeletonRows';
|
||||
import TableSkeletonHeader from 'components/Datatable/TableHeaderSkeleton';
|
||||
|
||||
import withEstimatesActions from './withEstimatesActions';
|
||||
import withAlertsActions from 'containers/Alert/withAlertActions';
|
||||
import withDrawerActions from 'containers/Drawer/withDrawerActions';
|
||||
import withDialogActions from 'containers/Dialog/withDialogActions';
|
||||
|
||||
import { useEstimatesListContext } from './EstimatesListProvider';
|
||||
import { useMemorizedColumnsWidths } from 'hooks';
|
||||
import { ActionsMenu, useEstiamtesTableColumns } from './components';
|
||||
import { TABLES } from 'common/tables';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
/**
|
||||
* Estimates datatable.
|
||||
*/
|
||||
function EstimatesDataTable({
|
||||
// #withEstimatesActions
|
||||
setEstimatesTableState,
|
||||
|
||||
// #withAlertsActions
|
||||
openAlert,
|
||||
|
||||
// #withDrawerActions
|
||||
openDrawer,
|
||||
|
||||
// #withDialogAction
|
||||
openDialog,
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Estimates list context.
|
||||
const {
|
||||
estimates,
|
||||
pagination,
|
||||
isEmptyStatus,
|
||||
isEstimatesLoading,
|
||||
isEstimatesFetching,
|
||||
} = useEstimatesListContext();
|
||||
|
||||
// Estimates table columns.
|
||||
const columns = useEstiamtesTableColumns();
|
||||
|
||||
// Handle estimate edit action.
|
||||
const handleEditEstimate = (estimate) => {
|
||||
history.push(`/estimates/${estimate.id}/edit`);
|
||||
};
|
||||
// Handle estimate delete action.
|
||||
const handleDeleteEstimate = ({ id }) => {
|
||||
openAlert('estimate-delete', { estimateId: id });
|
||||
};
|
||||
|
||||
// Handle cancel/confirm estimate deliver.
|
||||
const handleDeliverEstimate = ({ id }) => {
|
||||
openAlert('estimate-deliver', { estimateId: id });
|
||||
};
|
||||
|
||||
// Handle cancel/confirm estimate approve.
|
||||
const handleApproveEstimate = ({ id }) => {
|
||||
openAlert('estimate-Approve', { estimateId: id });
|
||||
};
|
||||
|
||||
// Handle cancel/confirm estimate reject.
|
||||
const handleRejectEstimate = ({ id }) => {
|
||||
openAlert('estimate-reject', { estimateId: id });
|
||||
};
|
||||
|
||||
// Handle convent to invoice.
|
||||
const handleConvertToInvoice = ({ id }) => {
|
||||
history.push(`/invoices/new?from_estimate_id=${id}`, { action: id });
|
||||
};
|
||||
|
||||
// Handle view detail estimate.
|
||||
const handleViewDetailEstimate = ({ id }) => {
|
||||
openDrawer('estimate-detail-drawer', { estimateId: id });
|
||||
};
|
||||
|
||||
// Handle print estimate.
|
||||
const handlePrintEstimate = ({ id }) => {
|
||||
openDialog('estimate-pdf-preview', { estimateId: id });
|
||||
};
|
||||
|
||||
// Handle cell click.
|
||||
const handleCellClick = (cell, event) => {
|
||||
openDrawer('estimate-detail-drawer', { estimateId: cell.row.original.id });
|
||||
};
|
||||
|
||||
// Local storage memorizing columns widths.
|
||||
const [initialColumnsWidths, , handleColumnResizing] =
|
||||
useMemorizedColumnsWidths(TABLES.ESTIMATES);
|
||||
|
||||
// Handles fetch data.
|
||||
const handleFetchData = useCallback(
|
||||
({ pageIndex, pageSize, sortBy }) => {
|
||||
setEstimatesTableState({
|
||||
pageIndex,
|
||||
pageSize,
|
||||
sortBy,
|
||||
});
|
||||
},
|
||||
[setEstimatesTableState],
|
||||
);
|
||||
|
||||
// Display empty status instead of the table.
|
||||
if (isEmptyStatus) {
|
||||
return <EstimatesEmptyStatus />;
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardContentTable>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={estimates}
|
||||
loading={isEstimatesLoading}
|
||||
headerLoading={isEstimatesLoading}
|
||||
progressBarLoading={isEstimatesFetching}
|
||||
onFetchData={handleFetchData}
|
||||
noInitialFetch={true}
|
||||
manualSortBy={true}
|
||||
selectionColumn={true}
|
||||
sticky={true}
|
||||
pagination={true}
|
||||
manualPagination={true}
|
||||
pagesCount={pagination.pagesCount}
|
||||
TableLoadingRenderer={TableSkeletonRows}
|
||||
TableHeaderSkeletonRenderer={TableSkeletonHeader}
|
||||
ContextMenu={ActionsMenu}
|
||||
onCellClick={handleCellClick}
|
||||
initialColumnsWidths={initialColumnsWidths}
|
||||
onColumnResizing={handleColumnResizing}
|
||||
payload={{
|
||||
onApprove: handleApproveEstimate,
|
||||
onEdit: handleEditEstimate,
|
||||
onReject: handleRejectEstimate,
|
||||
onDeliver: handleDeliverEstimate,
|
||||
onDelete: handleDeleteEstimate,
|
||||
onConvert: handleConvertToInvoice,
|
||||
onViewDetails: handleViewDetailEstimate,
|
||||
onPrint: handlePrintEstimate,
|
||||
}}
|
||||
/>
|
||||
</DashboardContentTable>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withEstimatesActions,
|
||||
withAlertsActions,
|
||||
withDrawerActions,
|
||||
withDialogActions,
|
||||
)(EstimatesDataTable);
|
||||
@@ -0,0 +1,35 @@
|
||||
import React from 'react';
|
||||
import { Button, Intent } from '@blueprintjs/core';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { EmptyStatus } from 'components';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
|
||||
export default function EstimatesEmptyStatus() {
|
||||
const history = useHistory();
|
||||
return (
|
||||
<EmptyStatus
|
||||
title={<T id={'it_s_time_to_send_estimates_to_your_customers'} />}
|
||||
description={
|
||||
<p>
|
||||
<T id={'estimate_is_used_to_create_bid_proposal_or_quote'} />
|
||||
</p>
|
||||
}
|
||||
action={
|
||||
<>
|
||||
<Button
|
||||
intent={Intent.PRIMARY}
|
||||
large={true}
|
||||
onClick={() => {
|
||||
history.push('/estimates/new');
|
||||
}}
|
||||
>
|
||||
<T id={'new_sale_estimate'} />
|
||||
</Button>
|
||||
<Button intent={Intent.NONE} large={true}>
|
||||
<T id={'learn_more'} />
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import React from 'react';
|
||||
import { DashboardContentTable, DashboardPageContent } from 'components';
|
||||
|
||||
import 'style/pages/SaleEstimate/List.scss';
|
||||
|
||||
import EstimatesActionsBar from './EstimatesActionsBar';
|
||||
import EstimatesAlerts from '../EstimatesAlerts';
|
||||
import EstimatesViewTabs from './EstimatesViewTabs';
|
||||
import EstimatesDataTable from './EstimatesDataTable';
|
||||
|
||||
import withEstimates from './withEstimates';
|
||||
import withEstimatesActions from './withEstimatesActions';
|
||||
|
||||
import { EstimatesListProvider } from './EstimatesListProvider';
|
||||
import { compose, transformTableStateToQuery } from 'utils';
|
||||
|
||||
/**
|
||||
* Sale estimates list page.
|
||||
*/
|
||||
function EstimatesList({
|
||||
// #withEstimate
|
||||
estimatesTableState,
|
||||
estimatesTableStateChanged,
|
||||
|
||||
// #withEstimatesActions
|
||||
resetEstimatesTableState,
|
||||
}) {
|
||||
// Resets the estimates table state once the page unmount.
|
||||
React.useEffect(
|
||||
() => () => {
|
||||
resetEstimatesTableState();
|
||||
},
|
||||
[resetEstimatesTableState],
|
||||
);
|
||||
|
||||
return (
|
||||
<EstimatesListProvider
|
||||
query={transformTableStateToQuery(estimatesTableState)}
|
||||
tableStateChanged={estimatesTableStateChanged}
|
||||
>
|
||||
<EstimatesActionsBar />
|
||||
|
||||
<DashboardPageContent>
|
||||
<EstimatesViewTabs />
|
||||
<EstimatesDataTable />
|
||||
</DashboardPageContent>
|
||||
|
||||
<EstimatesAlerts />
|
||||
</EstimatesListProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withEstimates(({ estimatesTableState, estimatesTableStateChanged }) => ({
|
||||
estimatesTableState,
|
||||
estimatesTableStateChanged,
|
||||
})),
|
||||
withEstimatesActions,
|
||||
)(EstimatesList);
|
||||
@@ -0,0 +1,68 @@
|
||||
import React, { createContext } from 'react';
|
||||
import { isEmpty } from 'lodash';
|
||||
|
||||
import DashboardInsider from 'components/Dashboard/DashboardInsider';
|
||||
|
||||
import { useResourceViews, useResourceMeta, useEstimates } from 'hooks/query';
|
||||
import { getFieldsFromResourceMeta } from 'utils';
|
||||
|
||||
// Estimates list context.
|
||||
const EstimatesListContext = createContext();
|
||||
|
||||
/**
|
||||
* Sale estimates data provider.
|
||||
*/
|
||||
function EstimatesListProvider({ query, tableStateChanged, ...props }) {
|
||||
// Fetches estimates resource views and fields.
|
||||
const { data: estimatesViews, isLoading: isViewsLoading } =
|
||||
useResourceViews('sale_estimates');
|
||||
|
||||
// Fetches the estimates resource fields.
|
||||
const {
|
||||
data: resourceMeta,
|
||||
isLoading: isResourceLoading,
|
||||
isFetching: isResourceFetching,
|
||||
} = useResourceMeta('sale_estimates');
|
||||
|
||||
// Fetches estimates list according to the given custom view id.
|
||||
const {
|
||||
data: { estimates, pagination, filterMeta },
|
||||
isLoading: isEstimatesLoading,
|
||||
isFetching: isEstimatesFetching,
|
||||
} = useEstimates(query, { keepPreviousData: true });
|
||||
|
||||
// Detarmines the datatable empty status.
|
||||
const isEmptyStatus =
|
||||
!isEstimatesLoading && !tableStateChanged && isEmpty(estimates);
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
estimates,
|
||||
pagination,
|
||||
|
||||
fields: getFieldsFromResourceMeta(resourceMeta.fields),
|
||||
estimatesViews,
|
||||
|
||||
isResourceLoading,
|
||||
isResourceFetching,
|
||||
|
||||
isEstimatesLoading,
|
||||
isEstimatesFetching,
|
||||
isViewsLoading,
|
||||
|
||||
isEmptyStatus,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={isViewsLoading || isResourceLoading}
|
||||
name={'sale_estimate'}
|
||||
>
|
||||
<EstimatesListContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const useEstimatesListContext = () => React.useContext(EstimatesListContext);
|
||||
|
||||
export { EstimatesListProvider, useEstimatesListContext };
|
||||
@@ -0,0 +1,52 @@
|
||||
import React from 'react';
|
||||
import { Alignment, Navbar, NavbarGroup } from '@blueprintjs/core';
|
||||
|
||||
import { DashboardViewsTabs } from 'components';
|
||||
|
||||
import withEstimatesActions from './withEstimatesActions';
|
||||
import withEstimates from './withEstimates';
|
||||
|
||||
import { useEstimatesListContext } from './EstimatesListProvider';
|
||||
import { compose, transfromViewsToTabs } from 'utils';
|
||||
|
||||
/**
|
||||
* Estimates views tabs.
|
||||
*/
|
||||
function EstimateViewTabs({
|
||||
// #withEstimatesActions
|
||||
setEstimatesTableState,
|
||||
|
||||
// #withEstimates
|
||||
estimatesCurrentView,
|
||||
}) {
|
||||
// Estimates list context.
|
||||
const { estimatesViews } = useEstimatesListContext();
|
||||
|
||||
// Estimates views.
|
||||
const tabs = transfromViewsToTabs(estimatesViews);
|
||||
|
||||
// Handle tab change.
|
||||
const handleTabsChange = (viewSlug) => {
|
||||
setEstimatesTableState({ viewSlug: viewSlug || null });
|
||||
};
|
||||
|
||||
return (
|
||||
<Navbar className={'navbar--dashboard-views'}>
|
||||
<NavbarGroup align={Alignment.LEFT}>
|
||||
<DashboardViewsTabs
|
||||
currentViewSlug={estimatesCurrentView}
|
||||
resourceName={'estimates'}
|
||||
tabs={tabs}
|
||||
onChange={handleTabsChange}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
</Navbar>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withEstimatesActions,
|
||||
withEstimates(({ estimatesTableState }) => ({
|
||||
estimatesCurrentView: estimatesTableState.viewSlug
|
||||
})),
|
||||
)(EstimateViewTabs);
|
||||
207
src/containers/Sales/Estimates/EstimatesLanding/components.js
Normal file
207
src/containers/Sales/Estimates/EstimatesLanding/components.js
Normal file
@@ -0,0 +1,207 @@
|
||||
import React from 'react';
|
||||
import { Intent, Tag, Menu, MenuItem, MenuDivider } from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
import clsx from 'classnames';
|
||||
|
||||
import { CLASSES } from '../../../../common/classes';
|
||||
import {
|
||||
FormatDateCell,
|
||||
FormattedMessage as T,
|
||||
Money,
|
||||
Choose,
|
||||
Icon,
|
||||
If,
|
||||
} from 'components';
|
||||
import { safeCallback } from 'utils';
|
||||
|
||||
/**
|
||||
* Status accessor.
|
||||
*/
|
||||
export const statusAccessor = (row) => (
|
||||
<Choose>
|
||||
<Choose.When condition={row.is_delivered && row.is_approved}>
|
||||
<Tag minimal={true} intent={Intent.SUCCESS}>
|
||||
<T id={'approved'} />
|
||||
</Tag>
|
||||
</Choose.When>
|
||||
<Choose.When condition={row.is_delivered && row.is_rejected}>
|
||||
<Tag minimal={true} intent={Intent.DANGER}>
|
||||
<T id={'rejected'} />
|
||||
</Tag>
|
||||
</Choose.When>
|
||||
<Choose.When
|
||||
condition={row.is_delivered && !row.is_rejected && !row.is_approved}
|
||||
>
|
||||
<Tag minimal={true} intent={Intent.SUCCESS}>
|
||||
<T id={'delivered'} />
|
||||
</Tag>
|
||||
</Choose.When>
|
||||
<Choose.Otherwise>
|
||||
<Tag minimal={true}>
|
||||
<T id={'draft'} />
|
||||
</Tag>
|
||||
</Choose.Otherwise>
|
||||
</Choose>
|
||||
);
|
||||
|
||||
/**
|
||||
* Actions menu.
|
||||
*/
|
||||
export function ActionsMenu({
|
||||
row: { original },
|
||||
payload: {
|
||||
onEdit,
|
||||
onDeliver,
|
||||
onReject,
|
||||
onApprove,
|
||||
onDelete,
|
||||
onDrawer,
|
||||
onConvert,
|
||||
onViewDetails,
|
||||
onPrint,
|
||||
},
|
||||
}) {
|
||||
return (
|
||||
<Menu>
|
||||
<MenuItem
|
||||
icon={<Icon icon="reader-18" />}
|
||||
text={intl.get('view_details')}
|
||||
onClick={safeCallback(onViewDetails, original)}
|
||||
/>
|
||||
<MenuDivider />
|
||||
<MenuItem
|
||||
icon={<Icon icon="pen-18" />}
|
||||
text={intl.get('edit_estimate')}
|
||||
onClick={safeCallback(onEdit, original)}
|
||||
/>
|
||||
<MenuItem
|
||||
icon={<Icon icon="convert_to" />}
|
||||
text={intl.get('convert_to_invoice')}
|
||||
onClick={safeCallback(onConvert, original)}
|
||||
/>
|
||||
<If condition={!original.is_delivered}>
|
||||
<MenuItem
|
||||
icon={<Icon icon={'check'} iconSize={18} />}
|
||||
text={intl.get('mark_as_delivered')}
|
||||
onClick={safeCallback(onDeliver, original)}
|
||||
/>
|
||||
</If>
|
||||
<Choose>
|
||||
<Choose.When condition={original.is_delivered && original.is_approved}>
|
||||
<MenuItem
|
||||
icon={<Icon icon={'close-black'} />}
|
||||
text={intl.get('mark_as_rejected')}
|
||||
onClick={safeCallback(onReject, original)}
|
||||
/>
|
||||
</Choose.When>
|
||||
<Choose.When condition={original.is_delivered && original.is_rejected}>
|
||||
<MenuItem
|
||||
icon={<Icon icon={'check'} iconSize={18} />}
|
||||
text={intl.get('mark_as_approved')}
|
||||
onClick={safeCallback(onApprove, original)}
|
||||
/>
|
||||
</Choose.When>
|
||||
<Choose.When condition={original.is_delivered}>
|
||||
<MenuItem
|
||||
icon={<Icon icon={'check'} iconSize={18} />}
|
||||
text={intl.get('mark_as_approved')}
|
||||
onClick={safeCallback(onApprove, original)}
|
||||
/>
|
||||
<MenuItem
|
||||
icon={<Icon icon={'close-black'} />}
|
||||
text={intl.get('mark_as_rejected')}
|
||||
onClick={safeCallback(onReject, original)}
|
||||
/>
|
||||
</Choose.When>
|
||||
</Choose>
|
||||
<MenuItem
|
||||
icon={<Icon icon={'print-16'} iconSize={16} />}
|
||||
text={intl.get('print')}
|
||||
onClick={safeCallback(onPrint, original)}
|
||||
/>
|
||||
<MenuItem
|
||||
text={intl.get('delete_estimate')}
|
||||
intent={Intent.DANGER}
|
||||
onClick={safeCallback(onDelete, original)}
|
||||
icon={<Icon icon="trash-16" iconSize={16} />}
|
||||
/>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
function AmountAccessor({ amount, currency_code }) {
|
||||
return <Money amount={amount} currency={currency_code} />;
|
||||
}
|
||||
|
||||
export function useEstiamtesTableColumns() {
|
||||
return React.useMemo(
|
||||
() => [
|
||||
{
|
||||
id: 'estimate_date',
|
||||
Header: intl.get('estimate_date'),
|
||||
accessor: 'estimate_date',
|
||||
Cell: FormatDateCell,
|
||||
width: 140,
|
||||
className: 'estimate_date',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'customer',
|
||||
Header: intl.get('customer_name'),
|
||||
accessor: 'customer.display_name',
|
||||
width: 140,
|
||||
className: 'customer_id',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'expiration_date',
|
||||
Header: intl.get('expiration_date'),
|
||||
accessor: 'expiration_date',
|
||||
Cell: FormatDateCell,
|
||||
width: 140,
|
||||
className: 'expiration_date',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'estimate_number',
|
||||
Header: intl.get('estimate_number'),
|
||||
accessor: (row) =>
|
||||
row.estimate_number ? `${row.estimate_number}` : null,
|
||||
width: 140,
|
||||
className: 'estimate_number',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'amount',
|
||||
Header: intl.get('amount'),
|
||||
accessor: AmountAccessor,
|
||||
width: 140,
|
||||
align: 'right',
|
||||
clickable: true,
|
||||
className: clsx(CLASSES.FONT_BOLD),
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
Header: intl.get('status'),
|
||||
accessor: (row) => statusAccessor(row),
|
||||
width: 140,
|
||||
className: 'status',
|
||||
clickable: true,
|
||||
},
|
||||
{
|
||||
id: 'reference_no',
|
||||
Header: intl.get('reference_no'),
|
||||
accessor: 'reference',
|
||||
width: 90,
|
||||
className: 'reference',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { connect } from 'react-redux';
|
||||
import {
|
||||
getEstimatesTableStateFactory,
|
||||
isEstimatesTableStateChangedFactory,
|
||||
} from 'store/Estimate/estimates.selectors';
|
||||
|
||||
export default (mapState) => {
|
||||
const getEstimatesTableState = getEstimatesTableStateFactory();
|
||||
const isEstimatesTableStateChanged = isEstimatesTableStateChangedFactory();
|
||||
|
||||
const mapStateToProps = (state, props) => {
|
||||
const mapped = {
|
||||
estimatesTableState: getEstimatesTableState(state, props),
|
||||
estimatesTableStateChanged: isEstimatesTableStateChanged(state, props),
|
||||
};
|
||||
return mapState ? mapState(mapped, state, props) : mapped;
|
||||
};
|
||||
return connect(mapStateToProps);
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { connect } from 'react-redux';
|
||||
import {
|
||||
setEstimatesTableState,
|
||||
resetEstimatesTableState,
|
||||
} from 'store/Estimate/estimates.actions';
|
||||
|
||||
const mapDispatchToProps = (dispatch) => ({
|
||||
setEstimatesTableState: (state) => dispatch(setEstimatesTableState(state)),
|
||||
resetEstimatesTableState: () => dispatch(resetEstimatesTableState()),
|
||||
});
|
||||
|
||||
export default connect(null, mapDispatchToProps);
|
||||
11
src/containers/Sales/Estimates/withEstimateDetail.js
Normal file
11
src/containers/Sales/Estimates/withEstimateDetail.js
Normal file
@@ -0,0 +1,11 @@
|
||||
import { connect } from 'react-redux';
|
||||
import { getEstimateByIdFactory } from 'store/Estimate/estimates.selectors';
|
||||
|
||||
export default () => {
|
||||
const getEstimateById = getEstimateByIdFactory();
|
||||
|
||||
const mapStateToProps = (state, props) => ({
|
||||
estimate: getEstimateById(state, props),
|
||||
});
|
||||
return connect(mapStateToProps);
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
import React, { lazy } from 'react';
|
||||
import withDrawers from 'containers/Drawer/withDrawers';
|
||||
|
||||
import { Drawer, DrawerSuspense } from 'components';
|
||||
import { compose } from 'utils';
|
||||
|
||||
const InvoicesDrawerContent = lazy(() => import('./InvoiceDrawerContent'));
|
||||
|
||||
/**
|
||||
* invoice drawer.
|
||||
*/
|
||||
function InvoiceDrawer({
|
||||
name,
|
||||
//#withDrawer
|
||||
isOpen,
|
||||
payload: { invoiceId },
|
||||
|
||||
}) {
|
||||
|
||||
return (
|
||||
<Drawer isOpen={isOpen} name={name}>
|
||||
<DrawerSuspense>
|
||||
<InvoicesDrawerContent invoiceId={invoiceId} />
|
||||
</DrawerSuspense>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withDrawers())(InvoiceDrawer);
|
||||
@@ -0,0 +1,18 @@
|
||||
import React from 'react';
|
||||
import { InvoiceDrawerProvider } from './InvoiceDrawerProvider';
|
||||
import InvoicePaper from './InvoicePaper';
|
||||
|
||||
/**
|
||||
* Invoice drawer content.
|
||||
*/
|
||||
export default function InvoiceDrawerContent({
|
||||
// #ownProp
|
||||
invoiceId,
|
||||
}) {
|
||||
|
||||
return (
|
||||
<InvoiceDrawerProvider invoiceId={invoiceId}>
|
||||
<InvoicePaper />
|
||||
</InvoiceDrawerProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import { useInvoice } from 'hooks/query';
|
||||
import { DrawerHeaderContent, DashboardInsider } from 'components';
|
||||
|
||||
const InvoiceDrawerContext = createContext();
|
||||
|
||||
/**
|
||||
* Invoice drawer provider.
|
||||
*/
|
||||
function InvoiceDrawerProvider({ invoiceId, ...props }) {
|
||||
// Fetch sale invoice details.
|
||||
const {
|
||||
data: { entries, ...invoice },
|
||||
isLoading: isInvoiceLoading,
|
||||
} = useInvoice(invoiceId, {
|
||||
enabled: !!invoiceId,
|
||||
});
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
invoiceId,
|
||||
invoice,
|
||||
entries,
|
||||
|
||||
isInvoiceLoading,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider loading={isInvoiceLoading}>
|
||||
<DrawerHeaderContent name={'invoice-drawer'} />
|
||||
<InvoiceDrawerContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
const useInvoiceDrawerContext = () => useContext(InvoiceDrawerContext);
|
||||
|
||||
export { InvoiceDrawerProvider, useInvoiceDrawerContext };
|
||||
38
src/containers/Sales/Invoices/InvoiceDetails/InvoicePaper.js
Normal file
38
src/containers/Sales/Invoices/InvoiceDetails/InvoicePaper.js
Normal file
@@ -0,0 +1,38 @@
|
||||
import React from 'react';
|
||||
import { useInvoiceDrawerContext } from './InvoiceDrawerProvider';
|
||||
import PaperTemplate from 'containers/Drawers/PaperTemplate/PaperTemplate';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
export default function InvoicePaper() {
|
||||
const { invoice, entries } = useInvoiceDrawerContext();
|
||||
|
||||
const propLabels = {
|
||||
labels: {
|
||||
name: intl.get('invoice'),
|
||||
billedTo: intl.get('billed_to'),
|
||||
date: intl.get('invoice_date_'),
|
||||
refNo: intl.get('invoice_no__'),
|
||||
billedFrom: intl.get('billed_from'),
|
||||
amount: intl.get('invoice_amount'),
|
||||
dueDate: intl.get('due_date_'),
|
||||
},
|
||||
};
|
||||
|
||||
const defaultValues = {
|
||||
billedTo: invoice.customer.display_name,
|
||||
date: invoice.invoice_date,
|
||||
amount: invoice.balance,
|
||||
billedFrom: '',
|
||||
dueDate: invoice.due_date,
|
||||
referenceNo: invoice.invoice_no,
|
||||
...invoice,
|
||||
};
|
||||
|
||||
return (
|
||||
<PaperTemplate
|
||||
labels={propLabels.labels}
|
||||
paperData={defaultValues}
|
||||
entries={entries}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Intent,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
Popover,
|
||||
PopoverInteractionKind,
|
||||
Position,
|
||||
Menu,
|
||||
MenuItem,
|
||||
} from '@blueprintjs/core';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import classNames from 'classnames';
|
||||
|
||||
import { useInvoiceFormContext } from './InvoiceFormProvider';
|
||||
import { If, Icon } from 'components';
|
||||
|
||||
/**
|
||||
* Invoice floating actions bar.
|
||||
*/
|
||||
export default function InvoiceFloatingActions() {
|
||||
const history = useHistory();
|
||||
|
||||
// Formik context.
|
||||
const { resetForm, submitForm, isSubmitting } = useFormikContext();
|
||||
|
||||
// Invoice form context.
|
||||
const { setSubmitPayload, invoice } = useInvoiceFormContext();
|
||||
|
||||
// Handle submit & deliver button click.
|
||||
const handleSubmitDeliverBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, deliver: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, deliver & new button click.
|
||||
const handleSubmitDeliverAndNewBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, deliver: true, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, deliver & continue editing button click.
|
||||
const handleSubmitDeliverContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, deliver: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit as draft button click.
|
||||
const handleSubmitDraftBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, deliver: false });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit as draft & new button click.
|
||||
const handleSubmitDraftAndNewBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, deliver: false, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit as draft & continue editing button click.
|
||||
const handleSubmitDraftContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, deliver: false });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle cancel button click.
|
||||
const handleCancelBtnClick = (event) => {
|
||||
history.goBack();
|
||||
};
|
||||
|
||||
const handleClearBtnClick = (event) => {
|
||||
resetForm();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
|
||||
{/* ----------- Save And Deliver ----------- */}
|
||||
<If condition={!invoice || !invoice?.is_delivered}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
onClick={handleSubmitDeliverBtnClick}
|
||||
text={<T id={'save_and_deliver'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'deliver_and_new'} />}
|
||||
onClick={handleSubmitDeliverAndNewBtnClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'deliver_continue_editing'} />}
|
||||
onClick={handleSubmitDeliverContinueEditingBtnClick}
|
||||
/>
|
||||
</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>
|
||||
{/* ----------- Save As Draft ----------- */}
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
className={'ml1'}
|
||||
onClick={handleSubmitDraftBtnClick}
|
||||
text={<T id={'save_as_draft'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitDraftAndNewBtnClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'save_continue_editing'} />}
|
||||
onClick={handleSubmitDraftContinueEditingBtnClick}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
minimal={true}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
|
||||
/>
|
||||
</Popover>
|
||||
</ButtonGroup>
|
||||
</If>
|
||||
{/* ----------- Save and New ----------- */}
|
||||
<If condition={invoice && invoice?.is_delivered}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
onClick={handleSubmitDeliverBtnClick}
|
||||
text={<T id={'save'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitDeliverAndNewBtnClick}
|
||||
/>
|
||||
</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>
|
||||
</If>
|
||||
|
||||
{/* ----------- Clear & Reset----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
disabled={isSubmitting}
|
||||
onClick={handleClearBtnClick}
|
||||
text={invoice ? <T id={'reset'} /> : <T id={'clear'} />}
|
||||
/>
|
||||
{/* ----------- Cancel ----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
onClick={handleCancelBtnClick}
|
||||
text={<T id={'cancel'} />}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
183
src/containers/Sales/Invoices/InvoiceForm/InvoiceForm.js
Normal file
183
src/containers/Sales/Invoices/InvoiceForm/InvoiceForm.js
Normal file
@@ -0,0 +1,183 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Formik, Form } from 'formik';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
import { sumBy, omit, isEmpty } from 'lodash';
|
||||
import classNames from 'classnames';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import {
|
||||
getCreateInvoiceFormSchema,
|
||||
getEditInvoiceFormSchema,
|
||||
} from './InvoiceForm.schema';
|
||||
|
||||
import InvoiceFormHeader from './InvoiceFormHeader';
|
||||
import InvoiceItemsEntriesEditorField from './InvoiceItemsEntriesEditorField';
|
||||
import InvoiceFloatingActions from './InvoiceFloatingActions';
|
||||
import InvoiceFormFooter from './InvoiceFormFooter';
|
||||
import InvoiceFormDialogs from './InvoiceFormDialogs';
|
||||
|
||||
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
|
||||
import withMediaActions from 'containers/Media/withMediaActions';
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import { AppToaster } from 'components';
|
||||
import { compose, orderingLinesIndexes, transactionNumber } from 'utils';
|
||||
import { useInvoiceFormContext } from './InvoiceFormProvider';
|
||||
import { transformToEditForm, defaultInvoice, transformErrors } from './utils';
|
||||
|
||||
/**
|
||||
* Invoice form.
|
||||
*/
|
||||
function InvoiceForm({
|
||||
// #withSettings
|
||||
invoiceNextNumber,
|
||||
invoiceNumberPrefix,
|
||||
invoiceIncrementMode,
|
||||
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Invoice form context.
|
||||
const {
|
||||
isNewMode,
|
||||
invoice,
|
||||
estimateId,
|
||||
newInvoice,
|
||||
createInvoiceMutate,
|
||||
editInvoiceMutate,
|
||||
submitPayload,
|
||||
} = useInvoiceFormContext();
|
||||
|
||||
// Invoice number.
|
||||
const invoiceNumber = transactionNumber(
|
||||
invoiceNumberPrefix,
|
||||
invoiceNextNumber,
|
||||
);
|
||||
// Form initial values.
|
||||
const initialValues = useMemo(
|
||||
() => ({
|
||||
...(!isEmpty(invoice)
|
||||
? { ...transformToEditForm(invoice), currency_code: base_currency }
|
||||
: {
|
||||
...defaultInvoice,
|
||||
...(invoiceIncrementMode && {
|
||||
invoice_no: invoiceNumber,
|
||||
}),
|
||||
entries: orderingLinesIndexes(defaultInvoice.entries),
|
||||
...newInvoice,
|
||||
currency_code: base_currency,
|
||||
}),
|
||||
}),
|
||||
[invoice, newInvoice, invoiceNumber, invoiceIncrementMode],
|
||||
);
|
||||
|
||||
// Handles form submit.
|
||||
const handleSubmit = (values, { setSubmitting, setErrors, resetForm }) => {
|
||||
setSubmitting(true);
|
||||
|
||||
const entries = values.entries.filter(
|
||||
(item) => item.item_id && item.quantity,
|
||||
);
|
||||
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
|
||||
|
||||
// Throw danger toaster in case total quantity equals zero.
|
||||
if (totalQuantity === 0) {
|
||||
AppToaster.show({
|
||||
message: intl.get('quantity_cannot_be_zero_or_empty'),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
const form = {
|
||||
...omit(values, ['invoice_no', 'invoice_no_manually']),
|
||||
...(values.invoice_no_manually && {
|
||||
invoice_no: values.invoice_no,
|
||||
}),
|
||||
delivered: submitPayload.deliver,
|
||||
from_estimate_id: estimateId,
|
||||
entries: entries.map((entry) => ({ ...omit(entry, ['total']) })),
|
||||
};
|
||||
// Handle the request success.
|
||||
const onSuccess = () => {
|
||||
AppToaster.show({
|
||||
message: intl.get(
|
||||
isNewMode
|
||||
? 'the_invoice_has_been_created_successfully'
|
||||
: 'the_invoice_has_been_edited_successfully',
|
||||
{ number: values.invoice_no },
|
||||
),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
|
||||
if (submitPayload.redirect) {
|
||||
history.push('/invoices');
|
||||
}
|
||||
if (submitPayload.resetForm) {
|
||||
resetForm();
|
||||
}
|
||||
};
|
||||
|
||||
// Handle the request error.
|
||||
const onError = ({
|
||||
response: {
|
||||
data: { errors },
|
||||
},
|
||||
}) => {
|
||||
if (errors) {
|
||||
transformErrors(errors, { setErrors });
|
||||
}
|
||||
setSubmitting(false);
|
||||
};
|
||||
if (!isEmpty(invoice)) {
|
||||
editInvoiceMutate([invoice.id, form]).then(onSuccess).catch(onError);
|
||||
} else {
|
||||
createInvoiceMutate(form).then(onSuccess).catch(onError);
|
||||
}
|
||||
};
|
||||
|
||||
const CreateInvoiceFormSchema = getCreateInvoiceFormSchema();
|
||||
const EditInvoiceFormSchema = getEditInvoiceFormSchema();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
CLASSES.PAGE_FORM,
|
||||
CLASSES.PAGE_FORM_STRIP_STYLE,
|
||||
CLASSES.PAGE_FORM_INVOICE,
|
||||
)}
|
||||
>
|
||||
<Formik
|
||||
validationSchema={
|
||||
isNewMode ? CreateInvoiceFormSchema : EditInvoiceFormSchema
|
||||
}
|
||||
initialValues={initialValues}
|
||||
onSubmit={handleSubmit}
|
||||
>
|
||||
<Form>
|
||||
<InvoiceFormHeader />
|
||||
<InvoiceItemsEntriesEditorField />
|
||||
<InvoiceFormFooter />
|
||||
<InvoiceFloatingActions />
|
||||
<InvoiceFormDialogs />
|
||||
</Form>
|
||||
</Formik>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withDashboardActions,
|
||||
withMediaActions,
|
||||
withSettings(({ invoiceSettings }) => ({
|
||||
invoiceNextNumber: invoiceSettings?.nextNumber,
|
||||
invoiceNumberPrefix: invoiceSettings?.numberPrefix,
|
||||
invoiceIncrementMode: invoiceSettings?.autoIncrement,
|
||||
})),
|
||||
withCurrentOrganization(),
|
||||
)(InvoiceForm);
|
||||
@@ -0,0 +1,55 @@
|
||||
import * as Yup from 'yup';
|
||||
import intl from 'react-intl-universal';
|
||||
import { DATATYPES_LENGTH } from 'common/dataTypes';
|
||||
import { isBlank } from 'utils';
|
||||
|
||||
const getSchema = () => Yup.object().shape({
|
||||
customer_id: Yup.string()
|
||||
.label(intl.get('customer_name_'))
|
||||
.required(),
|
||||
invoice_date: Yup.date()
|
||||
.required()
|
||||
.label(intl.get('invoice_date_')),
|
||||
due_date: Yup.date()
|
||||
.required()
|
||||
.label(intl.get('due_date_')),
|
||||
invoice_no: Yup.string()
|
||||
.max(DATATYPES_LENGTH.STRING)
|
||||
.label(intl.get('invoice_no_')),
|
||||
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING),
|
||||
delivered: Yup.boolean(),
|
||||
from_estimate_id: Yup.string(),
|
||||
invoice_message: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(DATATYPES_LENGTH.TEXT)
|
||||
.label(intl.get('note')),
|
||||
terms_conditions: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(DATATYPES_LENGTH.TEXT)
|
||||
.label(intl.get('note')),
|
||||
entries: Yup.array().of(
|
||||
Yup.object().shape({
|
||||
quantity: Yup.number()
|
||||
.nullable()
|
||||
.max(DATATYPES_LENGTH.INT_10)
|
||||
.when(['rate'], {
|
||||
is: (rate) => rate,
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
rate: Yup.number().nullable().max(DATATYPES_LENGTH.INT_10),
|
||||
item_id: Yup.number()
|
||||
.nullable()
|
||||
.when(['quantity', 'rate'], {
|
||||
is: (quantity, rate) => !isBlank(quantity) && !isBlank(rate),
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
discount: Yup.number().nullable().min(0).max(100),
|
||||
description: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export const getCreateInvoiceFormSchema = getSchema;
|
||||
export const getEditInvoiceFormSchema = getSchema;
|
||||
@@ -0,0 +1,25 @@
|
||||
import React from 'react';
|
||||
import InvoiceNumberDialog from 'containers/Dialogs/InvoiceNumberDialog';
|
||||
import { useFormikContext } from 'formik';
|
||||
|
||||
/**
|
||||
* Invoice form dialogs.
|
||||
*/
|
||||
export default function InvoiceFormDialogs() {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
|
||||
// Update the form once the invoice number form submit confirm.
|
||||
const handleInvoiceNumberFormConfirm = ({ incrementNumber, manually }) => {
|
||||
setFieldValue('invoice_no', incrementNumber || '');
|
||||
setFieldValue('invoice_no_manually', manually);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<InvoiceNumberDialog
|
||||
dialogName={'invoice-number-form'}
|
||||
onConfirm={handleInvoiceNumberFormConfirm}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import React from 'react';
|
||||
import { FastField } from 'formik';
|
||||
import classNames from 'classnames';
|
||||
import { FormGroup, TextArea } from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { Row, Col, Postbox } from 'components';
|
||||
import Dragzone from 'components/Dragzone';
|
||||
|
||||
import { inputIntent } from 'utils';
|
||||
|
||||
export default function InvoiceFormFooter() {
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
|
||||
<Postbox title={<T id={'invoice_details'} />} defaultOpen={false}>
|
||||
<Row>
|
||||
<Col md={8}>
|
||||
{/* --------- Invoice message --------- */}
|
||||
<FastField name={'invoice_message'}>
|
||||
{({ field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'invoice_message'} />}
|
||||
className={'form-group--invoice_message'}
|
||||
intent={inputIntent({ error, touched })}
|
||||
>
|
||||
<TextArea growVertically={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* --------- Terms and conditions --------- */}
|
||||
<FastField name={'terms_conditions'}>
|
||||
{({ field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'terms_conditions'} />}
|
||||
className={'form-group--terms_conditions'}
|
||||
intent={inputIntent({ error, touched })}
|
||||
>
|
||||
<TextArea growVertically={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</Col>
|
||||
|
||||
<Col md={4}>
|
||||
<Dragzone
|
||||
initialFiles={[]}
|
||||
// onDrop={handleDropFiles}
|
||||
// onDeleteFile={handleDeleteFile}
|
||||
hint={<T id={'attachments_maximum'} />}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</Postbox>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { useFormikContext } from 'formik';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import InvoiceFormHeaderFields from './InvoiceFormHeaderFields';
|
||||
|
||||
import { getEntriesTotal } from 'containers/Entries/utils';
|
||||
import { PageFormBigNumber } from 'components';
|
||||
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import { compose } from 'redux';
|
||||
|
||||
/**
|
||||
* Invoice form header section.
|
||||
*/
|
||||
function InvoiceFormHeader({
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
const { values } = useFormikContext();
|
||||
|
||||
// Calculate the total due amount of invoice entries.
|
||||
const totalDueAmount = useMemo(
|
||||
() => getEntriesTotal(values.entries),
|
||||
[values.entries],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
|
||||
<InvoiceFormHeaderFields />
|
||||
<PageFormBigNumber
|
||||
label={intl.get('due_amount')}
|
||||
amount={totalDueAmount}
|
||||
currencyCode={base_currency}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export default compose(withCurrentOrganization())(InvoiceFormHeader);
|
||||
@@ -0,0 +1,212 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
FormGroup,
|
||||
InputGroup,
|
||||
Position,
|
||||
ControlGroup,
|
||||
} from '@blueprintjs/core';
|
||||
import { DateInput } from '@blueprintjs/datetime';
|
||||
import { FastField, Field, ErrorMessage } from 'formik';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { momentFormatter, compose, tansformDateValue } from 'utils';
|
||||
import classNames from 'classnames';
|
||||
import {
|
||||
useObserveInvoiceNoSettings,
|
||||
customerNameFieldShouldUpdate,
|
||||
} from './utils';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import {
|
||||
ContactSelecetList,
|
||||
FieldRequiredHint,
|
||||
Icon,
|
||||
InputPrependButton,
|
||||
} from 'components';
|
||||
import { useInvoiceFormContext } from './InvoiceFormProvider';
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import withDialogActions from 'containers/Dialog/withDialogActions';
|
||||
import { inputIntent, handleDateChange } from 'utils';
|
||||
|
||||
/**
|
||||
* Invoice form header fields.
|
||||
*/
|
||||
function InvoiceFormHeaderFields({
|
||||
// #withDialogActions
|
||||
openDialog,
|
||||
|
||||
// #withSettings
|
||||
invoiceAutoIncrement,
|
||||
invoiceNumberPrefix,
|
||||
invoiceNextNumber,
|
||||
}) {
|
||||
// Invoice form context.
|
||||
const { customers } = useInvoiceFormContext();
|
||||
|
||||
// Handle invoice number changing.
|
||||
const handleInvoiceNumberChange = () => {
|
||||
openDialog('invoice-number-form');
|
||||
};
|
||||
|
||||
// Handle invoice no. field blur.
|
||||
const handleInvoiceNoBlur = (form, field) => (event) => {
|
||||
const newValue = event.target.value;
|
||||
|
||||
if (field.value !== newValue && invoiceAutoIncrement) {
|
||||
openDialog('invoice-number-form', {
|
||||
initialFormValues: {
|
||||
manualTransactionNo: newValue,
|
||||
incrementMode: 'manual-transaction',
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Syncs invoice number settings with form.
|
||||
useObserveInvoiceNoSettings(invoiceNumberPrefix, invoiceNextNumber);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
|
||||
{/* ----------- Customer name ----------- */}
|
||||
<FastField
|
||||
name={'customer_id'}
|
||||
customers={customers}
|
||||
shouldUpdate={customerNameFieldShouldUpdate}
|
||||
>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'customer_name'} />}
|
||||
inline={true}
|
||||
className={classNames(
|
||||
'form-group--customer-name',
|
||||
'form-group--select-list',
|
||||
CLASSES.FILL,
|
||||
)}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name={'customer_id'} />}
|
||||
>
|
||||
<ContactSelecetList
|
||||
contactsList={customers}
|
||||
selectedContactId={value}
|
||||
defaultSelectText={<T id={'select_customer_account'} />}
|
||||
onContactSelected={(customer) => {
|
||||
form.setFieldValue('customer_id', customer.id);
|
||||
}}
|
||||
popoverFill={true}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Invoice date ----------- */}
|
||||
<FastField name={'invoice_date'}>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'invoice_date'} />}
|
||||
inline={true}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
className={classNames('form-group--invoice-date', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="invoice_date" />}
|
||||
>
|
||||
<DateInput
|
||||
{...momentFormatter('YYYY/MM/DD')}
|
||||
value={tansformDateValue(value)}
|
||||
onChange={handleDateChange((formattedDate) => {
|
||||
form.setFieldValue('invoice_date', formattedDate);
|
||||
})}
|
||||
popoverProps={{ position: Position.BOTTOM_LEFT, minimal: true }}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Due date ----------- */}
|
||||
<FastField name={'due_date'}>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'due_date'} />}
|
||||
inline={true}
|
||||
className={classNames('form-group--due-date', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="due_date" />}
|
||||
>
|
||||
<DateInput
|
||||
{...momentFormatter('YYYY/MM/DD')}
|
||||
value={tansformDateValue(value)}
|
||||
onChange={handleDateChange((formattedDate) => {
|
||||
form.setFieldValue('due_date', formattedDate);
|
||||
})}
|
||||
popoverProps={{ position: Position.BOTTOM_LEFT, minimal: true }}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Invoice number ----------- */}
|
||||
<Field name={'invoice_no'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'invoice_no'} />}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
inline={true}
|
||||
className={classNames('form-group--invoice-no', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="invoice_no" />}
|
||||
>
|
||||
<ControlGroup fill={true}>
|
||||
<InputGroup
|
||||
minimal={true}
|
||||
value={field.value}
|
||||
asyncControl={true}
|
||||
onBlur={handleInvoiceNoBlur(form, field)}
|
||||
/>
|
||||
<InputPrependButton
|
||||
buttonProps={{
|
||||
onClick: handleInvoiceNumberChange,
|
||||
icon: <Icon icon={'settings-18'} />,
|
||||
}}
|
||||
tooltip={true}
|
||||
tooltipProps={{
|
||||
content: (
|
||||
<T id={'setting_your_auto_generated_invoice_number'} />
|
||||
),
|
||||
position: Position.BOTTOM_LEFT,
|
||||
}}
|
||||
/>
|
||||
</ControlGroup>
|
||||
</FormGroup>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
{/* ----------- Reference ----------- */}
|
||||
<FastField name={'reference_no'}>
|
||||
{({ 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_no" />}
|
||||
>
|
||||
<InputGroup minimal={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withDialogActions,
|
||||
withSettings(({ invoiceSettings }) => ({
|
||||
invoiceAutoIncrement: invoiceSettings?.autoIncrement,
|
||||
invoiceNextNumber: invoiceSettings?.nextNumber,
|
||||
invoiceNumberPrefix: invoiceSettings?.numberPrefix,
|
||||
})),
|
||||
)(InvoiceFormHeaderFields);
|
||||
21
src/containers/Sales/Invoices/InvoiceForm/InvoiceFormPage.js
Normal file
21
src/containers/Sales/Invoices/InvoiceForm/InvoiceFormPage.js
Normal file
@@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
import 'style/pages/SaleInvoice/PageForm.scss';
|
||||
|
||||
import InvoiceForm from './InvoiceForm';
|
||||
import { InvoiceFormProvider } from './InvoiceFormProvider';
|
||||
|
||||
/**
|
||||
* Invoice form page.
|
||||
*/
|
||||
export default function InvoiceFormPage() {
|
||||
const { id } = useParams();
|
||||
const idAsInteger = parseInt(id, 10);
|
||||
|
||||
return (
|
||||
<InvoiceFormProvider invoiceId={idAsInteger}>
|
||||
<InvoiceForm />
|
||||
</InvoiceFormProvider>
|
||||
);
|
||||
}
|
||||
107
src/containers/Sales/Invoices/InvoiceForm/InvoiceFormProvider.js
Normal file
107
src/containers/Sales/Invoices/InvoiceForm/InvoiceFormProvider.js
Normal file
@@ -0,0 +1,107 @@
|
||||
import React, { createContext, useState } from 'react';
|
||||
import { isEmpty, pick } from 'lodash';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import DashboardInsider from 'components/Dashboard/DashboardInsider';
|
||||
import { transformToEditForm, ITEMS_FILTER_ROLES_QUERY } from './utils';
|
||||
import {
|
||||
useInvoice,
|
||||
useItems,
|
||||
useCustomers,
|
||||
useCreateInvoice,
|
||||
useEditInvoice,
|
||||
useSettingsInvoices,
|
||||
useEstimate,
|
||||
} from 'hooks/query';
|
||||
|
||||
const InvoiceFormContext = createContext();
|
||||
|
||||
/**
|
||||
* Accounts chart data provider.
|
||||
*/
|
||||
function InvoiceFormProvider({ invoiceId, ...props }) {
|
||||
const { state } = useLocation();
|
||||
const estimateId = state?.action;
|
||||
|
||||
const { data: invoice, isLoading: isInvoiceLoading } = useInvoice(invoiceId, {
|
||||
enabled: !!invoiceId,
|
||||
});
|
||||
|
||||
// Fetches the estimate by the given id.
|
||||
const { data: estimate, isLoading: isEstimateLoading } = useEstimate(
|
||||
estimateId,
|
||||
{ enabled: !!estimateId },
|
||||
);
|
||||
|
||||
const newInvoice = !isEmpty(estimate)
|
||||
? transformToEditForm({
|
||||
...pick(estimate, ['customer_id', 'customer', 'entries']),
|
||||
})
|
||||
: [];
|
||||
|
||||
// Handle fetching the items table based on the given query.
|
||||
const {
|
||||
data: { items },
|
||||
isLoading: isItemsLoading,
|
||||
} = useItems({
|
||||
page_size: 10000,
|
||||
stringified_filter_roles: ITEMS_FILTER_ROLES_QUERY,
|
||||
});
|
||||
|
||||
// Handle fetch customers data table or list
|
||||
const {
|
||||
data: { customers },
|
||||
isLoading: isCustomersLoading,
|
||||
} = useCustomers({ page_size: 10000 });
|
||||
|
||||
// Handle fetching settings.
|
||||
const { isLoading: isSettingsLoading } = useSettingsInvoices();
|
||||
|
||||
// Create and edit invoice mutations.
|
||||
const { mutateAsync: createInvoiceMutate } = useCreateInvoice();
|
||||
const { mutateAsync: editInvoiceMutate } = useEditInvoice();
|
||||
|
||||
// Form submit payload.
|
||||
const [submitPayload, setSubmitPayload] = useState();
|
||||
|
||||
// Detarmines whether the form in new mode.
|
||||
const isNewMode = !invoiceId;
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
invoice,
|
||||
items,
|
||||
customers,
|
||||
newInvoice,
|
||||
estimateId,
|
||||
submitPayload,
|
||||
|
||||
isInvoiceLoading,
|
||||
isItemsLoading,
|
||||
isCustomersLoading,
|
||||
isSettingsLoading,
|
||||
|
||||
createInvoiceMutate,
|
||||
editInvoiceMutate,
|
||||
setSubmitPayload,
|
||||
isNewMode,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={
|
||||
isInvoiceLoading ||
|
||||
isItemsLoading ||
|
||||
isCustomersLoading ||
|
||||
isEstimateLoading ||
|
||||
isSettingsLoading
|
||||
}
|
||||
name={'invoice-form'}
|
||||
>
|
||||
<InvoiceFormContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const useInvoiceFormContext = () => React.useContext(InvoiceFormContext);
|
||||
|
||||
export { InvoiceFormProvider, useInvoiceFormContext };
|
||||
@@ -0,0 +1,41 @@
|
||||
import React from 'react';
|
||||
import { FastField } from 'formik';
|
||||
import classNames from 'classnames';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import ItemsEntriesTable from 'containers/Entries/ItemsEntriesTable';
|
||||
import { useInvoiceFormContext } from './InvoiceFormProvider';
|
||||
import { entriesFieldShouldUpdate } from './utils';
|
||||
|
||||
/**
|
||||
* Invoice items entries editor field.
|
||||
*/
|
||||
export default function InvoiceItemsEntriesEditorField() {
|
||||
const { items } = useInvoiceFormContext();
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
|
||||
<FastField
|
||||
name={'entries'}
|
||||
items={items}
|
||||
shouldUpdate={entriesFieldShouldUpdate}
|
||||
>
|
||||
{({
|
||||
form: { values, setFieldValue },
|
||||
field: { value },
|
||||
meta: { error, touched },
|
||||
}) => (
|
||||
<ItemsEntriesTable
|
||||
entries={value}
|
||||
onUpdateData={(entries) => {
|
||||
setFieldValue('entries', entries);
|
||||
}}
|
||||
items={items}
|
||||
errors={error}
|
||||
linesNumber={4}
|
||||
currencyCode={values.currency_code}
|
||||
/>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
148
src/containers/Sales/Invoices/InvoiceForm/utils.js
Normal file
148
src/containers/Sales/Invoices/InvoiceForm/utils.js
Normal file
@@ -0,0 +1,148 @@
|
||||
import React from 'react';
|
||||
import moment from 'moment';
|
||||
import {
|
||||
compose,
|
||||
transformToForm,
|
||||
repeatValue,
|
||||
transactionNumber,
|
||||
} from 'utils';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
|
||||
import { defaultFastFieldShouldUpdate } from 'utils';
|
||||
import intl from 'react-intl-universal';
|
||||
import { ERROR } from 'common/errors';
|
||||
import { AppToaster } from 'components';
|
||||
import {
|
||||
updateItemsEntriesTotal,
|
||||
ensureEntriesHaveEmptyLine,
|
||||
} from 'containers/Entries/utils';
|
||||
|
||||
export const MIN_LINES_NUMBER = 4;
|
||||
|
||||
// Default invoice entry object.
|
||||
export const defaultInvoiceEntry = {
|
||||
index: 0,
|
||||
item_id: '',
|
||||
rate: '',
|
||||
discount: '',
|
||||
quantity: '',
|
||||
description: '',
|
||||
amount: '',
|
||||
};
|
||||
|
||||
// Default invoice object.
|
||||
export const defaultInvoice = {
|
||||
customer_id: '',
|
||||
invoice_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
due_date: moment().format('YYYY-MM-DD'),
|
||||
delivered: '',
|
||||
invoice_no: '',
|
||||
invoice_no_manually: false,
|
||||
reference_no: '',
|
||||
invoice_message: '',
|
||||
terms_conditions: '',
|
||||
entries: [...repeatValue(defaultInvoiceEntry, MIN_LINES_NUMBER)],
|
||||
};
|
||||
|
||||
/**
|
||||
* Transform invoice to initial values in edit mode.
|
||||
*/
|
||||
export function transformToEditForm(invoice) {
|
||||
const initialEntries = [
|
||||
...invoice.entries.map((invoice) => ({
|
||||
...transformToForm(invoice, defaultInvoiceEntry),
|
||||
})),
|
||||
...repeatValue(
|
||||
defaultInvoiceEntry,
|
||||
Math.max(MIN_LINES_NUMBER - invoice.entries.length, 0),
|
||||
),
|
||||
];
|
||||
const entries = compose(
|
||||
ensureEntriesHaveEmptyLine(defaultInvoiceEntry),
|
||||
updateItemsEntriesTotal,
|
||||
)(initialEntries);
|
||||
|
||||
return {
|
||||
...transformToForm(invoice, defaultInvoice),
|
||||
entries,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformes the response errors types.
|
||||
*/
|
||||
export const transformErrors = (errors, { setErrors }) => {
|
||||
if (errors.some((e) => e.type === ERROR.SALE_INVOICE_NUMBER_IS_EXISTS)) {
|
||||
setErrors({
|
||||
invoice_no: intl.get('sale_invoice_number_is_exists'),
|
||||
});
|
||||
}
|
||||
if (
|
||||
errors.some(
|
||||
({ type }) =>
|
||||
type === ERROR.SALE_ESTIMATE_IS_ALREADY_CONVERTED_TO_INVOICE,
|
||||
)
|
||||
) {
|
||||
AppToaster.show({
|
||||
message: intl.get('sale_estimate_is_already_converted_to_invoice'),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
}
|
||||
if (
|
||||
errors.some((error) => error.type === ERROR.SALE_INVOICE_NO_IS_REQUIRED)
|
||||
) {
|
||||
setErrors({
|
||||
invoice_no: intl.get('invoice.field.error.invoice_no_required'),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Syncs invoice no. settings with form.
|
||||
*/
|
||||
export const useObserveInvoiceNoSettings = (prefix, nextNumber) => {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
|
||||
React.useEffect(() => {
|
||||
const invoiceNo = transactionNumber(prefix, nextNumber);
|
||||
setFieldValue('invoice_no', invoiceNo);
|
||||
}, [setFieldValue, prefix, nextNumber]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines customer name field when should update.
|
||||
*/
|
||||
export const customerNameFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.customers !== oldProps.customers ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines invoice entries field when should update.
|
||||
*/
|
||||
export const entriesFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.items !== oldProps.items ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
|
||||
export const ITEMS_FILTER_ROLES_QUERY = JSON.stringify([
|
||||
{
|
||||
index: 1,
|
||||
fieldKey: 'sellable',
|
||||
value: true,
|
||||
condition: '&&',
|
||||
comparator: 'equals',
|
||||
},
|
||||
{
|
||||
index: 2,
|
||||
fieldKey: 'active',
|
||||
value: true,
|
||||
condition: '&&',
|
||||
comparator: 'equals',
|
||||
},
|
||||
]);
|
||||
121
src/containers/Sales/Invoices/InvoiceUniversalSearch.js
Normal file
121
src/containers/Sales/Invoices/InvoiceUniversalSearch.js
Normal file
@@ -0,0 +1,121 @@
|
||||
import React from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import { MenuItem } from '@blueprintjs/core';
|
||||
|
||||
import { T, Choose, Icon } from 'components';
|
||||
|
||||
import { highlightText } from 'utils';
|
||||
|
||||
import { RESOURCES_TYPES } from 'common/resourcesTypes';
|
||||
import withDrawerActions from '../../Drawer/withDrawerActions';
|
||||
|
||||
/**
|
||||
* Universal search invoice item select action.
|
||||
*/
|
||||
function InvoiceUniversalSearchSelectComponent({
|
||||
// #ownProps
|
||||
resourceType,
|
||||
resourceId,
|
||||
|
||||
// #withDrawerActions
|
||||
openDrawer,
|
||||
}) {
|
||||
if (resourceType === RESOURCES_TYPES.INVOICE) {
|
||||
openDrawer('invoice-detail-drawer', { invoiceId: resourceId });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const InvoiceUniversalSearchSelect = withDrawerActions(
|
||||
InvoiceUniversalSearchSelectComponent,
|
||||
);
|
||||
|
||||
/**
|
||||
* Invoice status.
|
||||
*/
|
||||
function InvoiceStatus({ customer }) {
|
||||
return (
|
||||
<Choose>
|
||||
<Choose.When condition={customer.is_fully_paid && customer.is_delivered}>
|
||||
<span class="status status-success">
|
||||
<T id={'paid'} />
|
||||
</span>
|
||||
</Choose.When>
|
||||
|
||||
<Choose.When condition={customer.is_delivered}>
|
||||
<Choose>
|
||||
<Choose.When condition={customer.is_overdue}>
|
||||
<span className={'status status-warning'}>
|
||||
{intl.get('overdue_by', { overdue: customer.overdue_days })}
|
||||
</span>
|
||||
</Choose.When>
|
||||
<Choose.Otherwise>
|
||||
<span className={'status status-warning'}>
|
||||
{intl.get('due_in', { due: customer.remaining_days })}
|
||||
</span>
|
||||
</Choose.Otherwise>
|
||||
</Choose>
|
||||
</Choose.When>
|
||||
<Choose.Otherwise>
|
||||
<span class="status status--gray">
|
||||
<T id={'draft'} />
|
||||
</span>
|
||||
</Choose.Otherwise>
|
||||
</Choose>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Universal search invoice item.
|
||||
*/
|
||||
export function InvoiceUniversalSearchItem(
|
||||
item,
|
||||
{ handleClick, modifiers, query },
|
||||
) {
|
||||
return (
|
||||
<MenuItem
|
||||
active={modifiers.active}
|
||||
text={
|
||||
<div>
|
||||
<div>{highlightText(item.text, query)}</div>
|
||||
<span class="bp3-text-muted">
|
||||
{highlightText(item.reference.invoice_no, query)}{' '}
|
||||
<Icon icon={'caret-right-16'} iconSize={16} />
|
||||
{item.reference.formatted_invoice_date}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
label={
|
||||
<>
|
||||
<div class="amount">${item.reference.balance}</div>
|
||||
<InvoiceStatus customer={item.reference} />
|
||||
</>
|
||||
}
|
||||
onClick={handleClick}
|
||||
className={'universal-search__item--invoice'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformes invoices to search.
|
||||
* @param {*} invoice
|
||||
* @returns
|
||||
*/
|
||||
const transformInvoicesToSearch = (invoice) => ({
|
||||
id: invoice.id,
|
||||
text: invoice.customer.display_name,
|
||||
label: invoice.formatted_balance,
|
||||
reference: invoice,
|
||||
});
|
||||
|
||||
/**
|
||||
* Binds universal search invoice configure.
|
||||
*/
|
||||
export const universalSearchInvoiceBind = () => ({
|
||||
resourceType: RESOURCES_TYPES.INVOICE,
|
||||
optionItemLabel: intl.get('invoices'),
|
||||
selectItemAction: InvoiceUniversalSearchSelect,
|
||||
itemRenderer: InvoiceUniversalSearchItem,
|
||||
itemSelect: transformInvoicesToSearch,
|
||||
});
|
||||
15
src/containers/Sales/Invoices/InvoicesAlerts.js
Normal file
15
src/containers/Sales/Invoices/InvoicesAlerts.js
Normal file
@@ -0,0 +1,15 @@
|
||||
import React from 'react';
|
||||
import InvoiceDeleteAlert from 'containers/Alerts/Invoices/InvoiceDeleteAlert';
|
||||
import InvoiceDeliverAlert from 'containers/Alerts/Invoices/InvoiceDeliverAlert';
|
||||
|
||||
/**
|
||||
* Invoices alert.
|
||||
*/
|
||||
export default function ItemsAlerts() {
|
||||
return (
|
||||
<div>
|
||||
<InvoiceDeleteAlert name={'invoice-delete'} />
|
||||
<InvoiceDeliverAlert name={'invoice-deliver'} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import React from 'react';
|
||||
import { useHistory } from 'react-router';
|
||||
import { Alignment, Navbar, NavbarGroup } from '@blueprintjs/core';
|
||||
|
||||
import { DashboardViewsTabs } from 'components';
|
||||
|
||||
import withInvoices from './withInvoices';
|
||||
import withInvoiceActions from './withInvoiceActions';
|
||||
|
||||
import { compose, transfromViewsToTabs } from 'utils';
|
||||
import { useInvoicesListContext } from './InvoicesListProvider';
|
||||
|
||||
/**
|
||||
* Invoices views tabs.
|
||||
*/
|
||||
function InvoiceViewTabs({
|
||||
// #withInvoiceActions
|
||||
setInvoicesTableState,
|
||||
|
||||
// #withInvoices
|
||||
invoicesCurrentView,
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Invoices list context.
|
||||
const { invoicesViews } = useInvoicesListContext();
|
||||
|
||||
const tabs = transfromViewsToTabs(invoicesViews);
|
||||
|
||||
// Handle tab change.
|
||||
const handleTabsChange = (viewSlug) => {
|
||||
setInvoicesTableState({ viewSlug });
|
||||
};
|
||||
// Handle click a new view tab.
|
||||
const handleClickNewView = () => {
|
||||
history.push('/custom_views/invoices/new');
|
||||
};
|
||||
|
||||
return (
|
||||
<Navbar className={'navbar--dashboard-views'}>
|
||||
<NavbarGroup align={Alignment.LEFT}>
|
||||
<DashboardViewsTabs
|
||||
currentViewSlug={invoicesCurrentView}
|
||||
resourceName={'invoices'}
|
||||
tabs={tabs}
|
||||
onNewViewTabClick={handleClickNewView}
|
||||
onChange={handleTabsChange}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
</Navbar>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withInvoiceActions,
|
||||
withInvoices(({ invoicesTableState }) => ({
|
||||
invoicesCurrentView: invoicesTableState.viewSlug,
|
||||
})),
|
||||
)(InvoiceViewTabs);
|
||||
@@ -0,0 +1,134 @@
|
||||
import React from 'react';
|
||||
import Icon from 'components/Icon';
|
||||
import {
|
||||
Button,
|
||||
Classes,
|
||||
NavbarDivider,
|
||||
NavbarGroup,
|
||||
Intent,
|
||||
Alignment,
|
||||
} from '@blueprintjs/core';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import {
|
||||
FormattedMessage as T,
|
||||
AdvancedFilterPopover,
|
||||
DashboardFilterButton,
|
||||
} from 'components';
|
||||
|
||||
import DashboardActionsBar from 'components/Dashboard/DashboardActionsBar';
|
||||
|
||||
import { If, DashboardActionViewsList } from 'components';
|
||||
|
||||
import { useRefreshInvoices } from 'hooks/query/invoices';
|
||||
import { useInvoicesListContext } from './InvoicesListProvider';
|
||||
|
||||
import withInvoiceActions from './withInvoiceActions';
|
||||
import withInvoices from './withInvoices';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
/**
|
||||
* Invoices table actions bar.
|
||||
*/
|
||||
function InvoiceActionsBar({
|
||||
// #withInvoiceActions
|
||||
setInvoicesTableState,
|
||||
|
||||
// #withInvoices
|
||||
invoicesFilterRoles,
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Sale invoices list context.
|
||||
const { invoicesViews, invoicesFields } = useInvoicesListContext();
|
||||
|
||||
// Handle new invoice button click.
|
||||
const handleClickNewInvoice = () => {
|
||||
history.push('/invoices/new');
|
||||
};
|
||||
|
||||
// Invoices refresh action.
|
||||
const { refresh } = useRefreshInvoices();
|
||||
|
||||
// Handle views tab change.
|
||||
const handleTabChange = (view) => {
|
||||
setInvoicesTableState({ viewSlug: view ? view.slug : null });
|
||||
};
|
||||
|
||||
// Handle click a refresh sale invoices
|
||||
const handleRefreshBtnClick = () => {
|
||||
refresh();
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardActionsBar>
|
||||
<NavbarGroup>
|
||||
<DashboardActionViewsList
|
||||
allMenuItem={true}
|
||||
resourceName={'invoices'}
|
||||
views={invoicesViews}
|
||||
onChange={handleTabChange}
|
||||
/>
|
||||
<NavbarDivider />
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'plus'} />}
|
||||
text={<T id={'new_invoice'} />}
|
||||
onClick={handleClickNewInvoice}
|
||||
/>
|
||||
<AdvancedFilterPopover
|
||||
advancedFilterProps={{
|
||||
conditions: invoicesFilterRoles,
|
||||
defaultFieldKey: 'invoice_no',
|
||||
fields: invoicesFields,
|
||||
onFilterChange: (filterConditions) => {
|
||||
setInvoicesTableState({ filterRoles: filterConditions });
|
||||
},
|
||||
}}
|
||||
>
|
||||
<DashboardFilterButton conditionsCount={invoicesFilterRoles.length} />
|
||||
</AdvancedFilterPopover>
|
||||
|
||||
<NavbarDivider />
|
||||
|
||||
<If condition={false}>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'trash-16'} iconSize={16} />}
|
||||
text={<T id={'delete'} />}
|
||||
intent={Intent.DANGER}
|
||||
/>
|
||||
</If>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'print-16'} iconSize={'16'} />}
|
||||
text={<T id={'print'} />}
|
||||
/>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'file-import-16'} />}
|
||||
text={<T id={'import'} />}
|
||||
/>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'file-export-16'} iconSize={'16'} />}
|
||||
text={<T id={'export'} />}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
<NavbarGroup align={Alignment.RIGHT}>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon="refresh-16" iconSize={14} />}
|
||||
onClick={handleRefreshBtnClick}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
</DashboardActionsBar>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withInvoiceActions,
|
||||
withInvoices(({ invoicesTableState }) => ({
|
||||
invoicesFilterRoles: invoicesTableState.filterRoles,
|
||||
})),
|
||||
)(InvoiceActionsBar);
|
||||
@@ -0,0 +1,158 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
import InvoicesEmptyStatus from './InvoicesEmptyStatus';
|
||||
|
||||
import { DataTable, DashboardContentTable } from 'components';
|
||||
import { TABLES } from 'common/tables';
|
||||
import { useMemorizedColumnsWidths } from 'hooks';
|
||||
|
||||
import TableSkeletonRows from 'components/Datatable/TableSkeletonRows';
|
||||
import TableSkeletonHeader from 'components/Datatable/TableHeaderSkeleton';
|
||||
|
||||
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
|
||||
import withInvoices from './withInvoices';
|
||||
import withInvoiceActions from './withInvoiceActions';
|
||||
import withAlertsActions from 'containers/Alert/withAlertActions';
|
||||
import withDrawerActions from 'containers/Drawer/withDrawerActions';
|
||||
import withDialogActions from 'containers/Dialog/withDialogActions';
|
||||
|
||||
import { useInvoicesTableColumns, ActionsMenu } from './components';
|
||||
import { useInvoicesListContext } from './InvoicesListProvider';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
/**
|
||||
* Invoices datatable.
|
||||
*/
|
||||
function InvoicesDataTable({
|
||||
// #withInvoicesActions
|
||||
setInvoicesTableState,
|
||||
|
||||
// #withInvoices
|
||||
invoicesTableState,
|
||||
|
||||
// #withAlertsActions
|
||||
openAlert,
|
||||
|
||||
// #withDrawerActions
|
||||
openDrawer,
|
||||
|
||||
// #withDialogAction
|
||||
openDialog,
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Invoices list context.
|
||||
const {
|
||||
invoices,
|
||||
pagination,
|
||||
isEmptyStatus,
|
||||
isInvoicesLoading,
|
||||
isInvoicesFetching,
|
||||
} = useInvoicesListContext();
|
||||
|
||||
// Invoices table columns.
|
||||
const columns = useInvoicesTableColumns();
|
||||
|
||||
// Handle delete sale invoice.
|
||||
const handleDeleteInvoice = ({ id }) => {
|
||||
openAlert('invoice-delete', { invoiceId: id });
|
||||
};
|
||||
|
||||
// Handle cancel/confirm invoice deliver.
|
||||
const handleDeliverInvoice = ({ id }) => {
|
||||
openAlert('invoice-deliver', { invoiceId: id });
|
||||
};
|
||||
|
||||
// Handle edit sale invoice.
|
||||
const handleEditInvoice = (invoice) => {
|
||||
history.push(`/invoices/${invoice.id}/edit`);
|
||||
};
|
||||
|
||||
// handle quick payment receive.
|
||||
const handleQuickPaymentReceive = ({ id }) => {
|
||||
openDialog('quick-payment-receive', { invoiceId: id });
|
||||
};
|
||||
|
||||
// Handle view detail invoice.
|
||||
const handleViewDetailInvoice = ({ id }) => {
|
||||
openDrawer('invoice-detail-drawer', { invoiceId: id });
|
||||
};
|
||||
|
||||
// Handle print invoices.
|
||||
const handlePrintInvoice = ({ id }) => {
|
||||
openDialog('invoice-pdf-preview', { invoiceId: id });
|
||||
};
|
||||
|
||||
// Handle cell click.
|
||||
const handleCellClick = (cell, event) => {
|
||||
openDrawer('invoice-detail-drawer', { invoiceId: cell.row.original.id });
|
||||
};
|
||||
|
||||
// Local storage memorizing columns widths.
|
||||
const [initialColumnsWidths, , handleColumnResizing] =
|
||||
useMemorizedColumnsWidths(TABLES.INVOICES);
|
||||
|
||||
// Handles fetch data once the table state change.
|
||||
const handleDataTableFetchData = useCallback(
|
||||
({ pageSize, pageIndex, sortBy }) => {
|
||||
setInvoicesTableState({
|
||||
pageSize,
|
||||
pageIndex,
|
||||
sortBy,
|
||||
});
|
||||
},
|
||||
[setInvoicesTableState],
|
||||
);
|
||||
|
||||
// Display invoice empty status instead of the table.
|
||||
if (isEmptyStatus) {
|
||||
return <InvoicesEmptyStatus />;
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardContentTable>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={invoices}
|
||||
loading={isInvoicesLoading}
|
||||
headerLoading={isInvoicesLoading}
|
||||
progressBarLoading={isInvoicesFetching}
|
||||
onFetchData={handleDataTableFetchData}
|
||||
manualSortBy={true}
|
||||
selectionColumn={true}
|
||||
noInitialFetch={true}
|
||||
sticky={true}
|
||||
pagination={true}
|
||||
manualPagination={true}
|
||||
pagesCount={pagination.pagesCount}
|
||||
autoResetSortBy={false}
|
||||
autoResetPage={false}
|
||||
TableLoadingRenderer={TableSkeletonRows}
|
||||
TableHeaderSkeletonRenderer={TableSkeletonHeader}
|
||||
ContextMenu={ActionsMenu}
|
||||
onCellClick={handleCellClick}
|
||||
initialColumnsWidths={initialColumnsWidths}
|
||||
onColumnResizing={handleColumnResizing}
|
||||
payload={{
|
||||
onDelete: handleDeleteInvoice,
|
||||
onDeliver: handleDeliverInvoice,
|
||||
onEdit: handleEditInvoice,
|
||||
onQuick: handleQuickPaymentReceive,
|
||||
onViewDetails: handleViewDetailInvoice,
|
||||
onPrint: handlePrintInvoice,
|
||||
}}
|
||||
/>
|
||||
</DashboardContentTable>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withDashboardActions,
|
||||
withInvoiceActions,
|
||||
withAlertsActions,
|
||||
withDrawerActions,
|
||||
withDialogActions,
|
||||
withInvoices(({ invoicesTableState }) => ({ invoicesTableState })),
|
||||
)(InvoicesDataTable);
|
||||
@@ -0,0 +1,37 @@
|
||||
import React from 'react';
|
||||
import { Button, Intent } from '@blueprintjs/core';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { EmptyStatus } from 'components';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
|
||||
export default function EstimatesEmptyStatus() {
|
||||
const history = useHistory();
|
||||
|
||||
return (
|
||||
<EmptyStatus
|
||||
title={<T id={'the_organization_doesn_t_receive_money_yet'} />}
|
||||
description={
|
||||
<p>
|
||||
<T id={'invoices_empty_status_description'} />
|
||||
</p>
|
||||
}
|
||||
action={
|
||||
<>
|
||||
<Button
|
||||
intent={Intent.PRIMARY}
|
||||
large={true}
|
||||
onClick={() => {
|
||||
history.push('/invoices/new');
|
||||
}}
|
||||
>
|
||||
<T id={'new_sale_invoice'} />
|
||||
</Button>
|
||||
|
||||
<Button intent={Intent.NONE} large={true}>
|
||||
<T id={'learn_more'} />
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import React from 'react';
|
||||
|
||||
import 'style/pages/SaleInvoice/List.scss';
|
||||
|
||||
import { DashboardContentTable, DashboardPageContent } from 'components';
|
||||
import InvoicesActionsBar from './InvoicesActionsBar';
|
||||
import { InvoicesListProvider } from './InvoicesListProvider';
|
||||
|
||||
import InvoiceViewTabs from './InvoiceViewTabs';
|
||||
import InvoicesDataTable from './InvoicesDataTable';
|
||||
import InvoicesAlerts from '../InvoicesAlerts';
|
||||
|
||||
import withInvoices from './withInvoices';
|
||||
import withInvoiceActions from './withInvoiceActions';
|
||||
import withAlertsActions from 'containers/Alert/withAlertActions';
|
||||
|
||||
import { transformTableStateToQuery, compose } from 'utils';
|
||||
|
||||
/**
|
||||
* Sale invoices list.
|
||||
*/
|
||||
function InvoicesList({
|
||||
// #withInvoice
|
||||
invoicesTableState,
|
||||
invoicesTableStateChanged,
|
||||
|
||||
// #withInvoicesActions
|
||||
resetInvoicesTableState,
|
||||
}) {
|
||||
// Resets the invoices table state once the page unmount.
|
||||
React.useEffect(
|
||||
() => () => {
|
||||
resetInvoicesTableState();
|
||||
},
|
||||
[resetInvoicesTableState],
|
||||
);
|
||||
|
||||
return (
|
||||
<InvoicesListProvider
|
||||
query={transformTableStateToQuery(invoicesTableState)}
|
||||
tableStateChanged={invoicesTableStateChanged}
|
||||
>
|
||||
<InvoicesActionsBar />
|
||||
|
||||
<DashboardPageContent>
|
||||
<InvoiceViewTabs />
|
||||
<InvoicesDataTable />
|
||||
</DashboardPageContent>
|
||||
|
||||
<InvoicesAlerts />
|
||||
</InvoicesListProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withInvoices(({ invoicesTableState, invoicesTableStateChanged }) => ({
|
||||
invoicesTableState,
|
||||
invoicesTableStateChanged,
|
||||
})),
|
||||
withInvoiceActions,
|
||||
withAlertsActions,
|
||||
)(InvoicesList);
|
||||
@@ -0,0 +1,65 @@
|
||||
import React, { createContext } from 'react';
|
||||
import { isEmpty } from 'lodash';
|
||||
|
||||
import DashboardInsider from 'components/Dashboard/DashboardInsider';
|
||||
import { useResourceViews, useResourceMeta, useInvoices } from 'hooks/query';
|
||||
import { getFieldsFromResourceMeta } from 'utils';
|
||||
|
||||
const InvoicesListContext = createContext();
|
||||
|
||||
/**
|
||||
* Accounts chart data provider.
|
||||
*/
|
||||
function InvoicesListProvider({ query, tableStateChanged, ...props }) {
|
||||
// Fetch accounts resource views and fields.
|
||||
const { data: invoicesViews, isLoading: isViewsLoading } =
|
||||
useResourceViews('sale_invoices');
|
||||
|
||||
// Fetch the accounts resource fields.
|
||||
const {
|
||||
data: resourceMeta,
|
||||
isLoading: isResourceLoading,
|
||||
isFetching: isResourceFetching,
|
||||
} = useResourceMeta('sale_invoices');
|
||||
|
||||
// Fetch accounts list according to the given custom view id.
|
||||
const {
|
||||
data: { invoices, pagination, filterMeta },
|
||||
isFetching: isInvoicesFetching,
|
||||
isLoading: isInvoicesLoading,
|
||||
} = useInvoices(query, { keepPreviousData: true });
|
||||
|
||||
// Detarmines the datatable empty status.
|
||||
const isEmptyStatus =
|
||||
isEmpty(invoices) && !tableStateChanged && !isInvoicesLoading;
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
invoices,
|
||||
pagination,
|
||||
|
||||
invoicesFields: getFieldsFromResourceMeta(resourceMeta.fields),
|
||||
invoicesViews,
|
||||
|
||||
isInvoicesLoading,
|
||||
isInvoicesFetching,
|
||||
isResourceFetching,
|
||||
isResourceLoading,
|
||||
isViewsLoading,
|
||||
|
||||
isEmptyStatus,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={isViewsLoading || isResourceLoading}
|
||||
name={'sales-invoices-list'}
|
||||
>
|
||||
<InvoicesListContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const useInvoicesListContext = () => React.useContext(InvoicesListContext);
|
||||
|
||||
export { InvoicesListProvider, useInvoicesListContext };
|
||||
227
src/containers/Sales/Invoices/InvoicesLanding/components.js
Normal file
227
src/containers/Sales/Invoices/InvoicesLanding/components.js
Normal file
@@ -0,0 +1,227 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Intent,
|
||||
Tag,
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuDivider,
|
||||
ProgressBar,
|
||||
} from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
import clsx from 'classnames';
|
||||
|
||||
import { CLASSES } from '../../../../common/classes';
|
||||
import {
|
||||
FormatDateCell,
|
||||
FormattedMessage as T,
|
||||
AppToaster,
|
||||
Choose,
|
||||
If,
|
||||
Icon,
|
||||
} from 'components';
|
||||
import { formattedAmount, safeCallback, calculateStatus } from 'utils';
|
||||
|
||||
export const statusAccessor = (row) => {
|
||||
return (
|
||||
<div className={'status-accessor'}>
|
||||
<Choose>
|
||||
<Choose.When condition={row.is_fully_paid && row.is_delivered}>
|
||||
<span className={'fully-paid-icon'}>
|
||||
<Icon icon="small-tick" iconSize={18} />
|
||||
</span>
|
||||
<span class="fully-paid-text">
|
||||
<T id={'paid'} />
|
||||
</span>
|
||||
</Choose.When>
|
||||
|
||||
<Choose.When condition={row.is_delivered}>
|
||||
<Choose>
|
||||
<Choose.When condition={row.is_overdue}>
|
||||
<span className={'overdue-status'}>
|
||||
{intl.get('overdue_by', { overdue: row.overdue_days })}
|
||||
</span>
|
||||
</Choose.When>
|
||||
<Choose.Otherwise>
|
||||
<span className={'due-status'}>
|
||||
{intl.get('due_in', { due: row.remaining_days })}
|
||||
</span>
|
||||
</Choose.Otherwise>
|
||||
</Choose>
|
||||
|
||||
<If condition={row.is_partially_paid}>
|
||||
<span class="partial-paid">
|
||||
{intl.get('day_partially_paid', {
|
||||
due: formattedAmount(row.due_amount, row.currency_code),
|
||||
})}
|
||||
</span>
|
||||
<ProgressBar
|
||||
animate={false}
|
||||
stripes={false}
|
||||
intent={Intent.PRIMARY}
|
||||
value={calculateStatus(row.payment_amount, row.balance)}
|
||||
/>
|
||||
</If>
|
||||
</Choose.When>
|
||||
<Choose.Otherwise>
|
||||
<Tag minimal={true}>
|
||||
<T id={'draft'} />
|
||||
</Tag>
|
||||
</Choose.Otherwise>
|
||||
</Choose>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const handleDeleteErrors = (errors) => {
|
||||
if (
|
||||
errors.find(
|
||||
(error) => error.type === 'INVOICE_HAS_ASSOCIATED_PAYMENT_ENTRIES',
|
||||
)
|
||||
) {
|
||||
AppToaster.show({
|
||||
message: intl.get('the_invoice_cannot_be_deleted'),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
}
|
||||
if (
|
||||
errors.find(
|
||||
(error) => error.type === 'INVOICE_AMOUNT_SMALLER_THAN_PAYMENT_AMOUNT',
|
||||
)
|
||||
) {
|
||||
AppToaster.show({
|
||||
message: intl.get('the_payment_amount_that_received'),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export function ActionsMenu({
|
||||
payload: {
|
||||
onEdit,
|
||||
onDeliver,
|
||||
onDelete,
|
||||
onDrawer,
|
||||
onQuick,
|
||||
onViewDetails,
|
||||
onPrint,
|
||||
},
|
||||
row: { original },
|
||||
}) {
|
||||
return (
|
||||
<Menu>
|
||||
<MenuItem
|
||||
icon={<Icon icon="reader-18" />}
|
||||
text={intl.get('view_details')}
|
||||
onClick={safeCallback(onViewDetails, original)}
|
||||
/>
|
||||
<MenuDivider />
|
||||
<MenuItem
|
||||
icon={<Icon icon="pen-18" />}
|
||||
text={intl.get('edit_invoice')}
|
||||
onClick={safeCallback(onEdit, original)}
|
||||
/>
|
||||
<If condition={!original.is_delivered}>
|
||||
<MenuItem
|
||||
icon={<Icon icon="send" iconSize={16} />}
|
||||
text={intl.get('mark_as_delivered')}
|
||||
onClick={safeCallback(onDeliver, original)}
|
||||
/>
|
||||
</If>
|
||||
<If condition={original.is_delivered && !original.is_fully_paid}>
|
||||
<MenuItem
|
||||
icon={<Icon icon="quick-payment-16" iconSize={16} />}
|
||||
text={intl.get('add_payment')}
|
||||
onClick={safeCallback(onQuick, original)}
|
||||
/>
|
||||
</If>
|
||||
<MenuItem
|
||||
icon={<Icon icon={'print-16'} iconSize={16} />}
|
||||
text={intl.get('print')}
|
||||
onClick={safeCallback(onPrint, original)}
|
||||
/>
|
||||
<MenuItem
|
||||
text={intl.get('delete_invoice')}
|
||||
intent={Intent.DANGER}
|
||||
onClick={safeCallback(onDelete, original)}
|
||||
icon={<Icon icon="trash-16" iconSize={16} />}
|
||||
/>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve invoices table columns.
|
||||
*/
|
||||
export function useInvoicesTableColumns() {
|
||||
return React.useMemo(
|
||||
() => [
|
||||
{
|
||||
id: 'invoice_date',
|
||||
Header: intl.get('invoice_date'),
|
||||
accessor: 'invoice_date',
|
||||
Cell: FormatDateCell,
|
||||
width: 110,
|
||||
className: 'invoice_date',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'customer',
|
||||
Header: intl.get('customer_name'),
|
||||
accessor: 'customer.display_name',
|
||||
width: 180,
|
||||
className: 'customer_id',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
|
||||
{
|
||||
id: 'invoice_no',
|
||||
Header: intl.get('invoice_no__'),
|
||||
accessor: 'invoice_no',
|
||||
width: 100,
|
||||
className: 'invoice_no',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'amount',
|
||||
Header: intl.get('balance'),
|
||||
accessor: 'formatted_amount',
|
||||
width: 120,
|
||||
align: 'right',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
className: clsx(CLASSES.FONT_BOLD),
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
Header: intl.get('status'),
|
||||
accessor: (row) => statusAccessor(row),
|
||||
width: 160,
|
||||
className: 'status',
|
||||
clickable: true,
|
||||
},
|
||||
{
|
||||
id: 'due_date',
|
||||
Header: intl.get('due_date'),
|
||||
accessor: 'due_date',
|
||||
Cell: FormatDateCell,
|
||||
width: 110,
|
||||
className: 'due_date',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'reference_no',
|
||||
Header: intl.get('reference_no'),
|
||||
accessor: 'reference_no',
|
||||
width: 90,
|
||||
className: 'reference_no',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { connect } from 'react-redux';
|
||||
import {
|
||||
setInvoicesTableState,
|
||||
resetInvoicesTableState
|
||||
} from 'store/Invoice/invoices.actions';
|
||||
|
||||
const mapDipatchToProps = (dispatch) => ({
|
||||
setInvoicesTableState: (queries) => dispatch(setInvoicesTableState(queries)),
|
||||
resetInvoicesTableState: () => dispatch(resetInvoicesTableState()),
|
||||
});
|
||||
|
||||
export default connect(null, mapDipatchToProps);
|
||||
@@ -0,0 +1,19 @@
|
||||
import { connect } from 'react-redux';
|
||||
import {
|
||||
getInvoicesTableStateFactory,
|
||||
isInvoicesTableStateChangedFactory,
|
||||
} from 'store/Invoice/invoices.selector';
|
||||
|
||||
export default (mapState) => {
|
||||
const getInvoicesTableState = getInvoicesTableStateFactory();
|
||||
const isInvoicesTableStateChanged = isInvoicesTableStateChangedFactory();
|
||||
|
||||
const mapStateToProps = (state, props) => {
|
||||
const mapped = {
|
||||
invoicesTableState: getInvoicesTableState(state, props),
|
||||
invoicesTableStateChanged: isInvoicesTableStateChanged(state, props),
|
||||
};
|
||||
return mapState ? mapState(mapped, state, props) : mapped;
|
||||
};
|
||||
return connect(mapStateToProps);
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import React, { lazy } from 'react';
|
||||
import withDrawers from 'containers/Drawer/withDrawers';
|
||||
import { Drawer, DrawerSuspense } from 'components';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
const PaymentReceiveDrawerContent = lazy(() =>
|
||||
import('./PaymentReceiveDrawerContent'),
|
||||
);
|
||||
|
||||
/**
|
||||
* payment receive drawer.
|
||||
*/
|
||||
function PaymentReceiveDrawer({
|
||||
name,
|
||||
//#withDrawer
|
||||
isOpen,
|
||||
payload: { paymentReceiveId },
|
||||
|
||||
}) {
|
||||
|
||||
return (
|
||||
<Drawer isOpen={isOpen} name={name}>
|
||||
<DrawerSuspense>
|
||||
<PaymentReceiveDrawerContent paymentReceiveId={paymentReceiveId} />
|
||||
</DrawerSuspense>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withDrawers())(PaymentReceiveDrawer);
|
||||
@@ -0,0 +1,17 @@
|
||||
import React from 'react';
|
||||
import { PaymentReceiveDrawerProvider } from './PaymentReceiveDrawerProvider';
|
||||
import PaymentReceivePaper from './PaymentReceivePaper';
|
||||
/**
|
||||
* payment receive drawer content.
|
||||
*/
|
||||
export default function PaymentReceiveDrawerContent({
|
||||
// #ownProp
|
||||
paymentReceiveId,
|
||||
}) {
|
||||
|
||||
return (
|
||||
<PaymentReceiveDrawerProvider paymentReceiveId={paymentReceiveId}>
|
||||
<PaymentReceivePaper />
|
||||
</PaymentReceiveDrawerProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import { usePaymentReceive } from 'hooks/query';
|
||||
import { DrawerHeaderContent, DashboardInsider } from 'components';
|
||||
|
||||
const PaymentReceiveDrawerContext = createContext();
|
||||
|
||||
function PaymentReceiveDrawerProvider({ paymentReceiveId, ...props }) {
|
||||
const {
|
||||
data: paymentReceive,
|
||||
isFetching: isPaymentReceiveLoading,
|
||||
} = usePaymentReceive(paymentReceiveId, {
|
||||
enabled: !!paymentReceiveId,
|
||||
});
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
paymentReceiveId,
|
||||
paymentReceive,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider loading={isPaymentReceiveLoading}>
|
||||
<DrawerHeaderContent name={'payment-receive-drawer'} />
|
||||
<PaymentReceiveDrawerContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
const usePaymentReceiveDrawerContext = () =>
|
||||
useContext(PaymentReceiveDrawerContext);
|
||||
|
||||
export { PaymentReceiveDrawerProvider, usePaymentReceiveDrawerContext };
|
||||
@@ -0,0 +1,9 @@
|
||||
import React from 'react';
|
||||
import PaymentPaperTemplate from 'containers/Drawers/PaymentPaperTemplate/PaymentPaperTemplate';
|
||||
import { usePaymentReceiveDrawerContext } from './PaymentReceiveDrawerProvider';
|
||||
|
||||
export default function PaymentReceivePaper() {
|
||||
const { paymentReceive } = usePaymentReceiveDrawerContext();
|
||||
|
||||
return <PaymentPaperTemplate paperData={paymentReceive} />;
|
||||
}
|
||||
13
src/containers/Sales/PaymentReceives/PaymentReceiveAlerts.js
Normal file
13
src/containers/Sales/PaymentReceives/PaymentReceiveAlerts.js
Normal file
@@ -0,0 +1,13 @@
|
||||
import React from 'react';
|
||||
import PaymentReceiveDeleteAlert from 'containers/Alerts/PaymentReceives/PaymentReceiveDeleteAlert';
|
||||
|
||||
/**
|
||||
* PaymentReceives alert.
|
||||
*/
|
||||
export default function EstimatesAlerts() {
|
||||
return (
|
||||
<div>
|
||||
<PaymentReceiveDeleteAlert name={'payment-receive-delete'} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Intent,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
Popover,
|
||||
PopoverInteractionKind,
|
||||
Position,
|
||||
Menu,
|
||||
MenuItem,
|
||||
} from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import classNames from 'classnames';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { CLASSES } from 'common/classes';
|
||||
|
||||
import { Icon } from 'components';
|
||||
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
|
||||
|
||||
/**
|
||||
* Payment receive floating actions bar.
|
||||
*/
|
||||
export default function PaymentReceiveFormFloatingActions() {
|
||||
// Payment receive form context.
|
||||
const { setSubmitPayload, isNewMode } = usePaymentReceiveFormContext();
|
||||
|
||||
// Formik form context.
|
||||
const { isSubmitting, submitForm, resetForm } = useFormikContext();
|
||||
|
||||
// History context.
|
||||
const history = useHistory();
|
||||
|
||||
// Handle submit button click.
|
||||
const handleSubmitBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle clear button click.
|
||||
const handleClearBtnClick = (event) => {
|
||||
resetForm();
|
||||
};
|
||||
|
||||
// Handle cancel button click.
|
||||
const handleCancelBtnClick = (event) => {
|
||||
history.goBack();
|
||||
};
|
||||
|
||||
// Handle submit & new button click.
|
||||
const handleSubmitAndNewClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit & continue editing button click.
|
||||
const handleSubmitContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, publish: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
|
||||
{/* ----------- Save and New ----------- */}
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
type="submit"
|
||||
onClick={handleSubmitBtnClick}
|
||||
text={!isNewMode ? <T id={'edit'} /> : <T id={'save'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitAndNewClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'save_continue_editing'} />}
|
||||
onClick={handleSubmitContinueEditingBtnClick}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
minimal={true}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
|
||||
/>
|
||||
</Popover>
|
||||
</ButtonGroup>
|
||||
|
||||
{/* ----------- Clear & Reset----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
disabled={isSubmitting}
|
||||
onClick={handleClearBtnClick}
|
||||
text={!isNewMode ? <T id={'reset'} /> : <T id={'clear'} />}
|
||||
/>
|
||||
|
||||
{/* ----------- Cancel ----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
disabled={isSubmitting}
|
||||
onClick={handleCancelBtnClick}
|
||||
text={<T id={'cancel'} />}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Formik, Form } from 'formik';
|
||||
import intl from 'react-intl-universal';
|
||||
import { omit, sumBy, pick, isEmpty, defaultTo } from 'lodash';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import classNames from 'classnames';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
import 'style/pages/PaymentReceive/PageForm.scss';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import PaymentReceiveHeader from './PaymentReceiveFormHeader';
|
||||
import PaymentReceiveFormBody from './PaymentReceiveFormBody';
|
||||
import PaymentReceiveFloatingActions from './PaymentReceiveFloatingActions';
|
||||
import PaymentReceiveFormFooter from './PaymentReceiveFormFooter';
|
||||
import PaymentReceiveFormAlerts from './PaymentReceiveFormAlerts';
|
||||
import PaymentReceiveFormDialogs from './PaymentReceiveFormDialogs';
|
||||
import { PaymentReceiveInnerProvider } from './PaymentReceiveInnerProvider';
|
||||
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import {
|
||||
EditPaymentReceiveFormSchema,
|
||||
CreatePaymentReceiveFormSchema,
|
||||
} from './PaymentReceiveForm.schema';
|
||||
import { AppToaster } from 'components';
|
||||
import { transactionNumber, compose } from 'utils';
|
||||
|
||||
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
|
||||
import { defaultPaymentReceive, transformToEditForm } from './utils';
|
||||
|
||||
/**
|
||||
* Payment Receive form.
|
||||
*/
|
||||
function PaymentReceiveForm({
|
||||
// #withSettings
|
||||
preferredDepositAccount,
|
||||
paymentReceiveNextNumber,
|
||||
paymentReceiveNumberPrefix,
|
||||
paymentReceiveAutoIncrement,
|
||||
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Payment receive form context.
|
||||
const {
|
||||
isNewMode,
|
||||
paymentReceiveEditPage,
|
||||
paymentEntriesEditPage,
|
||||
paymentReceiveId,
|
||||
submitPayload,
|
||||
editPaymentReceiveMutate,
|
||||
createPaymentReceiveMutate,
|
||||
} = usePaymentReceiveFormContext();
|
||||
|
||||
// Payment receive number.
|
||||
const nextPaymentNumber = transactionNumber(
|
||||
paymentReceiveNumberPrefix,
|
||||
paymentReceiveNextNumber,
|
||||
);
|
||||
// Form initial values.
|
||||
const initialValues = useMemo(
|
||||
() => ({
|
||||
...(!isEmpty(paymentReceiveEditPage)
|
||||
? transformToEditForm(paymentReceiveEditPage, paymentEntriesEditPage)
|
||||
: {
|
||||
...defaultPaymentReceive,
|
||||
...(paymentReceiveAutoIncrement && {
|
||||
payment_receive_no: nextPaymentNumber,
|
||||
deposit_account_id: defaultTo(preferredDepositAccount, ''),
|
||||
}),
|
||||
currency_code: base_currency,
|
||||
}),
|
||||
}),
|
||||
[
|
||||
paymentReceiveEditPage,
|
||||
nextPaymentNumber,
|
||||
paymentEntriesEditPage,
|
||||
paymentReceiveAutoIncrement,
|
||||
preferredDepositAccount,
|
||||
],
|
||||
);
|
||||
|
||||
// Handle form submit.
|
||||
const handleSubmitForm = (
|
||||
values,
|
||||
{ setSubmitting, resetForm, setFieldError },
|
||||
) => {
|
||||
setSubmitting(true);
|
||||
|
||||
// Filters entries that have no `invoice_id` and `payment_amount`.
|
||||
const entries = values.entries
|
||||
.filter((entry) => entry.invoice_id && entry.payment_amount)
|
||||
.map((entry) => ({
|
||||
...pick(entry, ['invoice_id', 'payment_amount']),
|
||||
}));
|
||||
|
||||
// Calculates the total payment amount of entries.
|
||||
const totalPaymentAmount = sumBy(entries, 'payment_amount');
|
||||
|
||||
if (totalPaymentAmount <= 0) {
|
||||
AppToaster.show({
|
||||
message: intl.get('you_cannot_make_payment_with_zero_total_amount'),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const form = {
|
||||
...omit(values, ['payment_receive_no_manually', 'payment_receive_no']),
|
||||
...(values.payment_receive_no_manually && {
|
||||
payment_receive_no: values.payment_receive_no,
|
||||
}),
|
||||
entries,
|
||||
};
|
||||
|
||||
// Handle request response success.
|
||||
const onSaved = (response) => {
|
||||
AppToaster.show({
|
||||
message: intl.get(
|
||||
paymentReceiveId
|
||||
? 'the_payment_receive_transaction_has_been_edited'
|
||||
: 'the_payment_receive_transaction_has_been_created',
|
||||
),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
|
||||
if (submitPayload.redirect) {
|
||||
history.push('/payment-receives');
|
||||
}
|
||||
if (submitPayload.resetForm) {
|
||||
resetForm();
|
||||
}
|
||||
};
|
||||
// Handle request response errors.
|
||||
const onError = ({
|
||||
response: {
|
||||
data: { errors },
|
||||
},
|
||||
}) => {
|
||||
const getError = (errorType) => errors.find((e) => e.type === errorType);
|
||||
|
||||
if (getError('PAYMENT_RECEIVE_NO_EXISTS')) {
|
||||
setFieldError(
|
||||
'payment_receive_no',
|
||||
intl.get('payment_number_is_not_unique'),
|
||||
);
|
||||
}
|
||||
if (getError('PAYMENT_RECEIVE_NO_REQUIRED')) {
|
||||
setFieldError(
|
||||
'payment_receive_no',
|
||||
intl.get('payment_receive.field.error.payment_receive_no_required'),
|
||||
);
|
||||
}
|
||||
setSubmitting(false);
|
||||
};
|
||||
|
||||
if (paymentReceiveId) {
|
||||
editPaymentReceiveMutate([paymentReceiveId, form])
|
||||
.then(onSaved)
|
||||
.catch(onError);
|
||||
} else {
|
||||
createPaymentReceiveMutate(form).then(onSaved).catch(onError);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
CLASSES.PAGE_FORM,
|
||||
CLASSES.PAGE_FORM_STRIP_STYLE,
|
||||
CLASSES.PAGE_FORM_PAYMENT_RECEIVE,
|
||||
)}
|
||||
>
|
||||
<Formik
|
||||
initialValues={initialValues}
|
||||
onSubmit={handleSubmitForm}
|
||||
validationSchema={
|
||||
isNewMode
|
||||
? CreatePaymentReceiveFormSchema
|
||||
: EditPaymentReceiveFormSchema
|
||||
}
|
||||
>
|
||||
<Form>
|
||||
<PaymentReceiveInnerProvider>
|
||||
<PaymentReceiveHeader />
|
||||
<PaymentReceiveFormBody />
|
||||
<PaymentReceiveFormFooter />
|
||||
<PaymentReceiveFloatingActions />
|
||||
|
||||
{/* ------- Alerts & Dialogs ------- */}
|
||||
<PaymentReceiveFormAlerts />
|
||||
<PaymentReceiveFormDialogs />
|
||||
</PaymentReceiveInnerProvider>
|
||||
</Form>
|
||||
</Formik>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withSettings(({ paymentReceiveSettings }) => ({
|
||||
paymentReceiveSettings,
|
||||
paymentReceiveNextNumber: paymentReceiveSettings?.nextNumber,
|
||||
paymentReceiveNumberPrefix: paymentReceiveSettings?.numberPrefix,
|
||||
paymentReceiveAutoIncrement: paymentReceiveSettings?.autoIncrement,
|
||||
preferredDepositAccount: paymentReceiveSettings?.depositAccount,
|
||||
})),
|
||||
withCurrentOrganization(),
|
||||
)(PaymentReceiveForm);
|
||||
@@ -0,0 +1,38 @@
|
||||
import * as Yup from 'yup';
|
||||
import intl from 'react-intl-universal';
|
||||
import { DATATYPES_LENGTH } from 'common/dataTypes';
|
||||
|
||||
const Schema = Yup.object().shape({
|
||||
customer_id: Yup.string()
|
||||
.label(intl.get('customer_name_'))
|
||||
.required(),
|
||||
payment_date: Yup.date()
|
||||
.required()
|
||||
.label(intl.get('payment_date_')),
|
||||
deposit_account_id: Yup.number()
|
||||
.required()
|
||||
.label(intl.get('deposit_account_')),
|
||||
full_amount: Yup.number().nullable(),
|
||||
payment_receive_no: Yup.string()
|
||||
.nullable()
|
||||
.max(DATATYPES_LENGTH.STRING)
|
||||
.label(intl.get('payment_receive_no_')),
|
||||
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING).nullable(),
|
||||
// statement: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
|
||||
entries: Yup.array().of(
|
||||
Yup.object().shape({
|
||||
id: Yup.number().nullable(),
|
||||
due_amount: Yup.number().nullable(),
|
||||
payment_amount: Yup.number().nullable().max(Yup.ref('due_amount')),
|
||||
invoice_id: Yup.number()
|
||||
.nullable()
|
||||
.when(['payment_amount'], {
|
||||
is: (payment_amount) => payment_amount,
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export const CreatePaymentReceiveFormSchema = Schema;
|
||||
export const EditPaymentReceiveFormSchema = Schema;
|
||||
@@ -0,0 +1,26 @@
|
||||
import React from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import ClearingAllLinesAlert from 'containers/Alerts/PaymentReceives/ClearingAllLinesAlert';
|
||||
import { clearAllPaymentEntries } from './utils';
|
||||
|
||||
/**
|
||||
* Payment receive form alerts.
|
||||
*/
|
||||
export default function PaymentReceiveFormAlerts() {
|
||||
const { values: { entries }, setFieldValue } = useFormikContext();
|
||||
|
||||
const handleClearingAllLines = () => {
|
||||
const newEntries = clearAllPaymentEntries(entries);
|
||||
setFieldValue('entries', newEntries);
|
||||
setFieldValue('full_amount', '');
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ClearingAllLinesAlert
|
||||
name={'clear-all-lines-payment-receive'}
|
||||
onConfirm={handleClearingAllLines}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import React from 'react';
|
||||
import { FastField } from 'formik';
|
||||
import PaymentReceiveItemsTable from './PaymentReceiveItemsTable';
|
||||
import classNames from 'classnames';
|
||||
import { CLASSES } from 'common/classes';
|
||||
|
||||
/**
|
||||
* Payment Receive form body.
|
||||
*/
|
||||
export default function PaymentReceiveFormBody() {
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
|
||||
<FastField name={'entries'}>
|
||||
{({ form: { values, setFieldValue }, field: { value } }) => (
|
||||
<PaymentReceiveItemsTable
|
||||
entries={value}
|
||||
onUpdateData={(newEntries) => {
|
||||
setFieldValue('entries', newEntries);
|
||||
}}
|
||||
currencyCode={values.currency_code}
|
||||
/>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import React from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import PaymentReceiveNumberDialog from 'containers/Dialogs/PaymentReceiveNumberDialog';
|
||||
|
||||
/**
|
||||
* Payment receive form dialogs.
|
||||
*/
|
||||
export default function PaymentReceiveFormDialogs() {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
|
||||
const handleUpdatePaymentNumber = ({ incrementNumber, manually }) => {
|
||||
setFieldValue('payment_receive_no', incrementNumber);
|
||||
setFieldValue('payment_receive_no_manually', manually)
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<PaymentReceiveNumberDialog
|
||||
dialogName={'payment-receive-number-form'}
|
||||
onConfirm={handleUpdatePaymentNumber}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import React from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { FormGroup, TextArea } from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { FastField } from 'formik';
|
||||
import { Row, Col, Postbox } from 'components';
|
||||
import { CLASSES } from 'common/classes';
|
||||
|
||||
/**
|
||||
* Payment receive form footer.
|
||||
*/
|
||||
export default function PaymentReceiveFormFooter({ getFieldProps }) {
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
|
||||
<Postbox title={<T id={'payment_receive_details'} />} defaultOpen={false}>
|
||||
<Row>
|
||||
<Col md={8}>
|
||||
{/* --------- Statement --------- */}
|
||||
<FastField name={'statement'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'statement'} />}
|
||||
className={'form-group--statement'}
|
||||
>
|
||||
<TextArea growVertically={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</Col>
|
||||
</Row>
|
||||
</Postbox>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { sumBy } from 'lodash';
|
||||
import { useFormikContext } from 'formik';
|
||||
import classNames from 'classnames';
|
||||
import { Money } from 'components';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import PaymentReceiveHeaderFields from './PaymentReceiveHeaderFields';
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
/**
|
||||
* Payment receive form header.
|
||||
*/
|
||||
function PaymentReceiveFormHeader({
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
// Formik form context.
|
||||
const { values } = useFormikContext();
|
||||
|
||||
// Calculates the total payment amount from due amount.
|
||||
const paymentFullAmount = useMemo(
|
||||
() => sumBy(values.entries, 'payment_amount'),
|
||||
[values.entries],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}>
|
||||
<PaymentReceiveHeaderFields />
|
||||
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_BIG_NUMBERS)}>
|
||||
<div class="big-amount">
|
||||
<span class="big-amount__label">
|
||||
<T id={'amount_received'} />
|
||||
</span>
|
||||
<h1 class="big-amount__number">
|
||||
<Money amount={paymentFullAmount} currency={base_currency} />
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withCurrentOrganization())(PaymentReceiveFormHeader);
|
||||
@@ -0,0 +1,19 @@
|
||||
import React from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
import { PaymentReceiveFormProvider } from './PaymentReceiveFormProvider';
|
||||
import PaymentReceiveForm from './PaymentReceiveForm';
|
||||
|
||||
/**
|
||||
* Payment receive form page.
|
||||
*/
|
||||
export default function PaymentReceiveFormPage() {
|
||||
const { id: paymentReceiveId } = useParams();
|
||||
const paymentReceiveIdInt = parseInt(paymentReceiveId, 10);
|
||||
|
||||
return (
|
||||
<PaymentReceiveFormProvider paymentReceiveId={paymentReceiveIdInt}>
|
||||
<PaymentReceiveForm paymentReceiveId={paymentReceiveIdInt} />
|
||||
</PaymentReceiveFormProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import { DashboardInsider } from 'components';
|
||||
import {
|
||||
useSettingsPaymentReceives,
|
||||
usePaymentReceiveEditPage,
|
||||
useAccounts,
|
||||
useCustomers,
|
||||
useCreatePaymentReceive,
|
||||
useEditPaymentReceive,
|
||||
} from 'hooks/query';
|
||||
|
||||
// Payment receive form context.
|
||||
const PaymentReceiveFormContext = createContext();
|
||||
|
||||
/**
|
||||
* Payment receive form provider.
|
||||
*/
|
||||
function PaymentReceiveFormProvider({ paymentReceiveId, ...props }) {
|
||||
// Form state.
|
||||
const [submitPayload, setSubmitPayload] = React.useState({});
|
||||
|
||||
// Fetches payment recevie details.
|
||||
const {
|
||||
data: {
|
||||
paymentReceive: paymentReceiveEditPage,
|
||||
entries: paymentEntriesEditPage,
|
||||
},
|
||||
isLoading: isPaymentLoading,
|
||||
isFetching: isPaymentFetching,
|
||||
} = usePaymentReceiveEditPage(paymentReceiveId, {
|
||||
enabled: !!paymentReceiveId,
|
||||
});
|
||||
// Handle fetch accounts data.
|
||||
const { data: accounts, isLoading: isAccountsLoading } = useAccounts();
|
||||
|
||||
// Fetch payment made settings.
|
||||
const fetchSettings = useSettingsPaymentReceives();
|
||||
|
||||
// Fetches customers list.
|
||||
const {
|
||||
data: { customers },
|
||||
isLoading: isCustomersLoading,
|
||||
} = useCustomers({ page_size: 10000 });
|
||||
|
||||
// Detarmines whether the new mode.
|
||||
const isNewMode = !paymentReceiveId;
|
||||
|
||||
// Create and edit payment receive mutations.
|
||||
const { mutateAsync: editPaymentReceiveMutate } = useEditPaymentReceive();
|
||||
const { mutateAsync: createPaymentReceiveMutate } = useCreatePaymentReceive();
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
paymentReceiveId,
|
||||
paymentReceiveEditPage,
|
||||
paymentEntriesEditPage,
|
||||
accounts,
|
||||
customers,
|
||||
|
||||
isPaymentLoading,
|
||||
isAccountsLoading,
|
||||
isPaymentFetching,
|
||||
isCustomersLoading,
|
||||
isNewMode,
|
||||
|
||||
submitPayload,
|
||||
setSubmitPayload,
|
||||
|
||||
editPaymentReceiveMutate,
|
||||
createPaymentReceiveMutate,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={isPaymentLoading || isAccountsLoading || isCustomersLoading}
|
||||
name={'payment-receive-form'}
|
||||
>
|
||||
<PaymentReceiveFormContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const usePaymentReceiveFormContext = () =>
|
||||
useContext(PaymentReceiveFormContext);
|
||||
|
||||
export { PaymentReceiveFormProvider, usePaymentReceiveFormContext };
|
||||
@@ -0,0 +1,325 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import {
|
||||
FormGroup,
|
||||
InputGroup,
|
||||
Position,
|
||||
ControlGroup,
|
||||
Button,
|
||||
} from '@blueprintjs/core';
|
||||
import { DateInput } from '@blueprintjs/datetime';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { FastField, Field, useFormikContext, ErrorMessage } from 'formik';
|
||||
|
||||
import { useAutofocus } from 'hooks';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import classNames from 'classnames';
|
||||
import {
|
||||
compose,
|
||||
safeSumBy,
|
||||
momentFormatter,
|
||||
tansformDateValue,
|
||||
handleDateChange,
|
||||
inputIntent,
|
||||
} from 'utils';
|
||||
import {
|
||||
AccountsSelectList,
|
||||
ContactSelecetList,
|
||||
FieldRequiredHint,
|
||||
Icon,
|
||||
InputPrependButton,
|
||||
MoneyInputGroup,
|
||||
InputPrependText,
|
||||
Hint,
|
||||
Money,
|
||||
} from 'components';
|
||||
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
|
||||
import { ACCOUNT_TYPE } from 'common/accountTypes';
|
||||
|
||||
import withDialogActions from 'containers/Dialog/withDialogActions';
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import {
|
||||
useObservePaymentNoSettings,
|
||||
amountPaymentEntries,
|
||||
fullAmountPaymentEntries,
|
||||
customersFieldShouldUpdate,
|
||||
accountsFieldShouldUpdate,
|
||||
} from './utils';
|
||||
import { toSafeInteger } from 'lodash';
|
||||
|
||||
/**
|
||||
* Payment receive header fields.
|
||||
*/
|
||||
function PaymentReceiveHeaderFields({
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
|
||||
// #withDialogActions
|
||||
openDialog,
|
||||
|
||||
// #withSettings
|
||||
paymentReceiveAutoIncrement,
|
||||
paymentReceiveNumberPrefix,
|
||||
paymentReceiveNextNumber,
|
||||
}) {
|
||||
// Payment receive form context.
|
||||
const { customers, accounts, isNewMode } = usePaymentReceiveFormContext();
|
||||
|
||||
// Formik form context.
|
||||
const {
|
||||
values: { entries },
|
||||
setFieldValue,
|
||||
} = useFormikContext();
|
||||
|
||||
const customerFieldRef = useAutofocus();
|
||||
|
||||
// Calculates the full-amount received.
|
||||
const totalDueAmount = useMemo(
|
||||
() => safeSumBy(entries, 'due_amount'),
|
||||
[entries],
|
||||
);
|
||||
// Handle receive full-amount link click.
|
||||
const handleReceiveFullAmountClick = () => {
|
||||
const newEntries = fullAmountPaymentEntries(entries);
|
||||
const fullAmount = safeSumBy(newEntries, 'payment_amount');
|
||||
|
||||
setFieldValue('entries', newEntries);
|
||||
setFieldValue('full_amount', fullAmount);
|
||||
};
|
||||
// Handles the full-amount field blur.
|
||||
const onFullAmountBlur = (value) => {
|
||||
const newEntries = amountPaymentEntries(toSafeInteger(value), entries);
|
||||
setFieldValue('entries', newEntries);
|
||||
};
|
||||
// Handle click open payment receive number dialog.
|
||||
const handleClickOpenDialog = () => {
|
||||
openDialog('payment-receive-number-form');
|
||||
};
|
||||
|
||||
// Handle payment number field blur.
|
||||
const handlePaymentNoBlur = (form, field) => (event) => {
|
||||
const newValue = event.target.value;
|
||||
|
||||
if (field.value !== newValue && paymentReceiveAutoIncrement) {
|
||||
openDialog('payment-receive-number-form', {
|
||||
initialFormValues: {
|
||||
manualTransactionNo: newValue,
|
||||
incrementMode: 'manual-transaction',
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Syncs payment receive number from settings to the form.
|
||||
useObservePaymentNoSettings(
|
||||
paymentReceiveNumberPrefix,
|
||||
paymentReceiveNextNumber,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
|
||||
{/* ------------- Customer name ------------- */}
|
||||
<FastField
|
||||
name={'customer_id'}
|
||||
customers={customers}
|
||||
shouldUpdate={customersFieldShouldUpdate}
|
||||
>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'customer_name'} />}
|
||||
inline={true}
|
||||
className={classNames('form-group--select-list', CLASSES.FILL)}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name={'customer_id'} />}
|
||||
>
|
||||
<ContactSelecetList
|
||||
contactsList={customers}
|
||||
selectedContactId={value}
|
||||
defaultSelectText={<T id={'select_customer_account'} />}
|
||||
onContactSelected={(customer) => {
|
||||
form.setFieldValue('customer_id', customer.id);
|
||||
form.setFieldValue('full_amount', '');
|
||||
}}
|
||||
popoverFill={true}
|
||||
disabled={!isNewMode}
|
||||
buttonProps={{
|
||||
elementRef: (ref) => (customerFieldRef.current = ref),
|
||||
}}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ------------- Payment date ------------- */}
|
||||
<FastField name={'payment_date'}>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'payment_date'} />}
|
||||
inline={true}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
className={classNames('form-group--select-list', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="payment_date" />}
|
||||
>
|
||||
<DateInput
|
||||
{...momentFormatter('YYYY/MM/DD')}
|
||||
value={tansformDateValue(value)}
|
||||
onChange={handleDateChange((formattedDate) => {
|
||||
form.setFieldValue('payment_date', formattedDate);
|
||||
})}
|
||||
popoverProps={{ position: Position.BOTTOM, minimal: true }}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ------------ Full amount ------------ */}
|
||||
<Field name={'full_amount'}>
|
||||
{({
|
||||
form: { setFieldValue },
|
||||
field: { value, onChange },
|
||||
meta: { error, touched },
|
||||
}) => (
|
||||
<FormGroup
|
||||
label={<T id={'full_amount'} />}
|
||||
inline={true}
|
||||
className={('form-group--full-amount', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
labelInfo={<Hint />}
|
||||
helperText={<ErrorMessage name="full_amount" />}
|
||||
>
|
||||
<ControlGroup>
|
||||
<InputPrependText text={base_currency} />
|
||||
<MoneyInputGroup
|
||||
value={value}
|
||||
onChange={(value) => {
|
||||
setFieldValue('full_amount', value);
|
||||
}}
|
||||
onBlurValue={onFullAmountBlur}
|
||||
/>
|
||||
</ControlGroup>
|
||||
|
||||
<Button
|
||||
onClick={handleReceiveFullAmountClick}
|
||||
className={'receive-full-amount'}
|
||||
small={true}
|
||||
minimal={true}
|
||||
>
|
||||
<T id={'receive_full_amount'} /> (
|
||||
<Money amount={totalDueAmount} currency={base_currency} />)
|
||||
</Button>
|
||||
</FormGroup>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
{/* ------------ Payment receive no. ------------ */}
|
||||
<FastField name={'payment_receive_no'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'payment_receive_no'} />}
|
||||
inline={true}
|
||||
className={('form-group--payment_receive_no', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="payment_receive_no" />}
|
||||
>
|
||||
<ControlGroup fill={true}>
|
||||
<InputGroup
|
||||
intent={inputIntent({ error, touched })}
|
||||
minimal={true}
|
||||
value={field.value}
|
||||
asyncControl={true}
|
||||
onBlur={handlePaymentNoBlur(form, field)}
|
||||
/>
|
||||
<InputPrependButton
|
||||
buttonProps={{
|
||||
onClick: handleClickOpenDialog,
|
||||
icon: <Icon icon={'settings-18'} />,
|
||||
}}
|
||||
tooltip={true}
|
||||
tooltipProps={{
|
||||
content: (
|
||||
<T
|
||||
id={'setting_your_auto_generated_payment_receive_number'}
|
||||
/>
|
||||
),
|
||||
position: Position.BOTTOM_LEFT,
|
||||
}}
|
||||
/>
|
||||
</ControlGroup>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ------------ Deposit account ------------ */}
|
||||
<FastField
|
||||
name={'deposit_account_id'}
|
||||
accounts={accounts}
|
||||
shouldUpdate={accountsFieldShouldUpdate}
|
||||
>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'deposit_to'} />}
|
||||
className={classNames(
|
||||
'form-group--deposit_account_id',
|
||||
'form-group--select-list',
|
||||
CLASSES.FILL,
|
||||
)}
|
||||
inline={true}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name={'deposit_account_id'} />}
|
||||
>
|
||||
<AccountsSelectList
|
||||
accounts={accounts}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
onAccountSelected={(account) => {
|
||||
form.setFieldValue('deposit_account_id', account.id);
|
||||
}}
|
||||
defaultSelectText={<T id={'select_deposit_account'} />}
|
||||
selectedAccountId={value}
|
||||
filterByTypes={[
|
||||
ACCOUNT_TYPE.CASH,
|
||||
ACCOUNT_TYPE.BANK,
|
||||
ACCOUNT_TYPE.OTHER_CURRENT_ASSET,
|
||||
]}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ------------ Reference No. ------------ */}
|
||||
<FastField name={'reference_no'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'reference'} />}
|
||||
inline={true}
|
||||
className={classNames('form-group--reference', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="reference" />}
|
||||
>
|
||||
<InputGroup
|
||||
intent={inputIntent({ error, touched })}
|
||||
minimal={true}
|
||||
{...field}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withSettings(({ paymentReceiveSettings }) => ({
|
||||
paymentReceiveNextNumber: paymentReceiveSettings?.nextNumber,
|
||||
paymentReceiveNumberPrefix: paymentReceiveSettings?.numberPrefix,
|
||||
paymentReceiveAutoIncrement: paymentReceiveSettings?.autoIncrement,
|
||||
})),
|
||||
withDialogActions,
|
||||
withCurrentOrganization(),
|
||||
)(PaymentReceiveHeaderFields);
|
||||
@@ -0,0 +1,50 @@
|
||||
import React, { createContext, useContext, useEffect } from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { useDueInvoices } from 'hooks/query';
|
||||
import { transformInvoicesNewPageEntries } from './utils';
|
||||
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
|
||||
import { isEmpty } from 'lodash';
|
||||
|
||||
const PaymentReceiveInnerContext = createContext();
|
||||
|
||||
/**
|
||||
* Payment receive inner form provider.
|
||||
*/
|
||||
function PaymentReceiveInnerProvider({ ...props }) {
|
||||
const { isNewMode } = usePaymentReceiveFormContext();
|
||||
|
||||
// Formik context.
|
||||
const {
|
||||
values: { customer_id: customerId },
|
||||
setFieldValue,
|
||||
} = useFormikContext();
|
||||
|
||||
// Fetches customer receivable invoices.
|
||||
const {
|
||||
data: dueInvoices,
|
||||
isLoading: isDueInvoicesLoading,
|
||||
isFetching: isDueInvoicesFetching,
|
||||
} = useDueInvoices(customerId, {
|
||||
enabled: !!customerId && isNewMode,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDueInvoicesFetching && dueInvoices && isNewMode) {
|
||||
setFieldValue('entries', transformInvoicesNewPageEntries(dueInvoices));
|
||||
}
|
||||
}, [isDueInvoicesFetching, dueInvoices, isNewMode, setFieldValue]);
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
dueInvoices,
|
||||
isDueInvoicesLoading,
|
||||
isDueInvoicesFetching,
|
||||
};
|
||||
|
||||
return <PaymentReceiveInnerContext.Provider value={provider} {...props} />;
|
||||
}
|
||||
|
||||
const usePaymentReceiveInnerContext = () =>
|
||||
useContext(PaymentReceiveInnerContext);
|
||||
|
||||
export { PaymentReceiveInnerProvider, usePaymentReceiveInnerContext };
|
||||
@@ -0,0 +1,69 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { CloudLoadingIndicator } from 'components';
|
||||
import classNames from 'classnames';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { usePaymentReceiveInnerContext } from './PaymentReceiveInnerProvider';
|
||||
import { DataTableEditable } from 'components';
|
||||
import { usePaymentReceiveEntriesColumns } from './components';
|
||||
import { compose, updateTableCell } from 'utils';
|
||||
|
||||
/**
|
||||
* Payment receive items table.
|
||||
*/
|
||||
export default function PaymentReceiveItemsTable({
|
||||
entries,
|
||||
onUpdateData,
|
||||
currencyCode,
|
||||
}) {
|
||||
// Payment receive form context.
|
||||
const { isDueInvoicesFetching } = usePaymentReceiveInnerContext();
|
||||
|
||||
// Payment receive entries form context.
|
||||
const columns = usePaymentReceiveEntriesColumns();
|
||||
|
||||
// Formik context.
|
||||
const {
|
||||
values: { customer_id },
|
||||
} = useFormikContext();
|
||||
|
||||
// No results message.
|
||||
const noResultsMessage = customer_id ? (
|
||||
<T id={'there_is_no_receivable_invoices_for_this_customer'} />
|
||||
) : (
|
||||
<T id={'please_select_a_customer_to_display_all_open_invoices_for_it'} />
|
||||
);
|
||||
|
||||
// Handle update data.
|
||||
const handleUpdateData = useCallback(
|
||||
(rowIndex, columnId, value) => {
|
||||
const newRows = compose(updateTableCell(rowIndex, columnId, value))(
|
||||
entries,
|
||||
);
|
||||
|
||||
onUpdateData(newRows);
|
||||
},
|
||||
[entries, onUpdateData],
|
||||
);
|
||||
|
||||
return (
|
||||
<CloudLoadingIndicator isLoading={isDueInvoicesFetching}>
|
||||
<DataTableEditable
|
||||
progressBarLoading={isDueInvoicesFetching}
|
||||
className={classNames(CLASSES.DATATABLE_EDITOR_ITEMS_ENTRIES)}
|
||||
columns={columns}
|
||||
data={entries}
|
||||
spinnerProps={false}
|
||||
payload={{
|
||||
errors: [],
|
||||
updateData: handleUpdateData,
|
||||
currencyCode,
|
||||
}}
|
||||
noResults={noResultsMessage}
|
||||
footer={true}
|
||||
/>
|
||||
</CloudLoadingIndicator>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import React from 'react';
|
||||
import moment from 'moment';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
import { Money } from 'components';
|
||||
import { MoneyFieldCell } from 'components/DataTableCells';
|
||||
import { safeSumBy, formattedAmount } from 'utils';
|
||||
|
||||
/**
|
||||
* Invoice date cell.
|
||||
*/
|
||||
function InvoiceDateCell({ value }) {
|
||||
return <span>{moment(value).format('YYYY MMM DD')}</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index table cell.
|
||||
*/
|
||||
function IndexCell({ row: { index } }) {
|
||||
return <span>{index + 1}</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoice number table cell accessor.
|
||||
*/
|
||||
function InvNumberCellAccessor(row) {
|
||||
return row?.invoice_no ? `#${row?.invoice_no || ''}` : '-';
|
||||
}
|
||||
|
||||
/**
|
||||
* Balance footer cell.
|
||||
*/
|
||||
function BalanceFooterCell({ payload: { currencyCode }, rows }) {
|
||||
const total = safeSumBy(rows, 'original.amount');
|
||||
return <span>{formattedAmount(total, currencyCode)}</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Due amount footer cell.
|
||||
*/
|
||||
function DueAmountFooterCell({ payload: { currencyCode }, rows }) {
|
||||
const totalDueAmount = safeSumBy(rows, 'original.due_amount');
|
||||
return <span>{formattedAmount(totalDueAmount, currencyCode)}</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Payment amount footer cell.
|
||||
*/
|
||||
function PaymentAmountFooterCell({ payload: { currencyCode }, rows }) {
|
||||
const totalPaymentAmount = safeSumBy(rows, 'original.payment_amount');
|
||||
return <span>{formattedAmount(totalPaymentAmount, currencyCode)}</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mobey table cell.
|
||||
*/
|
||||
function MoneyTableCell({ row: { original }, value }) {
|
||||
return <Money amount={value} currency={original.currency_code} />;
|
||||
}
|
||||
|
||||
function DateFooterCell() {
|
||||
return intl.get('total')
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve payment receive form entries columns.
|
||||
*/
|
||||
export const usePaymentReceiveEntriesColumns = () => {
|
||||
|
||||
|
||||
return React.useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: '#',
|
||||
accessor: 'index',
|
||||
Cell: IndexCell,
|
||||
width: 40,
|
||||
disableResizing: true,
|
||||
disableSortBy: true,
|
||||
className: 'index',
|
||||
},
|
||||
{
|
||||
Header: intl.get('Date'),
|
||||
id: 'invoice_date',
|
||||
accessor: 'invoice_date',
|
||||
Cell: InvoiceDateCell,
|
||||
Footer: DateFooterCell,
|
||||
disableSortBy: true,
|
||||
disableResizing: true,
|
||||
width: 250,
|
||||
className: 'date',
|
||||
},
|
||||
{
|
||||
Header: intl.get('invocie_number'),
|
||||
accessor: InvNumberCellAccessor,
|
||||
disableSortBy: true,
|
||||
className: 'invoice_number',
|
||||
},
|
||||
{
|
||||
Header: intl.get('invoice_amount'),
|
||||
accessor: 'amount',
|
||||
Footer: BalanceFooterCell,
|
||||
Cell: MoneyTableCell,
|
||||
disableSortBy: true,
|
||||
width: 100,
|
||||
className: 'invoice_amount',
|
||||
},
|
||||
{
|
||||
Header: intl.get('amount_due'),
|
||||
accessor: 'due_amount',
|
||||
Footer: DueAmountFooterCell,
|
||||
Cell: MoneyTableCell,
|
||||
disableSortBy: true,
|
||||
width: 150,
|
||||
className: 'amount_due',
|
||||
},
|
||||
{
|
||||
Header: intl.get('payment_amount'),
|
||||
accessor: 'payment_amount',
|
||||
Cell: MoneyFieldCell,
|
||||
Footer: PaymentAmountFooterCell,
|
||||
disableSortBy: true,
|
||||
width: 150,
|
||||
className: 'payment_amount',
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
};
|
||||
126
src/containers/Sales/PaymentReceives/PaymentReceiveForm/utils.js
Normal file
126
src/containers/Sales/PaymentReceives/PaymentReceiveForm/utils.js
Normal file
@@ -0,0 +1,126 @@
|
||||
import React from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import moment from 'moment';
|
||||
import {
|
||||
defaultFastFieldShouldUpdate,
|
||||
transactionNumber,
|
||||
transformToForm,
|
||||
safeSumBy,
|
||||
} from 'utils';
|
||||
|
||||
// Default payment receive entry.
|
||||
export const defaultPaymentReceiveEntry = {
|
||||
payment_amount: '',
|
||||
invoice_id: '',
|
||||
invoice_no: '',
|
||||
due_amount: '',
|
||||
date: '',
|
||||
amount: '',
|
||||
currency_code: '',
|
||||
};
|
||||
|
||||
// Form initial values.
|
||||
export const defaultPaymentReceive = {
|
||||
customer_id: '',
|
||||
deposit_account_id: '',
|
||||
payment_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
reference_no: '',
|
||||
payment_receive_no: '',
|
||||
statement: '',
|
||||
full_amount: '',
|
||||
currency_code: '',
|
||||
entries: [],
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
export const transformToEditForm = (paymentReceive, paymentReceiveEntries) => ({
|
||||
...transformToForm(paymentReceive, defaultPaymentReceive),
|
||||
full_amount: safeSumBy(paymentReceiveEntries, 'payment_amount'),
|
||||
entries: [
|
||||
...paymentReceiveEntries.map((paymentReceiveEntry) => ({
|
||||
...transformToForm(paymentReceiveEntry, defaultPaymentReceiveEntry),
|
||||
payment_amount: paymentReceiveEntry.payment_amount || '',
|
||||
})),
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* Transformes the given invoices to the new page receivable entries.
|
||||
*/
|
||||
export const transformInvoicesNewPageEntries = (invoices) => [
|
||||
...invoices.map((invoice, index) => ({
|
||||
index: index + 1,
|
||||
invoice_id: invoice.id,
|
||||
entry_type: 'invoice',
|
||||
due_amount: invoice.due_amount,
|
||||
date: invoice.invoice_date,
|
||||
amount: invoice.balance,
|
||||
currency_code: invoice.currency_code,
|
||||
payment_amount: '',
|
||||
invoice_no: invoice.invoice_no,
|
||||
total_payment_amount: invoice.payment_amount,
|
||||
})),
|
||||
];
|
||||
|
||||
export const transformEntriesToEditForm = (receivableEntries) => [
|
||||
...transformInvoicesNewPageEntries([...(receivableEntries || [])]),
|
||||
];
|
||||
|
||||
export const clearAllPaymentEntries = (entries) => [
|
||||
...entries.map((entry) => ({ ...entry, payment_amount: 0 })),
|
||||
];
|
||||
|
||||
export const amountPaymentEntries = (amount, entries) => {
|
||||
let total = amount;
|
||||
|
||||
return entries.map((item) => {
|
||||
const diff = Math.min(item.due_amount, total);
|
||||
total -= Math.max(diff, 0);
|
||||
|
||||
return {
|
||||
...item,
|
||||
payment_amount: diff,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
export const fullAmountPaymentEntries = (entries) => {
|
||||
return entries.map((item) => ({
|
||||
...item,
|
||||
payment_amount: item.due_amount,
|
||||
}));
|
||||
};
|
||||
|
||||
/**
|
||||
* Syncs payment receive number settings with form.
|
||||
*/
|
||||
export const useObservePaymentNoSettings = (prefix, nextNumber) => {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
|
||||
React.useEffect(() => {
|
||||
const invoiceNo = transactionNumber(prefix, nextNumber);
|
||||
setFieldValue('payment_receive_no', invoiceNo);
|
||||
}, [setFieldValue, prefix, nextNumber]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines the customers fast-field should update.
|
||||
*/
|
||||
export const customersFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.customers !== oldProps.customers ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines the accounts fast-field should update.
|
||||
*/
|
||||
export const accountsFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.accounts !== oldProps.accounts ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,79 @@
|
||||
import React from 'react';
|
||||
import { MenuItem } from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
import { RESOURCES_TYPES } from "../../../common/resourcesTypes";
|
||||
import withDrawerActions from "../../Drawer/withDrawerActions";
|
||||
import { highlightText } from 'utils';
|
||||
import { Icon } from 'components';
|
||||
|
||||
/**
|
||||
* Payment receive universal search item select action.
|
||||
*/
|
||||
function PaymentReceiveUniversalSearchSelectComponent({
|
||||
// #ownProps
|
||||
resourceType,
|
||||
resourceId,
|
||||
|
||||
// #withDrawerActions
|
||||
openDrawer,
|
||||
}) {
|
||||
if (resourceType === RESOURCES_TYPES.PAYMENT_RECEIVE) {
|
||||
openDrawer('payment-receive-detail-drawer', { paymentReceiveId: resourceId });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const PaymentReceiveUniversalSearchSelect = withDrawerActions(
|
||||
PaymentReceiveUniversalSearchSelectComponent,
|
||||
);
|
||||
|
||||
/**
|
||||
* Payment receive universal search item.
|
||||
*/
|
||||
export function PaymentReceiveUniversalSearchItem(
|
||||
item,
|
||||
{ handleClick, modifiers, query },
|
||||
) {
|
||||
return (
|
||||
<MenuItem
|
||||
active={modifiers.active}
|
||||
text={
|
||||
<div>
|
||||
<div>{highlightText(item.text, query)}</div>
|
||||
|
||||
<span class="bp3-text-muted">
|
||||
{highlightText(item.reference.payment_receive_no, query)}{' '}
|
||||
<Icon icon={'caret-right-16'} iconSize={16} />
|
||||
{highlightText(item.reference.formatted_payment_date, query)}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
label={<div class="amount">{item.reference.formatted_amount}</div>}
|
||||
onClick={handleClick}
|
||||
className={'universal-search__item--invoice'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformes payment receives to search.
|
||||
*/
|
||||
const paymentReceivesToSearch = (payment) => ({
|
||||
id: payment.id,
|
||||
text: payment.customer.display_name,
|
||||
subText: payment.formatted_payment_date,
|
||||
label: payment.formatted_amount,
|
||||
reference: payment,
|
||||
});
|
||||
|
||||
/**
|
||||
* Binds universal search payment receive configure.
|
||||
*/
|
||||
export const universalSearchPaymentReceiveBind = () => ({
|
||||
resourceType: RESOURCES_TYPES.PAYMENT_RECEIVE,
|
||||
optionItemLabel: intl.get('payment_receives'),
|
||||
selectItemAction: PaymentReceiveUniversalSearchSelect,
|
||||
itemRenderer: PaymentReceiveUniversalSearchItem,
|
||||
itemSelect: paymentReceivesToSearch,
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import DashboardInsider from 'components/Dashboard/DashboardInsider';
|
||||
import {
|
||||
useResourceViews,
|
||||
useResourceMeta,
|
||||
usePaymentReceives,
|
||||
} from 'hooks/query';
|
||||
import { isTableEmptyStatus, getFieldsFromResourceMeta } from 'utils';
|
||||
|
||||
const PaymentReceivesListContext = createContext();
|
||||
|
||||
/**
|
||||
* Payment receives list data provider.
|
||||
*/
|
||||
function PaymentReceivesListProvider({ query, ...props }) {
|
||||
// Fetch payment receives resource views and fields.
|
||||
const {
|
||||
data: paymentReceivesViews,
|
||||
isFetching: isViewsLoading,
|
||||
} = useResourceViews('payment_receives');
|
||||
|
||||
// Fetch the payment receives resource fields.
|
||||
const {
|
||||
data: resourceMeta,
|
||||
isLoading: isResourceLoading,
|
||||
isFetching: isResourceFetching,
|
||||
} = useResourceMeta('payment_receives');
|
||||
|
||||
// Fetch payment receives list according to the given custom view id.
|
||||
const {
|
||||
data: { paymentReceives, pagination, filterMeta },
|
||||
isLoading: isPaymentReceivesLoading,
|
||||
isFetching: isPaymentReceivesFetching,
|
||||
} = usePaymentReceives(query);
|
||||
|
||||
// Detarmines the datatable empty status.
|
||||
const isEmptyStatus =
|
||||
isTableEmptyStatus({
|
||||
data: paymentReceives,
|
||||
pagination,
|
||||
filterMeta,
|
||||
}) && !isPaymentReceivesLoading;
|
||||
|
||||
// Provider payload.
|
||||
const state = {
|
||||
paymentReceives,
|
||||
pagination,
|
||||
|
||||
resourceMeta,
|
||||
fields: getFieldsFromResourceMeta(resourceMeta.fields),
|
||||
|
||||
paymentReceivesViews,
|
||||
|
||||
isPaymentReceivesLoading,
|
||||
isPaymentReceivesFetching,
|
||||
isResourceFetching,
|
||||
isResourceLoading,
|
||||
isViewsLoading,
|
||||
isEmptyStatus,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={isViewsLoading || isResourceLoading}
|
||||
name={'payment-receives-list'}
|
||||
>
|
||||
<PaymentReceivesListContext.Provider value={state} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const usePaymentReceivesListContext = () =>
|
||||
useContext(PaymentReceivesListContext);
|
||||
|
||||
export { PaymentReceivesListProvider, usePaymentReceivesListContext };
|
||||
@@ -0,0 +1,136 @@
|
||||
import React from 'react';
|
||||
import Icon from 'components/Icon';
|
||||
import {
|
||||
Button,
|
||||
Classes,
|
||||
NavbarDivider,
|
||||
NavbarGroup,
|
||||
Intent,
|
||||
Alignment,
|
||||
} from '@blueprintjs/core';
|
||||
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import {
|
||||
DashboardFilterButton,
|
||||
AdvancedFilterPopover,
|
||||
FormattedMessage as T,
|
||||
} from 'components';
|
||||
|
||||
import DashboardActionsBar from 'components/Dashboard/DashboardActionsBar';
|
||||
|
||||
import { If, DashboardActionViewsList } from 'components';
|
||||
|
||||
import withPaymentReceivesActions from './withPaymentReceivesActions';
|
||||
import withPaymentReceives from './withPaymentReceives';
|
||||
|
||||
import { compose } from 'utils';
|
||||
import { usePaymentReceivesListContext } from './PaymentReceiptsListProvider';
|
||||
import { useRefreshPaymentReceive } from 'hooks/query/paymentReceives';
|
||||
|
||||
/**
|
||||
* Payment receives actions bar.
|
||||
*/
|
||||
function PaymentReceiveActionsBar({
|
||||
// #withPaymentReceivesActions
|
||||
setPaymentReceivesTableState,
|
||||
|
||||
// #withPaymentReceives
|
||||
paymentFilterConditions
|
||||
}) {
|
||||
// History context.
|
||||
const history = useHistory();
|
||||
|
||||
// Payment receives list context.
|
||||
const { paymentReceivesViews, fields } = usePaymentReceivesListContext();
|
||||
|
||||
// Handle new payment button click.
|
||||
const handleClickNewPaymentReceive = () => {
|
||||
history.push('/payment-receives/new');
|
||||
};
|
||||
|
||||
// Payment receive refresh action.
|
||||
const { refresh } = useRefreshPaymentReceive();
|
||||
|
||||
// Handle tab changing.
|
||||
const handleTabChange = (viewId) => {
|
||||
setPaymentReceivesTableState({ customViewId: viewId.id || null });
|
||||
};
|
||||
|
||||
// Handle click a refresh payment receives
|
||||
const handleRefreshBtnClick = () => {
|
||||
refresh();
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardActionsBar>
|
||||
<NavbarGroup>
|
||||
<DashboardActionViewsList
|
||||
resourceName={'payment_receives'}
|
||||
views={paymentReceivesViews}
|
||||
onChange={handleTabChange}
|
||||
/>
|
||||
<NavbarDivider />
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'plus'} />}
|
||||
text={<T id={'new_payment_receive'} />}
|
||||
onClick={handleClickNewPaymentReceive}
|
||||
/>
|
||||
<AdvancedFilterPopover
|
||||
advancedFilterProps={{
|
||||
conditions: paymentFilterConditions,
|
||||
defaultFieldKey: 'payment_receive_no',
|
||||
fields: fields,
|
||||
onFilterChange: (filterConditions) => {
|
||||
setPaymentReceivesTableState({ filterRoles: filterConditions });
|
||||
},
|
||||
}}
|
||||
>
|
||||
<DashboardFilterButton
|
||||
conditionsCount={paymentFilterConditions.length}
|
||||
/>
|
||||
</AdvancedFilterPopover>
|
||||
|
||||
<If condition={false}>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'trash-16'} iconSize={16} />}
|
||||
text={<T id={'delete'} />}
|
||||
intent={Intent.DANGER}
|
||||
// onClick={handleBulkDelete}
|
||||
/>
|
||||
</If>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'print-16'} iconSize={'16'} />}
|
||||
text={<T id={'print'} />}
|
||||
/>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'file-import-16'} />}
|
||||
text={<T id={'import'} />}
|
||||
/>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'file-export-16'} iconSize={'16'} />}
|
||||
text={<T id={'export'} />}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
<NavbarGroup align={Alignment.RIGHT}>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon="refresh-16" iconSize={14} />}
|
||||
onClick={handleRefreshBtnClick}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
</DashboardActionsBar>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withPaymentReceivesActions,
|
||||
withPaymentReceives(({ paymentReceivesTableState }) => ({
|
||||
paymentReceivesTableState,
|
||||
paymentFilterConditions: paymentReceivesTableState.filterRoles,
|
||||
})),
|
||||
)(PaymentReceiveActionsBar);
|
||||
@@ -0,0 +1,64 @@
|
||||
import React from 'react';
|
||||
import { useHistory } from 'react-router';
|
||||
import { Alignment, Navbar, NavbarGroup } from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { pick } from 'lodash';
|
||||
|
||||
import { DashboardViewsTabs } from 'components';
|
||||
|
||||
import withPaymentReceives from './withPaymentReceives';
|
||||
import withPaymentReceivesActions from './withPaymentReceivesActions';
|
||||
import { usePaymentReceivesListContext } from './PaymentReceiptsListProvider';
|
||||
|
||||
import { compose } from 'utils';
|
||||
|
||||
/**
|
||||
* Payment receive view tabs.
|
||||
*/
|
||||
function PaymentReceiveViewTabs({
|
||||
// #withPaymentReceivesActions
|
||||
addPaymentReceivesTableQueries,
|
||||
|
||||
// #withPaymentReceives
|
||||
paymentReceivesTableState,
|
||||
}) {
|
||||
const history = useHistory();
|
||||
const { paymentReceivesViews, ...res } = usePaymentReceivesListContext();
|
||||
|
||||
const tabs = paymentReceivesViews.map((view) => ({
|
||||
...pick(view, ['name', 'id']),
|
||||
}));
|
||||
|
||||
// Handles click a new view tab.
|
||||
const handleClickNewView = () => {
|
||||
history.push('/custom_views/payment-receives/new');
|
||||
};
|
||||
|
||||
// Handles the active tab chaing.
|
||||
const handleTabsChange = (customView) => {
|
||||
addPaymentReceivesTableQueries({
|
||||
customViewId: customView || null,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Navbar className={'navbar--dashboard-views'}>
|
||||
<NavbarGroup align={Alignment.LEFT}>
|
||||
<DashboardViewsTabs
|
||||
customViewId={paymentReceivesTableState.customViewId}
|
||||
tabs={tabs}
|
||||
defaultTabText={<T id={'all_payments'} />}
|
||||
onNewViewTabClick={handleClickNewView}
|
||||
onChange={handleTabsChange}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
</Navbar>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withPaymentReceivesActions,
|
||||
withPaymentReceives(({ paymentReceivesTableState }) => ({
|
||||
paymentReceivesTableState,
|
||||
})),
|
||||
)(PaymentReceiveViewTabs);
|
||||
@@ -0,0 +1,37 @@
|
||||
import React from 'react';
|
||||
import { Button, Intent } from '@blueprintjs/core';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { EmptyStatus } from 'components';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
|
||||
export default function PaymentReceivesEmptyStatus() {
|
||||
const history = useHistory();
|
||||
|
||||
return (
|
||||
<EmptyStatus
|
||||
title={<T id={'the_organization_doesn_t_receive_money_yet'} />}
|
||||
description={
|
||||
<p>
|
||||
<T id={'receiving_customer_payments_is_one_pleasant_accounting_tasks'} />
|
||||
</p>
|
||||
}
|
||||
action={
|
||||
<>
|
||||
<Button
|
||||
intent={Intent.PRIMARY}
|
||||
large={true}
|
||||
onClick={() => {
|
||||
history.push('/payment-receives/new');
|
||||
}}
|
||||
>
|
||||
<T id={'new_payment_receive'} />
|
||||
</Button>
|
||||
|
||||
<Button intent={Intent.NONE} large={true}>
|
||||
<T id={'learn_more'} />
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import React from 'react';
|
||||
|
||||
import 'style/pages/PaymentReceive/List.scss';
|
||||
|
||||
import { DashboardContentTable, DashboardPageContent } from 'components';
|
||||
import PaymentReceiveActionsBar from './PaymentReceiveActionsBar';
|
||||
import PaymentReceiveAlerts from '../PaymentReceiveAlerts';
|
||||
import { PaymentReceivesListProvider } from './PaymentReceiptsListProvider';
|
||||
import PaymentReceiveViewTabs from './PaymentReceiveViewTabs';
|
||||
import PaymentReceivesTable from './PaymentReceivesTable';
|
||||
|
||||
import withPaymentReceives from './withPaymentReceives';
|
||||
import withPaymentReceivesActions from './withPaymentReceivesActions';
|
||||
|
||||
import { compose, transformTableStateToQuery } from 'utils';
|
||||
|
||||
/**
|
||||
* Payment receives list.
|
||||
*/
|
||||
function PaymentReceiveList({
|
||||
// #withPaymentReceives
|
||||
paymentReceivesTableState,
|
||||
paymentsTableStateChanged,
|
||||
|
||||
// #withPaymentReceivesActions
|
||||
resetPaymentReceivesTableState,
|
||||
}) {
|
||||
// Resets the payment receives table state once the page unmount.
|
||||
React.useEffect(
|
||||
() => () => {
|
||||
resetPaymentReceivesTableState();
|
||||
},
|
||||
[resetPaymentReceivesTableState],
|
||||
);
|
||||
|
||||
return (
|
||||
<PaymentReceivesListProvider
|
||||
query={transformTableStateToQuery(paymentReceivesTableState)}
|
||||
tableStateChanged={paymentsTableStateChanged}
|
||||
>
|
||||
<PaymentReceiveActionsBar />
|
||||
|
||||
<DashboardPageContent>
|
||||
<PaymentReceiveViewTabs />
|
||||
<PaymentReceivesTable />
|
||||
</DashboardPageContent>
|
||||
|
||||
<PaymentReceiveAlerts />
|
||||
</PaymentReceivesListProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withPaymentReceives(
|
||||
({ paymentReceivesTableState, paymentsTableStateChanged }) => ({
|
||||
paymentReceivesTableState,
|
||||
paymentsTableStateChanged,
|
||||
}),
|
||||
),
|
||||
withPaymentReceivesActions,
|
||||
)(PaymentReceiveList);
|
||||
@@ -0,0 +1,72 @@
|
||||
import React, { createContext } from 'react';
|
||||
import { isEmpty } from 'lodash';
|
||||
|
||||
import DashboardInsider from 'components/Dashboard/DashboardInsider';
|
||||
import {
|
||||
useResourceViews,
|
||||
useResourceMeta,
|
||||
usePaymentReceives,
|
||||
} from 'hooks/query';
|
||||
import { getFieldsFromResourceMeta } from 'utils';
|
||||
|
||||
const PaymentReceivesListContext = createContext();
|
||||
|
||||
/**
|
||||
* Payment receives data provider.
|
||||
*/
|
||||
function PaymentReceivesListProvider({ query, tableStateChanged, ...props }) {
|
||||
// Fetch accounts resource views and fields.
|
||||
const {
|
||||
data: paymentReceivesViews,
|
||||
isFetching: isViewsLoading,
|
||||
} = useResourceViews('payment_receives');
|
||||
|
||||
// Fetch the accounts resource fields.
|
||||
const {
|
||||
data: resourceMeta,
|
||||
isFetching: isResourceFetching,
|
||||
isLoading: isResourceLoading,
|
||||
} = useResourceMeta('payment_receives');
|
||||
|
||||
// Fetch accounts list according to the given custom view id.
|
||||
const {
|
||||
data: { paymentReceives, pagination, filterMeta },
|
||||
isLoading: isPaymentReceivesLoading,
|
||||
isFetching: isPaymentReceivesFetching,
|
||||
} = usePaymentReceives(query, { keepPreviousData: true });
|
||||
|
||||
// Detarmines the datatable empty status.
|
||||
const isEmptyStatus =
|
||||
!isPaymentReceivesLoading && !tableStateChanged && isEmpty(paymentReceives);
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
paymentReceives,
|
||||
paymentReceivesViews,
|
||||
pagination,
|
||||
resourceMeta,
|
||||
|
||||
fields: getFieldsFromResourceMeta(resourceMeta.fields),
|
||||
|
||||
isEmptyStatus,
|
||||
isViewsLoading,
|
||||
isResourceFetching,
|
||||
isResourceLoading,
|
||||
isPaymentReceivesLoading,
|
||||
isPaymentReceivesFetching
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={isViewsLoading || isResourceLoading}
|
||||
name={'payment_receives'}
|
||||
>
|
||||
<PaymentReceivesListContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const usePaymentReceivesListContext = () =>
|
||||
React.useContext(PaymentReceivesListContext);
|
||||
|
||||
export { PaymentReceivesListProvider, usePaymentReceivesListContext };
|
||||
@@ -0,0 +1,141 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
import { compose } from 'utils';
|
||||
import { TABLES } from 'common/tables';
|
||||
|
||||
import { DataTable, DashboardContentTable } from 'components';
|
||||
import PaymentReceivesEmptyStatus from './PaymentReceivesEmptyStatus';
|
||||
import TableSkeletonRows from 'components/Datatable/TableSkeletonRows';
|
||||
import TableSkeletonHeader from 'components/Datatable/TableHeaderSkeleton';
|
||||
|
||||
import withPaymentReceives from './withPaymentReceives';
|
||||
import withPaymentReceivesActions from './withPaymentReceivesActions';
|
||||
import withAlertsActions from 'containers/Alert/withAlertActions';
|
||||
import withDrawerActions from 'containers/Drawer/withDrawerActions';
|
||||
|
||||
import { usePaymentReceivesColumns, ActionsMenu } from './components';
|
||||
import { usePaymentReceivesListContext } from './PaymentReceiptsListProvider';
|
||||
import { useMemorizedColumnsWidths } from 'hooks';
|
||||
|
||||
/**
|
||||
* Payment receives datatable.
|
||||
*/
|
||||
function PaymentReceivesDataTable({
|
||||
// #withPaymentReceivesActions
|
||||
setPaymentReceivesTableState,
|
||||
|
||||
// #withPaymentReceives
|
||||
paymentReceivesTableState,
|
||||
|
||||
// #withAlertsActions
|
||||
openAlert,
|
||||
|
||||
// #withDrawerActions
|
||||
openDrawer,
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Payment receives list context.
|
||||
const {
|
||||
paymentReceives,
|
||||
pagination,
|
||||
|
||||
isPaymentReceivesLoading,
|
||||
isPaymentReceivesFetching,
|
||||
isEmptyStatus,
|
||||
} = usePaymentReceivesListContext();
|
||||
|
||||
// Payment receives columns.
|
||||
const columns = usePaymentReceivesColumns();
|
||||
|
||||
// Handles edit payment receive.
|
||||
const handleEditPaymentReceive = ({ id }) => {
|
||||
history.push(`/payment-receives/${id}/edit`);
|
||||
};
|
||||
|
||||
// Handles delete payment receive.
|
||||
const handleDeletePaymentReceive = ({ id }) => {
|
||||
openAlert('payment-receive-delete', { paymentReceiveId: id });
|
||||
};
|
||||
|
||||
// Handle drawer payment receive.
|
||||
const handleDrawerPaymentReceive = ({ id }) => {
|
||||
openDrawer('payment-receive-drawer', { paymentReceiveId: id });
|
||||
};
|
||||
|
||||
// Handle view detail payment receive..
|
||||
const handleViewDetailPaymentReceive = ({ id }) => {
|
||||
openDrawer('payment-receive-detail-drawer', { paymentReceiveId: id });
|
||||
};
|
||||
|
||||
// Handle cell click.
|
||||
const handleCellClick = (cell, event) => {
|
||||
openDrawer('payment-receive-detail-drawer', {
|
||||
paymentReceiveId: cell.row.original.id,
|
||||
});
|
||||
};
|
||||
|
||||
// Local storage memorizing columns widths.
|
||||
const [initialColumnsWidths, , handleColumnResizing] =
|
||||
useMemorizedColumnsWidths(TABLES.PAYMENT_RECEIVES);
|
||||
|
||||
// Handle datatable fetch once the table's state changing.
|
||||
const handleDataTableFetchData = useCallback(
|
||||
({ pageIndex, pageSize, sortBy }) => {
|
||||
setPaymentReceivesTableState({
|
||||
pageIndex,
|
||||
pageSize,
|
||||
sortBy,
|
||||
});
|
||||
},
|
||||
[setPaymentReceivesTableState],
|
||||
);
|
||||
|
||||
// Display empty status instead of the table.
|
||||
if (isEmptyStatus) {
|
||||
return <PaymentReceivesEmptyStatus />;
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardContentTable>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={paymentReceives}
|
||||
loading={isPaymentReceivesLoading}
|
||||
headerLoading={isPaymentReceivesLoading}
|
||||
progressBarLoading={isPaymentReceivesFetching}
|
||||
onFetchData={handleDataTableFetchData}
|
||||
manualSortBy={true}
|
||||
selectionColumn={true}
|
||||
noInitialFetch={true}
|
||||
sticky={true}
|
||||
autoResetSortBy={false}
|
||||
autoResetPage={false}
|
||||
pagination={true}
|
||||
pagesCount={pagination.pagesCount}
|
||||
TableLoadingRenderer={TableSkeletonRows}
|
||||
TableHeaderSkeletonRenderer={TableSkeletonHeader}
|
||||
ContextMenu={ActionsMenu}
|
||||
onCellClick={handleCellClick}
|
||||
initialColumnsWidths={initialColumnsWidths}
|
||||
onColumnResizing={handleColumnResizing}
|
||||
payload={{
|
||||
onDelete: handleDeletePaymentReceive,
|
||||
onEdit: handleEditPaymentReceive,
|
||||
onDrawer: handleDrawerPaymentReceive,
|
||||
onViewDetails: handleViewDetailPaymentReceive,
|
||||
}}
|
||||
/>
|
||||
</DashboardContentTable>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withPaymentReceivesActions,
|
||||
withAlertsActions,
|
||||
withDrawerActions,
|
||||
withPaymentReceives(({ paymentReceivesTableState }) => ({
|
||||
paymentReceivesTableState,
|
||||
})),
|
||||
)(PaymentReceivesDataTable);
|
||||
@@ -0,0 +1,140 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Intent,
|
||||
Button,
|
||||
Popover,
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuDivider,
|
||||
Position,
|
||||
} from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
import clsx from 'classnames';
|
||||
|
||||
import { FormatDateCell, Money, Icon } from 'components';
|
||||
import { safeCallback } from 'utils';
|
||||
import { CLASSES } from '../../../../common/classes';
|
||||
|
||||
/**
|
||||
* Table actions menu.
|
||||
*/
|
||||
export function ActionsMenu({
|
||||
row: { original: paymentReceive },
|
||||
payload: { onEdit, onDelete, onDrawer, onViewDetails },
|
||||
}) {
|
||||
return (
|
||||
<Menu>
|
||||
<MenuItem
|
||||
icon={<Icon icon="reader-18" />}
|
||||
text={intl.get('view_details')}
|
||||
onClick={safeCallback(onViewDetails, paymentReceive)}
|
||||
/>
|
||||
<MenuDivider />
|
||||
<MenuItem
|
||||
icon={<Icon icon="pen-18" />}
|
||||
text={intl.get('edit_payment_receive')}
|
||||
onClick={safeCallback(onEdit, paymentReceive)}
|
||||
/>
|
||||
<MenuItem
|
||||
icon={<Icon icon={'receipt-24'} iconSize={16} />}
|
||||
text={intl.get('payment_receive_paper')}
|
||||
onClick={safeCallback(onDrawer, paymentReceive)}
|
||||
/>
|
||||
<MenuItem
|
||||
text={intl.get('delete_payment_receive')}
|
||||
intent={Intent.DANGER}
|
||||
onClick={safeCallback(onDelete, paymentReceive)}
|
||||
icon={<Icon icon="trash-16" iconSize={16} />}
|
||||
/>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Amount accessor.
|
||||
*/
|
||||
export function AmountAccessor(row) {
|
||||
return <Money amount={row.amount} currency={row.currency_code} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Actions cell.
|
||||
*/
|
||||
export function ActionsCell(props) {
|
||||
return (
|
||||
<Popover
|
||||
content={<ActionsMenu {...props} />}
|
||||
position={Position.RIGHT_BOTTOM}
|
||||
>
|
||||
<Button icon={<Icon icon="more-h-16" iconSize={16} />} />
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve payment receives columns.
|
||||
*/
|
||||
export function usePaymentReceivesColumns() {
|
||||
return React.useMemo(
|
||||
() => [
|
||||
{
|
||||
id: 'payment_date',
|
||||
Header: intl.get('payment_date'),
|
||||
accessor: 'payment_date',
|
||||
Cell: FormatDateCell,
|
||||
width: 140,
|
||||
className: 'payment_date',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'customer',
|
||||
Header: intl.get('customer_name'),
|
||||
accessor: 'customer.display_name',
|
||||
width: 160,
|
||||
className: 'customer_id',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'amount',
|
||||
Header: intl.get('amount'),
|
||||
accessor: AmountAccessor,
|
||||
width: 120,
|
||||
align: 'right',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
className: clsx(CLASSES.FONT_BOLD),
|
||||
},
|
||||
{
|
||||
id: 'payment_receive_no',
|
||||
Header: intl.get('payment_receive_no'),
|
||||
accessor: (row) =>
|
||||
row.payment_receive_no ? `${row.payment_receive_no}` : null,
|
||||
width: 140,
|
||||
className: 'payment_receive_no',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'deposit_account',
|
||||
Header: intl.get('deposit_account'),
|
||||
accessor: 'deposit_account.name',
|
||||
width: 140,
|
||||
className: 'deposit_account_id',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'reference_no',
|
||||
Header: intl.get('reference_no'),
|
||||
accessor: 'reference_no',
|
||||
width: 140,
|
||||
className: 'reference_no',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { connect } from 'react-redux';
|
||||
import {
|
||||
getPaymentReceiveByIdFactory,
|
||||
getPaymentReceiveEntriesFactory,
|
||||
} from 'store/PaymentReceive/paymentReceive.selector';
|
||||
|
||||
export default () => {
|
||||
const getPaymentReceiveById = getPaymentReceiveByIdFactory();
|
||||
const getPaymentReceiveEntries = getPaymentReceiveEntriesFactory();
|
||||
|
||||
const mapStateToProps = (state, props) => ({
|
||||
paymentReceive: getPaymentReceiveById(state, props),
|
||||
paymentReceiveEntries: getPaymentReceiveEntries(state, props),
|
||||
});
|
||||
return connect(mapStateToProps);
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import { connect } from 'react-redux';
|
||||
import {
|
||||
getPaymentReceiveTableStateFactory,
|
||||
paymentsTableStateChangedFactory
|
||||
} from 'store/PaymentReceives/paymentReceives.selector';
|
||||
|
||||
export default (mapState) => {
|
||||
const getPaymentReceiveTableState = getPaymentReceiveTableStateFactory();
|
||||
const paymentsTableStateChanged = paymentsTableStateChangedFactory();
|
||||
|
||||
const mapStateToProps = (state, props) => {
|
||||
const mapped = {
|
||||
paymentReceivesTableState: getPaymentReceiveTableState(state, props),
|
||||
paymentsTableStateChanged: paymentsTableStateChanged(state, props),
|
||||
};
|
||||
return mapState ? mapState(mapped, state, props) : mapped;
|
||||
};
|
||||
return connect(mapStateToProps);
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import { connect } from 'react-redux';
|
||||
import {
|
||||
setPaymentReceivesTableState,
|
||||
resetPaymentReceivesTableState,
|
||||
} from 'store/PaymentReceives/paymentReceives.actions';
|
||||
|
||||
const mapDispatchToProps = (dispatch) => ({
|
||||
setPaymentReceivesTableState: (state) =>
|
||||
dispatch(setPaymentReceivesTableState(state)),
|
||||
|
||||
resetPaymentReceivesTableState: () =>
|
||||
dispatch(resetPaymentReceivesTableState()),
|
||||
});
|
||||
|
||||
export default connect(null, mapDispatchToProps);
|
||||
@@ -0,0 +1,29 @@
|
||||
import React, { lazy } from 'react';
|
||||
import withDrawers from 'containers/Drawer/withDrawers';
|
||||
|
||||
import { Drawer, DrawerSuspense } from 'components';
|
||||
import { compose } from 'utils';
|
||||
|
||||
const ReceiptDrawerContent = lazy(() => import('./ReceiptDrawerContent'));
|
||||
|
||||
/**
|
||||
* receipt drawer.
|
||||
*/
|
||||
const ReceiptDrawer = ({
|
||||
name,
|
||||
//#withDrawer
|
||||
isOpen,
|
||||
payload: { receiptId },
|
||||
}) => {
|
||||
return (
|
||||
<div>
|
||||
<Drawer isOpen={isOpen} name={name}>
|
||||
<DrawerSuspense>
|
||||
<ReceiptDrawerContent receiptId={receiptId} />
|
||||
</DrawerSuspense>
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default compose(withDrawers())(ReceiptDrawer);
|
||||
@@ -0,0 +1,17 @@
|
||||
import React from 'react';
|
||||
import { ReceiptDrawerProvider } from './ReceiptDrawerProvider';
|
||||
import ReceiptPaper from './ReceiptPaper';
|
||||
|
||||
/**
|
||||
* Receipt drawer content.
|
||||
*/
|
||||
export default function ReceiptDrawerContent({
|
||||
// #ownProp
|
||||
receiptId,
|
||||
}) {
|
||||
return (
|
||||
<ReceiptDrawerProvider receiptId={receiptId}>
|
||||
<ReceiptPaper />
|
||||
</ReceiptDrawerProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import { useReceipt } from 'hooks/query';
|
||||
import { DrawerHeaderContent, DashboardInsider } from 'components';
|
||||
|
||||
const ReceiptDrawerContext = createContext();
|
||||
|
||||
function ReceiptDrawerProvider({ receiptId, ...props }) {
|
||||
// Fetch sale receipt details.
|
||||
const {
|
||||
data: { entries, ...receipt },
|
||||
isFetching: isReceiptLoading,
|
||||
} = useReceipt(receiptId, {
|
||||
enabled: !!receiptId,
|
||||
});
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
receiptId,
|
||||
receipt,
|
||||
entries,
|
||||
|
||||
isReceiptLoading,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider loading={isReceiptLoading}>
|
||||
<DrawerHeaderContent name={'receipt-drawer'} />
|
||||
<ReceiptDrawerContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
const useReceiptDrawerContext = () => useContext(ReceiptDrawerContext);
|
||||
|
||||
export { ReceiptDrawerProvider, useReceiptDrawerContext };
|
||||
38
src/containers/Sales/Receipts/ReceiptDetails/ReceiptPaper.js
Normal file
38
src/containers/Sales/Receipts/ReceiptDetails/ReceiptPaper.js
Normal file
@@ -0,0 +1,38 @@
|
||||
import React from 'react';
|
||||
import { useReceiptDrawerContext } from './ReceiptDrawerProvider';
|
||||
import PaperTemplate from 'containers/Drawers/PaperTemplate/PaperTemplate';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
export default function ReceiptPaper() {
|
||||
const { receipt, entries } = useReceiptDrawerContext();
|
||||
|
||||
const propLabels = {
|
||||
labels: {
|
||||
name: intl.get('receipt_'),
|
||||
billedTo: intl.get('billed_to'),
|
||||
date: intl.get('receipt_date_'),
|
||||
refNo: intl.get('receipt_no'),
|
||||
billedFrom: intl.get('billed_from'),
|
||||
amount: intl.get('receipt_amount'),
|
||||
dueDate: intl.get('due_date_'),
|
||||
},
|
||||
};
|
||||
|
||||
const receipts = {
|
||||
billedTo: receipt.customer.display_name,
|
||||
date: receipt.receipt_date,
|
||||
amount: '',
|
||||
billedFrom: '',
|
||||
dueDate: receipt.due_date,
|
||||
referenceNo: receipt.receipt_number,
|
||||
...receipt,
|
||||
};
|
||||
|
||||
return (
|
||||
<PaperTemplate
|
||||
labels={propLabels.labels}
|
||||
paperData={receipts}
|
||||
entries={entries}
|
||||
/>
|
||||
);
|
||||
}
|
||||
196
src/containers/Sales/Receipts/ReceiptForm/ReceiptForm.js
Normal file
196
src/containers/Sales/Receipts/ReceiptForm/ReceiptForm.js
Normal file
@@ -0,0 +1,196 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Formik, Form } from 'formik';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
import { omit, sumBy, isEmpty } from 'lodash';
|
||||
import classNames from 'classnames';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { ERROR } from 'common/errors';
|
||||
import {
|
||||
EditReceiptFormSchema,
|
||||
CreateReceiptFormSchema,
|
||||
} from './ReceiptForm.schema';
|
||||
|
||||
import { useReceiptFormContext } from './ReceiptFormProvider';
|
||||
|
||||
import ReceiptFromHeader from './ReceiptFormHeader';
|
||||
import ReceiptItemsEntriesEditor from './ReceiptItemsEntriesEditor';
|
||||
import ReceiptFormFloatingActions from './ReceiptFormFloatingActions';
|
||||
import ReceiptFormFooter from './ReceiptFormFooter';
|
||||
import ReceiptFormDialogs from './ReceiptFormDialogs';
|
||||
|
||||
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import { AppToaster } from 'components';
|
||||
import { compose, orderingLinesIndexes, transactionNumber } from 'utils';
|
||||
import { transformToEditForm, defaultReceipt } from './utils';
|
||||
|
||||
/**
|
||||
* Receipt form.
|
||||
*/
|
||||
function ReceiptForm({
|
||||
// #withSettings
|
||||
receiptNextNumber,
|
||||
receiptNumberPrefix,
|
||||
receiptAutoIncrement,
|
||||
preferredDepositAccount,
|
||||
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Receipt form context.
|
||||
const {
|
||||
receipt,
|
||||
editReceiptMutate,
|
||||
createReceiptMutate,
|
||||
submitPayload,
|
||||
isNewMode,
|
||||
} = useReceiptFormContext();
|
||||
|
||||
// The next receipt number.
|
||||
const nextReceiptNumber = transactionNumber(
|
||||
receiptNumberPrefix,
|
||||
receiptNextNumber,
|
||||
);
|
||||
// Initial values in create and edit mode.
|
||||
const initialValues = useMemo(
|
||||
() => ({
|
||||
...(!isEmpty(receipt)
|
||||
? { ...transformToEditForm(receipt), currency_code: base_currency }
|
||||
: {
|
||||
...defaultReceipt,
|
||||
...(receiptAutoIncrement && {
|
||||
receipt_number: nextReceiptNumber,
|
||||
}),
|
||||
deposit_account_id: parseInt(preferredDepositAccount),
|
||||
entries: orderingLinesIndexes(defaultReceipt.entries),
|
||||
currency_code: base_currency,
|
||||
}),
|
||||
}),
|
||||
[receipt, preferredDepositAccount, nextReceiptNumber, receiptAutoIncrement],
|
||||
);
|
||||
|
||||
// Transform response error to fields.
|
||||
const handleErrors = (errors, { setErrors }) => {
|
||||
if (errors.some((e) => e.type === ERROR.SALE_RECEIPT_NUMBER_NOT_UNIQUE)) {
|
||||
setErrors({
|
||||
receipt_number: intl.get('sale_receipt_number_not_unique'),
|
||||
});
|
||||
}
|
||||
if (errors.some((e) => e.type === ERROR.SALE_RECEIPT_NO_IS_REQUIRED)) {
|
||||
setErrors({
|
||||
receipt_number: intl.get('receipt.field.error.receipt_number_required'),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Handle the form submit.
|
||||
const handleFormSubmit = (
|
||||
values,
|
||||
{ setErrors, setSubmitting, resetForm },
|
||||
) => {
|
||||
const entries = values.entries.filter(
|
||||
(item) => item.item_id && item.quantity,
|
||||
);
|
||||
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
|
||||
|
||||
if (totalQuantity === 0) {
|
||||
AppToaster.show({
|
||||
message: intl.get('quantity_cannot_be_zero_or_empty'),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
const form = {
|
||||
...omit(values, ['receipt_number_manually', 'receipt_number']),
|
||||
...(values.receipt_number_manually && {
|
||||
receipt_number: values.receipt_number,
|
||||
currency_code: base_currency,
|
||||
}),
|
||||
closed: submitPayload.status,
|
||||
entries: entries.map((entry) => ({ ...omit(entry, ['total']) })),
|
||||
};
|
||||
// Handle the request success.
|
||||
const onSuccess = (response) => {
|
||||
AppToaster.show({
|
||||
message: intl.get(
|
||||
isNewMode
|
||||
? 'the_receipt_has_been_created_successfully'
|
||||
: 'the_receipt_has_been_edited_successfully',
|
||||
{ number: values.receipt_number },
|
||||
),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
|
||||
if (submitPayload.redirect) {
|
||||
history.push('/receipts');
|
||||
}
|
||||
if (submitPayload.resetForm) {
|
||||
resetForm();
|
||||
}
|
||||
};
|
||||
|
||||
// Handle the request error.
|
||||
const onError = ({
|
||||
response: {
|
||||
data: { errors },
|
||||
},
|
||||
}) => {
|
||||
if (errors) {
|
||||
handleErrors(errors, { setErrors });
|
||||
}
|
||||
setSubmitting(false);
|
||||
};
|
||||
if (!isNewMode) {
|
||||
editReceiptMutate([receipt.id, form]).then(onSuccess).catch(onError);
|
||||
} else {
|
||||
createReceiptMutate(form).then(onSuccess).catch(onError);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
CLASSES.PAGE_FORM,
|
||||
CLASSES.PAGE_FORM_STRIP_STYLE,
|
||||
CLASSES.PAGE_FORM_RECEIPT,
|
||||
)}
|
||||
>
|
||||
<Formik
|
||||
validationSchema={
|
||||
isNewMode ? CreateReceiptFormSchema : EditReceiptFormSchema
|
||||
}
|
||||
initialValues={initialValues}
|
||||
onSubmit={handleFormSubmit}
|
||||
>
|
||||
<Form>
|
||||
<ReceiptFromHeader />
|
||||
<ReceiptItemsEntriesEditor />
|
||||
<ReceiptFormFooter />
|
||||
<ReceiptFormFloatingActions />
|
||||
|
||||
<ReceiptFormDialogs />
|
||||
</Form>
|
||||
</Formik>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withDashboardActions,
|
||||
withSettings(({ receiptSettings }) => ({
|
||||
receiptNextNumber: receiptSettings?.nextNumber,
|
||||
receiptNumberPrefix: receiptSettings?.numberPrefix,
|
||||
receiptAutoIncrement: receiptSettings?.autoIncrement,
|
||||
preferredDepositAccount: receiptSettings?.preferredDepositAccount,
|
||||
})),
|
||||
withCurrentOrganization(),
|
||||
)(ReceiptForm);
|
||||
@@ -0,0 +1,57 @@
|
||||
import * as Yup from 'yup';
|
||||
import intl from 'react-intl-universal';
|
||||
import { DATATYPES_LENGTH } from 'common/dataTypes';
|
||||
import { isBlank } from 'utils';
|
||||
|
||||
const Schema = Yup.object().shape({
|
||||
customer_id: Yup.string()
|
||||
.label(intl.get('customer_name_'))
|
||||
.required(),
|
||||
receipt_date: Yup.date()
|
||||
.required()
|
||||
.label(intl.get('receipt_date_')),
|
||||
receipt_number: Yup.string()
|
||||
.nullable()
|
||||
.max(DATATYPES_LENGTH.STRING)
|
||||
.label(intl.get('receipt_no_')),
|
||||
deposit_account_id: Yup.number()
|
||||
.required()
|
||||
.label(intl.get('deposit_account_')),
|
||||
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING),
|
||||
receipt_message: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(DATATYPES_LENGTH.STRING)
|
||||
.label(intl.get('receipt_message_')),
|
||||
statement: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(DATATYPES_LENGTH.TEXT)
|
||||
.label(intl.get('note')),
|
||||
closed: Yup.boolean(),
|
||||
entries: Yup.array().of(
|
||||
Yup.object().shape({
|
||||
quantity: Yup.number()
|
||||
.nullable()
|
||||
.max(DATATYPES_LENGTH.INT_10)
|
||||
.when(['rate'], {
|
||||
is: (rate) => rate,
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
rate: Yup.number().nullable().max(DATATYPES_LENGTH.INT_10),
|
||||
item_id: Yup.number()
|
||||
.nullable()
|
||||
.when(['quantity', 'rate'], {
|
||||
is: (quantity, rate) => !isBlank(quantity) && !isBlank(rate),
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
discount: Yup.number().nullable().min(0).max(DATATYPES_LENGTH.INT_10),
|
||||
description: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const CreateReceiptFormSchema = Schema;
|
||||
const EditReceiptFormSchema = Schema;
|
||||
|
||||
export { CreateReceiptFormSchema, EditReceiptFormSchema };
|
||||
@@ -0,0 +1,25 @@
|
||||
import React from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import ReceiptNumberDialog from 'containers/Dialogs/ReceiptNumberDialog';
|
||||
|
||||
/**
|
||||
* Receipt form dialogs.
|
||||
*/
|
||||
export default function ReceiptFormDialogs() {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
|
||||
// Update the form once the receipt number form submit confirm.
|
||||
const handleReceiptNumberFormConfirm = ({ incrementNumber, manually }) => {
|
||||
setFieldValue('receipt_number', incrementNumber || '');
|
||||
setFieldValue('receipt_number_manually', manually);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ReceiptNumberDialog
|
||||
dialogName={'receipt-number-form'}
|
||||
onConfirm={handleReceiptNumberFormConfirm}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Intent,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
Popover,
|
||||
PopoverInteractionKind,
|
||||
Position,
|
||||
Menu,
|
||||
MenuItem,
|
||||
} from '@blueprintjs/core';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import classNames from 'classnames';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { If, Icon } from 'components';
|
||||
import { useReceiptFormContext } from './ReceiptFormProvider';
|
||||
|
||||
/**
|
||||
* Receipt floating actions bar.
|
||||
*/
|
||||
export default function ReceiptFormFloatingActions() {
|
||||
// History context.
|
||||
const history = useHistory();
|
||||
|
||||
// Formik context.
|
||||
const { resetForm, submitForm, isSubmitting } = useFormikContext();
|
||||
|
||||
// Receipt form context.
|
||||
const { receipt, setSubmitPayload } = useReceiptFormContext();
|
||||
|
||||
// Handle submit & close button click.
|
||||
const handleSubmitCloseBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, status: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, close & new button click.
|
||||
const handleSubmitCloseAndNewBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, status: true, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, close & continue editing button click.
|
||||
const handleSubmitCloseContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, status: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit & draft button click.
|
||||
const handleSubmitDraftBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, status: false });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, draft & new button click.
|
||||
const handleSubmitDraftAndNewBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, status: false, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
const handleSubmitDraftContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, status: false });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle cancel button click.
|
||||
const handleCancelBtnClick = (event) => {
|
||||
history.goBack();
|
||||
};
|
||||
|
||||
const handleClearBtnClick = (event) => {
|
||||
resetForm();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
|
||||
{/* ----------- Save And Close ----------- */}
|
||||
<If condition={!receipt || !receipt?.is_closed}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
onClick={handleSubmitCloseBtnClick}
|
||||
text={<T id={'save_close'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'close_and_new'} />}
|
||||
onClick={handleSubmitCloseAndNewBtnClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'close_continue_editing'} />}
|
||||
onClick={handleSubmitCloseContinueEditingBtnClick}
|
||||
/>
|
||||
</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>
|
||||
{/* ----------- Save As Draft ----------- */}
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
className={'ml1'}
|
||||
onClick={handleSubmitDraftBtnClick}
|
||||
text={<T id={'save_as_draft'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitDraftAndNewBtnClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'save_continue_editing'} />}
|
||||
onClick={handleSubmitDraftContinueEditingBtnClick}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
minimal={true}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
|
||||
/>
|
||||
</Popover>
|
||||
</ButtonGroup>
|
||||
</If>
|
||||
{/* ----------- Save and New ----------- */}
|
||||
<If condition={receipt && receipt?.is_closed}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
onClick={handleSubmitCloseBtnClick}
|
||||
text={<T id={'save'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitCloseAndNewBtnClick}
|
||||
/>
|
||||
</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>
|
||||
</If>
|
||||
{/* ----------- Clear & Reset----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
disabled={isSubmitting}
|
||||
onClick={handleClearBtnClick}
|
||||
text={receipt ? <T id={'reset'} /> : <T id={'clear'} />}
|
||||
/>
|
||||
{/* ----------- Cancel ----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
onClick={handleCancelBtnClick}
|
||||
text={<T id={'cancel'} />}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import React from 'react';
|
||||
import { FormGroup, TextArea } from '@blueprintjs/core';
|
||||
import { FastField } from 'formik';
|
||||
import classNames from 'classnames';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import { Dragzone, Postbox, Row, Col } from 'components';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { inputIntent } from 'utils';
|
||||
|
||||
export default function ReceiptFormFooter({}) {
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
|
||||
<Postbox title={<T id={'receipt_details'}/>} defaultOpen={false}>
|
||||
<Row>
|
||||
<Col md={8}>
|
||||
{/* --------- Receipt message --------- */}
|
||||
<FastField name={'receipt_message'}>
|
||||
{({ field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'receipt_message'} />}
|
||||
className={'form-group--receipt_message'}
|
||||
intent={inputIntent({ error, touched })}
|
||||
>
|
||||
<TextArea growVertically={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* --------- Statement--------- */}
|
||||
<FastField name={'statement'}>
|
||||
{({ field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'statement'} />}
|
||||
className={'form-group--statement'}
|
||||
intent={inputIntent({ error, touched })}
|
||||
>
|
||||
<TextArea growVertically={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</Col>
|
||||
|
||||
<Col md={4}>
|
||||
<Dragzone
|
||||
initialFiles={[]}
|
||||
// onDrop={handleDropFiles}
|
||||
// onDeleteFile={handleDeleteFile}
|
||||
hint={<T id={'attachments_maximum'} />}
|
||||
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</Postbox>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { useFormikContext } from 'formik';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { PageFormBigNumber } from 'components';
|
||||
import ReceiptFormHeaderFields from './ReceiptFormHeaderFields';
|
||||
|
||||
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
|
||||
|
||||
import { getEntriesTotal } from 'containers/Entries/utils';
|
||||
import { compose } from 'redux';
|
||||
|
||||
/**
|
||||
* Receipt form header section.
|
||||
*/
|
||||
function ReceiptFormHeader({
|
||||
// #ownProps
|
||||
onReceiptNumberChanged,
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
const { values } = useFormikContext();
|
||||
|
||||
// Calculate the total due amount of bill entries.
|
||||
const totalDueAmount = useMemo(
|
||||
() => getEntriesTotal(values.entries),
|
||||
[values.entries],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
|
||||
<ReceiptFormHeaderFields
|
||||
onReceiptNumberChanged={onReceiptNumberChanged}
|
||||
/>
|
||||
<PageFormBigNumber
|
||||
label={intl.get('due_amount')}
|
||||
amount={totalDueAmount}
|
||||
currencyCode={base_currency}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withCurrentOrganization())(ReceiptFormHeader);
|
||||
@@ -0,0 +1,228 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import {
|
||||
FormGroup,
|
||||
InputGroup,
|
||||
Position,
|
||||
ControlGroup,
|
||||
} from '@blueprintjs/core';
|
||||
import { DateInput } from '@blueprintjs/datetime';
|
||||
import { FormattedMessage as T } from 'components';
|
||||
import classNames from 'classnames';
|
||||
import { FastField, ErrorMessage } from 'formik';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import {
|
||||
AccountsSelectList,
|
||||
ContactSelecetList,
|
||||
FieldRequiredHint,
|
||||
Icon,
|
||||
InputPrependButton,
|
||||
} from 'components';
|
||||
import withSettings from 'containers/Settings/withSettings';
|
||||
import withDialogActions from 'containers/Dialog/withDialogActions';
|
||||
import { ACCOUNT_TYPE } from 'common/accountTypes';
|
||||
import {
|
||||
momentFormatter,
|
||||
compose,
|
||||
tansformDateValue,
|
||||
handleDateChange,
|
||||
inputIntent,
|
||||
} from 'utils';
|
||||
import { useReceiptFormContext } from './ReceiptFormProvider';
|
||||
import {
|
||||
accountsFieldShouldUpdate,
|
||||
customersFieldShouldUpdate,
|
||||
useObserveReceiptNoSettings,
|
||||
} from './utils';
|
||||
|
||||
/**
|
||||
* Receipt form header fields.
|
||||
*/
|
||||
function ReceiptFormHeader({
|
||||
//#withDialogActions
|
||||
openDialog,
|
||||
|
||||
// #ownProps
|
||||
onReceiptNumberChanged,
|
||||
|
||||
// #withSettings
|
||||
receiptAutoIncrement,
|
||||
receiptNextNumber,
|
||||
receiptNumberPrefix,
|
||||
}) {
|
||||
const { accounts, customers } = useReceiptFormContext();
|
||||
|
||||
const handleReceiptNumberChange = useCallback(() => {
|
||||
openDialog('receipt-number-form', {});
|
||||
}, [openDialog]);
|
||||
|
||||
const handleReceiptNoBlur = (form, field) => (event) => {
|
||||
const newValue = event.target.value;
|
||||
|
||||
if (field.value !== newValue && receiptAutoIncrement) {
|
||||
openDialog('receipt-number-form', {
|
||||
initialFormValues: {
|
||||
manualTransactionNo: newValue,
|
||||
incrementMode: 'manual-transaction',
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Synsc receipt number settings with the form.
|
||||
useObserveReceiptNoSettings(receiptNumberPrefix, receiptNextNumber);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
|
||||
{/* ----------- Customer name ----------- */}
|
||||
<FastField
|
||||
name={'customer_id'}
|
||||
customers={customers}
|
||||
shouldUpdate={customersFieldShouldUpdate}
|
||||
>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'customer_name'} />}
|
||||
inline={true}
|
||||
className={classNames(CLASSES.FILL, 'form-group--customer')}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name={'customer_id'} />}
|
||||
>
|
||||
<ContactSelecetList
|
||||
contactsList={customers}
|
||||
selectedContactId={value}
|
||||
defaultSelectText={<T id={'select_customer_account'} />}
|
||||
onContactSelected={(contact) => {
|
||||
form.setFieldValue('customer_id', contact.id);
|
||||
}}
|
||||
popoverFill={true}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Deposit account ----------- */}
|
||||
<FastField
|
||||
name={'deposit_account_id'}
|
||||
accounts={accounts}
|
||||
shouldUpdate={accountsFieldShouldUpdate}
|
||||
>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'deposit_account'} />}
|
||||
className={classNames('form-group--deposit-account', CLASSES.FILL)}
|
||||
inline={true}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name={'deposit_account_id'} />}
|
||||
>
|
||||
<AccountsSelectList
|
||||
accounts={accounts}
|
||||
onAccountSelected={(account) => {
|
||||
form.setFieldValue('deposit_account_id', account.id);
|
||||
}}
|
||||
defaultSelectText={<T id={'select_deposit_account'} />}
|
||||
selectedAccountId={value}
|
||||
popoverFill={true}
|
||||
filterByTypes={[
|
||||
ACCOUNT_TYPE.CASH,
|
||||
ACCOUNT_TYPE.BANK,
|
||||
ACCOUNT_TYPE.OTHER_CURRENT_ASSET,
|
||||
]}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Receipt date ----------- */}
|
||||
<FastField name={'receipt_date'}>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'receipt_date'} />}
|
||||
inline={true}
|
||||
className={classNames(CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="receipt_date" />}
|
||||
>
|
||||
<DateInput
|
||||
{...momentFormatter('YYYY/MM/DD')}
|
||||
value={tansformDateValue(value)}
|
||||
onChange={handleDateChange((formattedDate) => {
|
||||
form.setFieldValue('receipt_date', formattedDate);
|
||||
})}
|
||||
popoverProps={{ position: Position.BOTTOM, minimal: true }}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Receipt number ----------- */}
|
||||
<FastField name={'receipt_number'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'receipt'} />}
|
||||
inline={true}
|
||||
className={('form-group--receipt_number', CLASSES.FILL)}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="receipt_number" />}
|
||||
>
|
||||
<ControlGroup fill={true}>
|
||||
<InputGroup
|
||||
minimal={true}
|
||||
value={field.value}
|
||||
asyncControl={true}
|
||||
onBlur={handleReceiptNoBlur(form, field)}
|
||||
/>
|
||||
<InputPrependButton
|
||||
buttonProps={{
|
||||
onClick: handleReceiptNumberChange,
|
||||
icon: <Icon icon={'settings-18'} />,
|
||||
}}
|
||||
tooltip={true}
|
||||
tooltipProps={{
|
||||
content: (
|
||||
<T
|
||||
id={'setting_your_auto_generated_payment_receive_number'}
|
||||
/>
|
||||
),
|
||||
position: Position.BOTTOM_LEFT,
|
||||
}}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</ControlGroup>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Reference ----------- */}
|
||||
<FastField name={'reference_no'}>
|
||||
{({ 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_no" />}
|
||||
>
|
||||
<InputGroup minimal={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withDialogActions,
|
||||
withSettings(({ receiptSettings }) => ({
|
||||
receiptAutoIncrement: receiptSettings?.autoIncrement,
|
||||
receiptNextNumber: receiptSettings?.nextNumber,
|
||||
receiptNumberPrefix: receiptSettings?.numberPrefix,
|
||||
})),
|
||||
)(ReceiptFormHeader);
|
||||
21
src/containers/Sales/Receipts/ReceiptForm/ReceiptFormPage.js
Normal file
21
src/containers/Sales/Receipts/ReceiptForm/ReceiptFormPage.js
Normal file
@@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
import 'style/pages/SaleReceipt/PageForm.scss';
|
||||
|
||||
import ReceiptFrom from './ReceiptForm';
|
||||
import { ReceiptFormProvider } from './ReceiptFormProvider';
|
||||
|
||||
/**
|
||||
* Receipt form page.
|
||||
*/
|
||||
export default function ReceiptFormPage() {
|
||||
const { id } = useParams();
|
||||
const idInt = parseInt(id, 10);
|
||||
|
||||
return (
|
||||
<ReceiptFormProvider receiptId={idInt}>
|
||||
<ReceiptFrom />
|
||||
</ReceiptFormProvider>
|
||||
);
|
||||
}
|
||||
101
src/containers/Sales/Receipts/ReceiptForm/ReceiptFormProvider.js
Normal file
101
src/containers/Sales/Receipts/ReceiptForm/ReceiptFormProvider.js
Normal file
@@ -0,0 +1,101 @@
|
||||
import React, { createContext, useState } from 'react';
|
||||
import DashboardInsider from 'components/Dashboard/DashboardInsider';
|
||||
import {
|
||||
useReceipt,
|
||||
useAccounts,
|
||||
useSettingsReceipts,
|
||||
useCustomers,
|
||||
useItems,
|
||||
useCreateReceipt,
|
||||
useEditReceipt,
|
||||
} from 'hooks/query';
|
||||
|
||||
const ReceiptFormContext = createContext();
|
||||
|
||||
/**
|
||||
* Receipt form provider.
|
||||
*/
|
||||
function ReceiptFormProvider({ receiptId, ...props }) {
|
||||
// Fetch sale receipt details.
|
||||
const { data: receipt, isLoading: isReceiptLoading } = useReceipt(
|
||||
receiptId,
|
||||
{
|
||||
enabled: !!receiptId,
|
||||
},
|
||||
);
|
||||
// Fetch accounts list.
|
||||
const { data: accounts, isLoading: isAccountsLoading } = useAccounts();
|
||||
|
||||
// Fetch customers list.
|
||||
const {
|
||||
data: { customers },
|
||||
isLoading: isCustomersLoading,
|
||||
} = useCustomers({ page_size: 10000 });
|
||||
|
||||
// Filter all sellable items only.
|
||||
const stringifiedFilterRoles = React.useMemo(
|
||||
() =>
|
||||
JSON.stringify([
|
||||
{ index: 1, fieldKey: 'sellable', value: true, condition: '&&', comparator: 'equals', },
|
||||
{ index: 2, fieldKey: 'active', value: true, condition: '&&', comparator: 'equals' },
|
||||
]),
|
||||
[],
|
||||
);
|
||||
|
||||
// Handle fetch Items data table or list
|
||||
const {
|
||||
data: { items },
|
||||
isLoading: isItemsLoading,
|
||||
} = useItems({
|
||||
page_size: 10000,
|
||||
stringified_filter_roles: stringifiedFilterRoles,
|
||||
});
|
||||
|
||||
// Fetch receipt settings.
|
||||
const { isLoading: isSettingLoading } = useSettingsReceipts();
|
||||
|
||||
const { mutateAsync: createReceiptMutate } = useCreateReceipt();
|
||||
const { mutateAsync: editReceiptMutate } = useEditReceipt();
|
||||
|
||||
const [submitPayload, setSubmitPayload] = useState({});
|
||||
|
||||
const isNewMode = !receiptId;
|
||||
|
||||
const provider = {
|
||||
receiptId,
|
||||
receipt,
|
||||
accounts,
|
||||
customers,
|
||||
items,
|
||||
submitPayload,
|
||||
|
||||
isNewMode,
|
||||
isReceiptLoading,
|
||||
isAccountsLoading,
|
||||
isCustomersLoading,
|
||||
isItemsLoading,
|
||||
isSettingLoading,
|
||||
|
||||
createReceiptMutate,
|
||||
editReceiptMutate,
|
||||
setSubmitPayload,
|
||||
};
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={
|
||||
isReceiptLoading ||
|
||||
isAccountsLoading ||
|
||||
isCustomersLoading ||
|
||||
isItemsLoading ||
|
||||
isSettingLoading
|
||||
}
|
||||
name={'receipt-form'}
|
||||
>
|
||||
<ReceiptFormContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const useReceiptFormContext = () => React.useContext(ReceiptFormContext);
|
||||
|
||||
export { ReceiptFormProvider, useReceiptFormContext };
|
||||
@@ -0,0 +1,34 @@
|
||||
import React from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { FastField } from 'formik';
|
||||
import ItemsEntriesTable from 'containers/Entries/ItemsEntriesTable';
|
||||
import { CLASSES } from 'common/classes';
|
||||
import { useReceiptFormContext } from './ReceiptFormProvider';
|
||||
import { entriesFieldShouldUpdate } from './utils';
|
||||
|
||||
export default function ReceiptItemsEntriesEditor({ defaultReceipt }) {
|
||||
const { items } = useReceiptFormContext();
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
|
||||
<FastField name={'entries'} items={items} shouldUpdate={entriesFieldShouldUpdate}>
|
||||
{({
|
||||
form: { values, setFieldValue },
|
||||
field: { value },
|
||||
meta: { error, touched },
|
||||
}) => (
|
||||
<ItemsEntriesTable
|
||||
entries={value}
|
||||
onUpdateData={(entries) => {
|
||||
setFieldValue('entries', entries);
|
||||
}}
|
||||
items={items}
|
||||
errors={error}
|
||||
linesNumber={4}
|
||||
currencyCode={values.currency_code}
|
||||
/>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user