re-structure to monorepo.

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

View File

@@ -0,0 +1,191 @@
// @ts-nocheck
import React from 'react';
import { useHistory } from 'react-router-dom';
import { useFormikContext } from 'formik';
import {
Intent,
Button,
ButtonGroup,
Popover,
PopoverInteractionKind,
Position,
Menu,
MenuItem,
} from '@blueprintjs/core';
import { If, Icon, FormattedMessage as T } from '@/components';
import { CLASSES } from '@/constants/classes';
import classNames from 'classnames';
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
/**
* Credit note floating actions.
*/
export default function CreditNoteFloatingActions() {
const history = useHistory();
// Formik context.
const { resetForm, submitForm, isSubmitting } = useFormikContext();
// Credit note form context.
const { setSubmitPayload, creditNote } = useCreditNoteFormContext();
// Handle submit as open button click.
const handleSubmitOpenBtnClick = (event) => {
setSubmitPayload({ redirect: true, open: true });
submitForm();
};
// Handle submit, open and anothe new button click.
const handleSubmitOpenAndNewBtnClick = (event) => {
setSubmitPayload({ redirect: false, open: true, resetForm: true });
submitForm();
};
// Handle submit as open & continue editing button click.
const handleSubmitOpenContinueEditingBtnClick = (event) => {
setSubmitPayload({ redirect: false, open: true });
submitForm();
};
// Handle submit as draft button click.
const handleSubmitDraftBtnClick = (event) => {
setSubmitPayload({ redirect: true, open: false });
submitForm();
};
// handle submit as draft & new button click.
const handleSubmitDraftAndNewBtnClick = (event) => {
setSubmitPayload({ redirect: false, open: false, resetForm: true });
submitForm();
};
// Handle submit as draft & continue editing button click.
const handleSubmitDraftContinueEditingBtnClick = (event) => {
setSubmitPayload({ redirect: false, open: 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 Open ----------- */}
<If condition={!creditNote || !creditNote?.is_open}>
<ButtonGroup>
<Button
disabled={isSubmitting}
loading={isSubmitting}
intent={Intent.PRIMARY}
onClick={handleSubmitOpenBtnClick}
text={<T id={'save_open'} />}
/>
<Popover
content={
<Menu>
<MenuItem
text={<T id={'open_and_new'} />}
onClick={handleSubmitOpenAndNewBtnClick}
/>
<MenuItem
text={<T id={'open_continue_editing'} />}
onClick={handleSubmitOpenContinueEditingBtnClick}
/>
</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={creditNote && creditNote?.is_open}>
<ButtonGroup>
<Button
loading={isSubmitting}
intent={Intent.PRIMARY}
onClick={handleSubmitOpenBtnClick}
style={{ minWidth: '85px' }}
text={<T id={'save'} />}
/>
<Popover
content={
<Menu>
<MenuItem
text={<T id={'save_and_new'} />}
onClick={handleSubmitOpenAndNewBtnClick}
/>
</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={creditNote ? <T id={'reset'} /> : <T id={'clear'} />}
/>
{/* ----------- Cancel ----------- */}
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={handleCancelBtnClick}
text={<T id={'cancel'} />}
/>
</div>
);
}

View File

@@ -0,0 +1,52 @@
// @ts-nocheck
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import { DATATYPES_LENGTH } from '@/constants/dataTypes';
import { isBlank } from '@/utils';
const getSchema = () =>
Yup.object().shape({
customer_id: Yup.string().label(intl.get('customer_name_')).required(),
credit_note_date: Yup.date().required().label(intl.get('invoice_date_')),
credit_note_number: Yup.string()
.max(DATATYPES_LENGTH.STRING)
.label(intl.get('invoice_no_')),
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING),
note: Yup.string()
.trim()
.min(1)
.max(DATATYPES_LENGTH.TEXT)
.label(intl.get('note')),
open: Yup.boolean(),
terms_conditions: Yup.string()
.trim()
.min(1)
.max(DATATYPES_LENGTH.TEXT)
.label(intl.get('note')),
branch_id: Yup.string(),
warehouse_id: Yup.string(),
exchange_rate:Yup.number(),
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 CreateCreditNoteFormSchema = getSchema;
export const EditCreditNoteFormSchema = getSchema;

View File

@@ -0,0 +1,177 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { useHistory } from 'react-router-dom';
import { Formik, Form } from 'formik';
import { Intent } from '@blueprintjs/core';
import { isEmpty } from 'lodash';
import { CLASSES } from '@/constants/classes';
import {
CreateCreditNoteFormSchema,
EditCreditNoteFormSchema,
} from './CreditNoteForm.schema';
import CreditNoteFormHeader from './CreditNoteFormHeader';
import CreditNoteItemsEntriesEditorField from './CreditNoteItemsEntriesEditorField';
import CreditNoteFormFooter from './CreditNoteFormFooter';
import CreditNoteFloatingActions from './CreditNoteFloatingActions';
import CreditNoteFormDialogs from './CreditNoteFormDialogs';
import CreditNoteFormTopBar from './CreditNoteFormTopBar';
import { AppToaster } from '@/components';
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
import {
filterNonZeroEntries,
transformToEditForm,
transformFormValuesToRequest,
defaultCreditNote,
} from './utils';
import {
compose,
orderingLinesIndexes,
transactionNumber,
safeSumBy,
} from '@/utils';
import withSettings from '@/containers/Settings/withSettings';
import withCurrentOrganization from '@/containers/Organization/withCurrentOrganization';
/**
* Credit note form.
*/
function CreditNoteForm({
// #withSettings
creditAutoIncrement,
creditNumberPrefix,
creditNextNumber,
// #withCurrentOrganization
organization: { base_currency },
}) {
const history = useHistory();
// Credit note form context.
const {
isNewMode,
submitPayload,
creditNote,
newCreditNote,
createCreditNoteMutate,
editCreditNoteMutate,
} = useCreditNoteFormContext();
// Credit number.
const creditNumber = transactionNumber(creditNumberPrefix, creditNextNumber);
// Initial values.
const initialValues = React.useMemo(
() => ({
...(!isEmpty(creditNote)
? { ...transformToEditForm(creditNote) }
: {
...defaultCreditNote,
...(creditAutoIncrement && {
credit_note_number: creditNumber,
}),
entries: orderingLinesIndexes(defaultCreditNote.entries),
currency_code: base_currency,
...newCreditNote,
}),
}),
[],
);
// Handles form submit.
const handleFormSubmit = (
values,
{ setSubmitting, setErrors, resetForm },
) => {
const entries = filterNonZeroEntries(values.entries);
const totalQuantity = safeSumBy(entries, 'quantity');
if (totalQuantity === 0) {
AppToaster.show({
message: intl.get('quantity_cannot_be_zero_or_empty'),
intent: Intent.DANGER,
});
setSubmitting(false);
return;
}
const form = {
...transformFormValuesToRequest(values),
open: submitPayload.open,
};
// Handle the request success.
const onSuccess = (response) => {
AppToaster.show({
message: intl.get(
isNewMode
? 'credit_note.success_message'
: 'credit_note.edit_success_message',
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
if (submitPayload.redirect) {
history.push('/credit-notes');
}
if (submitPayload.resetForm) {
resetForm();
}
};
// Handle the request error.
const onError = ({
response: {
data: { errors },
},
}) => {
setSubmitting(false);
};
if (isNewMode) {
createCreditNoteMutate(form).then(onSuccess).catch(onError);
} else {
editCreditNoteMutate([creditNote.id, form])
.then(onSuccess)
.catch(onError);
}
};
return (
<div
className={classNames(
CLASSES.PAGE_FORM,
CLASSES.PAGE_FORM_STRIP_STYLE,
CLASSES.PAGE_FORM_CREDIT_NOTE,
)}
>
<Formik
validationSchema={
isNewMode ? CreateCreditNoteFormSchema : EditCreditNoteFormSchema
}
initialValues={initialValues}
onSubmit={handleFormSubmit}
>
<Form>
<CreditNoteFormTopBar />
<CreditNoteFormHeader />
<CreditNoteItemsEntriesEditorField />
<CreditNoteFormFooter />
<CreditNoteFloatingActions />
<CreditNoteFormDialogs />
</Form>
</Formik>
</div>
);
}
export default compose(
withSettings(({ creditNoteSettings }) => ({
creditAutoIncrement: creditNoteSettings?.autoIncrement,
creditNextNumber: creditNoteSettings?.nextNumber,
creditNumberPrefix: creditNoteSettings?.numberPrefix,
})),
withCurrentOrganization(),
)(CreditNoteForm);

View File

@@ -0,0 +1,25 @@
// @ts-nocheck
import React from 'react';
import CreditNoteNumberDialog from '@/containers/Dialogs/CreditNoteNumberDialog';
import { useFormikContext } from 'formik';
/**
* Credit note form dialogs.
*/
export default function CreditNoteFormDialogs() {
// Update the form once the credit number form submit confirm.
const handleCreditNumberFormConfirm = ({ incrementNumber, manually }) => {
setFieldValue('credit_note_number', incrementNumber || '');
setFieldValue('credit_note_no_manually', manually);
};
const { setFieldValue } = useFormikContext();
return (
<React.Fragment>
<CreditNoteNumberDialog
dialogName={'credit-number-form'}
onConfirm={handleCreditNumberFormConfirm}
/>
</React.Fragment>
);
}

View File

@@ -0,0 +1,33 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import styled from 'styled-components';
import { CLASSES } from '@/constants/classes';
import { Row, Col, Paper } from '@/components';
import { CreditNoteFormFooterLeft } from './CreditNoteFormFooterLeft';
import { CreditNoteFormFooterRight } from './CreditNoteFormFooterRight';
/**
* Credit note form footer.
*/
export default function CreditNoteFormFooter() {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<CreditNoteFooterPaper>
<Row>
<Col md={8}>
<CreditNoteFormFooterLeft />
</Col>
<Col md={4}>
<CreditNoteFormFooterRight />
</Col>
</Row>
</CreditNoteFooterPaper>
</div>
);
}
const CreditNoteFooterPaper = styled(Paper)`
padding: 20px;
`;

View File

@@ -0,0 +1,60 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import styled from 'styled-components';
import { FFormGroup, FEditableText, FormattedMessage as T } from '@/components';
export function CreditNoteFormFooterLeft() {
return (
<React.Fragment>
{/* --------- Customer notes --------- */}
<CreditNoteMsgFormGroup
name={'note'}
label={<T id={'credit_note.label_customer_note'} />}
>
<FEditableText
name={'note'}
placeholder={intl.get('credit_note.label_customer_note.placeholder')}
/>
</CreditNoteMsgFormGroup>
{/* --------- Terms and conditions --------- */}
<TermsConditsFormGroup
label={<T id={'credit_note.label_terms_conditions'} />}
name={'terms_conditions'}
>
<FEditableText
name={'terms_conditions'}
placeholder={intl.get(
'credit_note.label_terms_and_conditions.placeholder',
)}
/>
</TermsConditsFormGroup>
</React.Fragment>
);
}
const CreditNoteMsgFormGroup = styled(FFormGroup)`
&.bp3-form-group {
margin-bottom: 40px;
.bp3-label {
font-size: 12px;
margin-bottom: 12px;
}
.bp3-form-content {
margin-left: 10px;
}
}
`;
const TermsConditsFormGroup = styled(FFormGroup)`
&.bp3-form-group {
.bp3-label {
font-size: 12px;
margin-bottom: 12px;
}
.bp3-form-content {
margin-left: 10px;
}
}
`;

View File

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

View File

@@ -0,0 +1,35 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { useFormikContext } from 'formik';
import { CLASSES } from '@/constants/classes';
import CreditNoteFormHeaderFields from './CreditNoteFormHeaderFields';
import { getEntriesTotal } from '@/containers/Entries/utils';
import { PageFormBigNumber } from '@/components';
/**
* Credit note header.
*/
function CreditNoteFormHeader() {
const {
values: { entries, currency_code },
} = useFormikContext();
// Calculate the total amount.
const totalAmount = React.useMemo(() => getEntriesTotal(entries), [entries]);
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<CreditNoteFormHeaderFields />
<PageFormBigNumber
label={intl.get('credit_note.label_amount_to_credit')}
amount={totalAmount}
currencyCode={currency_code}
/>
</div>
);
}
export default CreditNoteFormHeader;

View File

@@ -0,0 +1,215 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import styled from 'styled-components';
import {
FormGroup,
InputGroup,
Position,
ControlGroup,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FastField, Field, ErrorMessage } from 'formik';
import { CLASSES } from '@/constants/classes';
import {
CustomerSelectField,
FieldRequiredHint,
InputPrependButton,
Icon,
FormattedMessage as T,
CustomerDrawerLink,
} from '@/components';
import {
customerNameFieldShouldUpdate,
useObserveCreditNoSettings,
} from './utils';
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
import withSettings from '@/containers/Settings/withSettings';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import { CreditNoteExchangeRateInputField } from './components';
import {
momentFormatter,
compose,
tansformDateValue,
inputIntent,
handleDateChange,
} from '@/utils';
/**
* Credit note form header fields.
*/
function CreditNoteFormHeaderFields({
// #withDialogActions
openDialog,
// #withSettings
creditAutoIncrement,
creditNumberPrefix,
creditNextNumber,
}) {
// Credit note form context.
const { customers } = useCreditNoteFormContext();
// Handle credit number changing.
const handleCreditNumberChange = () => {
openDialog('credit-number-form');
};
// Handle credit no. field blur.
const handleCreditNoBlur = (form, field) => (event) => {
const newValue = event.target.value;
if (field.value !== newValue && creditAutoIncrement) {
openDialog('credit-number-form', {
initialFormValues: {
manualTransactionNo: newValue,
incrementMode: 'manual-transaction',
},
});
}
};
// Syncs credit number settings with form.
useObserveCreditNoSettings(creditNumberPrefix, creditNextNumber);
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'} />}
>
<CustomerSelectField
contacts={customers}
selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={(customer) => {
form.setFieldValue('customer_id', customer.id);
form.setFieldValue('currency_code', customer?.currency_code);
}}
popoverFill={true}
allowCreate={true}
/>
{value && (
<CustomerButtonLink customerId={value}>
<T id={'view_customer_details'} />
</CustomerButtonLink>
)}
</FormGroup>
)}
</FastField>
{/* ----------- Exchange rate ----------- */}
<CreditNoteExchangeRateInputField
name={'exchange_rate'}
formGroupProps={{ label: ' ', inline: true }}
/>
{/* ----------- Credit note date ----------- */}
<FastField name={'credit_note_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'credit_note.label_credit_note_date'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
className={classNames('form-group--credit_note_date', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="credit_note_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('credit_note_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM_LEFT, minimal: true }}
inputProps={{
leftIcon: <Icon icon={'date-range'} />,
}}
/>
</FormGroup>
)}
</FastField>
{/* ----------- Credit note # ----------- */}
<Field name={'credit_note_number'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'credit_note.label_credit_note'} />}
labelInfo={<FieldRequiredHint />}
inline={true}
className={classNames(
'form-group--credit_note_number',
CLASSES.FILL,
)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="credit_note_number" />}
>
<ControlGroup fill={true}>
<InputGroup
minimal={true}
value={field.value}
asyncControl={true}
onBlur={handleCreditNoBlur(form, field)}
/>
<InputPrependButton
buttonProps={{
onClick: handleCreditNumberChange,
icon: <Icon icon={'settings-18'} />,
}}
tooltip={true}
tooltipProps={{
content: (
<T id={'setting_your_auto_generated_credit_note_number'} />
),
position: Position.BOTTOM_LEFT,
}}
/>
</ControlGroup>
</FormGroup>
)}
</Field>
{/* ----------- Reference ----------- */}
<FastField name={'reference_no'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'reference_no'} />}
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(({ creditNoteSettings }) => ({
creditAutoIncrement: creditNoteSettings?.autoIncrement,
creditNextNumber: creditNoteSettings?.nextNumber,
creditNumberPrefix: creditNoteSettings?.numberPrefix,
})),
)(CreditNoteFormHeaderFields);
const CustomerButtonLink = styled(CustomerDrawerLink)`
font-size: 11px;
margin-top: 6px;
`;

View File

@@ -0,0 +1,22 @@
// @ts-nocheck
import React from 'react';
import { useParams } from 'react-router-dom';
import '@/style/pages/CreditNote/PageForm.scss';
import CreditNoteForm from './CreditNoteForm';
import { CreditNoteFormProvider } from './CreditNoteFormProvider';
/**
* Credit note form page.
*/
export default function CreditNoteFormPage() {
const { id } = useParams();
const idAsInteger = parseInt(id, 10);
return (
<CreditNoteFormProvider creditNoteId={idAsInteger}>
<CreditNoteForm />
</CreditNoteFormProvider>
);
}

View File

@@ -0,0 +1,135 @@
// @ts-nocheck
import React from 'react';
import { useLocation } from 'react-router-dom';
import { isEmpty, pick } from 'lodash';
import { DashboardInsider } from '@/components/Dashboard';
import { transformToEditForm } from './utils';
import { Features } from '@/constants';
import { useFeatureCan } from '@/hooks/state';
import {
useCreditNote,
useCreateCreditNote,
useEditCreditNote,
useItems,
useCustomers,
useWarehouses,
useBranches,
useSettingsCreditNotes,
useInvoice,
} from '@/hooks/query';
const CreditNoteFormContext = React.createContext();
/**
* Credit note data provider.
*/
function CreditNoteFormProvider({ creditNoteId, ...props }) {
const { state } = useLocation();
const invoiceId = state?.invoiceId;
// Features guard.
const { featureCan } = useFeatureCan();
const isWarehouseFeatureCan = featureCan(Features.Warehouses);
const isBranchFeatureCan = featureCan(Features.Branches);
// Handle fetch customers data table or list
const {
data: { customers },
isLoading: isCustomersLoading,
} = useCustomers({ page_size: 10000 });
// Handle fetching the items table based on the given query.
const {
data: { items },
isLoading: isItemsLoading,
} = useItems({
page_size: 10000,
});
// Handle fetch credit details.
const { data: creditNote, isLoading: isCreditNoteLoading } = useCreditNote(
creditNoteId,
{
enabled: !!creditNoteId,
},
);
// Handle fetch invoice detail.
const { data: invoice, isLoading: isInvoiceLoading } = useInvoice(invoiceId, {
enabled: !!invoiceId,
});
// Fetch warehouses list.
const {
data: warehouses,
isLoading: isWarehouesLoading,
isSuccess: isWarehousesSuccess,
} = useWarehouses({}, { enabled: isWarehouseFeatureCan });
// Fetches the branches list.
const {
data: branches,
isLoading: isBranchesLoading,
isSuccess: isBranchesSuccess,
} = useBranches({}, { enabled: isBranchFeatureCan });
// Handle fetching settings.
useSettingsCreditNotes();
// Create and edit credit note mutations.
const { mutateAsync: createCreditNoteMutate } = useCreateCreditNote();
const { mutateAsync: editCreditNoteMutate } = useEditCreditNote();
// Form submit payload.
const [submitPayload, setSubmitPayload] = React.useState();
// Determines whether the form in new mode.
const isNewMode = !creditNoteId;
// Determines whether the warehouse and branches are loading.
const isFeatureLoading = isWarehouesLoading || isBranchesLoading;
const newCreditNote = !isEmpty(invoice)
? transformToEditForm({
...pick(invoice, ['customer_id', 'currency_code', 'entries']),
})
: [];
// Provider payload.
const provider = {
items,
customers,
creditNote,
branches,
warehouses,
submitPayload,
isNewMode,
newCreditNote,
isItemsLoading,
isCustomersLoading,
isFeatureLoading,
isBranchesSuccess,
isWarehousesSuccess,
createCreditNoteMutate,
editCreditNoteMutate,
setSubmitPayload,
};
const isLoading =
isItemsLoading ||
isCustomersLoading ||
isCreditNoteLoading ||
isInvoiceLoading;
return (
<DashboardInsider loading={isLoading} name={'credit-note-form'}>
<CreditNoteFormContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const useCreditNoteFormContext = () => React.useContext(CreditNoteFormContext);
export { CreditNoteFormProvider, useCreditNoteFormContext };

View File

@@ -0,0 +1,115 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import {
Alignment,
NavbarGroup,
NavbarDivider,
Button,
Classes,
} from '@blueprintjs/core';
import {
useSetPrimaryBranchToForm,
useSetPrimaryWarehouseToForm,
} from './utils';
import { Features } from '@/constants';
import { useFeatureCan } from '@/hooks/state';
import {
Icon,
BranchSelect,
FeatureCan,
WarehouseSelect,
FormTopbar,
DetailsBarSkeletonBase,
} from '@/components';
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
/**
* Credit note form topbar .
* @returns {JSX.Element}
*/
export default function CreditNoteFormTopbar() {
// Features guard.
const { featureCan } = useFeatureCan();
// Sets the primary warehouse to form.
useSetPrimaryWarehouseToForm();
// Sets the primary branch to form.
useSetPrimaryBranchToForm();
// Can't display the navigation bar if warehouses or branches feature is not enabled.
if (!featureCan(Features.Warehouses) && !featureCan(Features.Branches)) {
return null;
}
return (
<FormTopbar>
<NavbarGroup align={Alignment.LEFT}>
<FeatureCan feature={Features.Branches}>
<CreditNoteFormSelectBranch />
</FeatureCan>
{featureCan(Features.Warehouses) && featureCan(Features.Branches) && (
<NavbarDivider />
)}
<FeatureCan feature={Features.Warehouses}>
<CreditFormSelectWarehouse />
</FeatureCan>
</NavbarGroup>
</FormTopbar>
);
}
function CreditNoteFormSelectBranch() {
// Credit note form context.
const { branches, isBranchesLoading } = useCreditNoteFormContext();
return isBranchesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<BranchSelect
name={'branch_id'}
branches={branches}
input={CreditNoteBranchSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function CreditFormSelectWarehouse() {
// Credit note form context.
const { warehouses, isWarehouesLoading } = useCreditNoteFormContext();
return isWarehouesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<WarehouseSelect
name={'warehouse_id'}
warehouses={warehouses}
input={CreditNoteWarehouseSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function CreditNoteWarehouseSelectButton({ label }) {
return (
<Button
text={intl.get('credit_note.warehouse_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'warehouse-16'} iconSize={16} />}
/>
);
}
function CreditNoteBranchSelectButton({ label }) {
return (
<Button
text={intl.get('credit_note.branch_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'branch-16'} iconSize={16} />}
/>
);
}

View File

@@ -0,0 +1,42 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import { FastField } from 'formik';
import { CLASSES } from '@/constants/classes';
import ItemsEntriesTable from '@/containers/Entries/ItemsEntriesTable';
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
import { entriesFieldShouldUpdate } from './utils';
/**
* Credit note items entries editor field.
*/
export default function CreditNoteItemsEntriesEditorField() {
const { items } = useCreditNoteFormContext();
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>
);
}

View File

@@ -0,0 +1,22 @@
// @ts-nocheck
import React from 'react';
import { BaseCurrency, BaseCurrencyRoot } from '@/components';
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
/**
* Credit note from currency tag.
* @returns
*/
export default function CreditNotetFormCurrencyTag() {
const { isForeignCustomer, selectCustomer } = useCreditNoteFormContext();
if (!isForeignCustomer) {
return null;
}
return (
<BaseCurrencyRoot>
<BaseCurrency currency={selectCustomer?.currency_code} />
</BaseCurrencyRoot>
);
}

View File

@@ -0,0 +1,30 @@
// @ts-nocheck
import React from 'react';
import { useFormikContext } from 'formik';
import { ExchangeRateInputGroup } from '@/components';
import { useCurrentOrganization } from '@/hooks/state';
import { useCreditNoteIsForeignCustomer } from './utils';
/**
* credit exchange rate input field.
* @returns {JSX.Element}
*/
export function CreditNoteExchangeRateInputField({ ...props }) {
const currentOrganization = useCurrentOrganization();
const { values } = useFormikContext();
const isForeignCustomer = useCreditNoteIsForeignCustomer();
// Can't continue if the customer is not foreign.
if (!isForeignCustomer) {
return null;
}
return (
<ExchangeRateInputGroup
fromCurrency={values.currency_code}
toCurrency={currentOrganization.base_currency}
{...props}
/>
);
}

View File

@@ -0,0 +1,218 @@
// @ts-nocheck
import React from 'react';
import moment from 'moment';
import * as R from 'ramda';
import { first } from 'lodash';
import {
defaultFastFieldShouldUpdate,
transformToForm,
repeatValue,
transactionNumber,
formattedAmount,
orderingLinesIndexes,
} from '@/utils';
import { useFormikContext } from 'formik';
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
import {
updateItemsEntriesTotal,
ensureEntriesHaveEmptyLine,
} from '@/containers/Entries/utils';
import { useCurrentOrganization } from '@/hooks/state';
import { getEntriesTotal } from '@/containers/Entries/utils';
export const MIN_LINES_NUMBER = 1;
// Default entry object.
export const defaultCreditNoteEntry = {
index: 0,
item_id: '',
rate: '',
discount: '',
quantity: '',
description: '',
amount: '',
};
// Default credit note object.
export const defaultCreditNote = {
customer_id: '',
credit_note_date: moment(new Date()).format('YYYY-MM-DD'),
credit_note_number: '',
credit_note_no_manually: false,
open: '',
reference_no: '',
note: '',
terms_conditions: '',
branch_id: '',
warehouse_id: '',
exchange_rate: 1,
currency_code: '',
entries: [...repeatValue(defaultCreditNoteEntry, MIN_LINES_NUMBER)],
};
/**
* Transform credit note to initial values in edit mode.
*/
export function transformToEditForm(creditNote) {
const initialEntries = [
...creditNote.entries.map((creditNote) => ({
...transformToForm(creditNote, defaultCreditNoteEntry),
})),
...repeatValue(
defaultCreditNoteEntry,
Math.max(MIN_LINES_NUMBER - creditNote.entries.length, 0),
),
];
const entries = R.compose(
ensureEntriesHaveEmptyLine(defaultCreditNoteEntry),
updateItemsEntriesTotal,
)(initialEntries);
return {
...transformToForm(creditNote, defaultCreditNote),
entries,
};
}
/**
* Transformes credit note entries to submit request.
*/
export const transformEntriesToSubmit = (entries) => {
const transformCreditNoteEntry = R.compose(
R.omit(['amount']),
R.curry(transformToForm)(R.__, defaultCreditNoteEntry),
);
return R.compose(
orderingLinesIndexes,
R.map(transformCreditNoteEntry),
)(entries);
};
/**
* Filters the givne non-zero entries.
*/
export const filterNonZeroEntries = (entries) => {
return entries.filter((item) => item.item_id && item.quantity);
};
/**
* Transformes form values to request body.
*/
export const transformFormValuesToRequest = (values) => {
const entries = filterNonZeroEntries(values.entries);
return {
...values,
entries: transformEntriesToSubmit(entries),
open: false,
};
};
/**
* Determines customer name field when should update.
*/
export const customerNameFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.customers !== oldProps.customers ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Determines invoice entries field when should update.
*/
export const entriesFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.items !== oldProps.items ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Syncs invoice no. settings with form.
*/
export const useObserveCreditNoSettings = (prefix, nextNumber) => {
const { setFieldValue } = useFormikContext();
React.useEffect(() => {
const creditNo = transactionNumber(prefix, nextNumber);
setFieldValue('credit_note_number', creditNo);
}, [setFieldValue, prefix, nextNumber]);
};
export const useSetPrimaryBranchToForm = () => {
const { setFieldValue } = useFormikContext();
const { branches, isBranchesSuccess } = useCreditNoteFormContext();
React.useEffect(() => {
if (isBranchesSuccess) {
const primaryBranch = branches.find((b) => b.primary) || first(branches);
if (primaryBranch) {
setFieldValue('branch_id', primaryBranch.id);
}
}
}, [isBranchesSuccess, setFieldValue, branches]);
};
export const useSetPrimaryWarehouseToForm = () => {
const { setFieldValue } = useFormikContext();
const { warehouses, isWarehousesSuccess } = useCreditNoteFormContext();
React.useEffect(() => {
if (isWarehousesSuccess) {
const primaryWarehouse =
warehouses.find((b) => b.primary) || first(warehouses);
if (primaryWarehouse) {
setFieldValue('warehouse_id', primaryWarehouse.id);
}
}
}, [isWarehousesSuccess, setFieldValue, warehouses]);
};
/**
* Retreives the credit note totals.
*/
export const useCreditNoteTotals = () => {
const {
values: { entries, currency_code: currencyCode },
} = useFormikContext();
// Retrieves the invoice entries total.
const total = React.useMemo(() => getEntriesTotal(entries), [entries]);
// Retrieves the formatted total money.
const formattedTotal = React.useMemo(
() => formattedAmount(total, currencyCode),
[total, currencyCode],
);
// Retrieves the formatted subtotal.
const formattedSubtotal = React.useMemo(
() => formattedAmount(total, currencyCode, { money: false }),
[total, currencyCode],
);
return {
total,
formattedTotal,
formattedSubtotal,
};
};
/**
* Detarmines whether the receipt has foreign customer.
* @returns {boolean}
*/
export const useCreditNoteIsForeignCustomer = () => {
const { values } = useFormikContext();
const currentOrganization = useCurrentOrganization();
const isForeignCustomer = React.useMemo(
() => values.currency_code !== currentOrganization.base_currency,
[values.currency_code, currentOrganization.base_currency],
);
return isForeignCustomer;
};

View File

@@ -0,0 +1,118 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import { MenuItem, Intent } from '@blueprintjs/core';
import { Icon, Choose, T, TextStatus } from '@/components';
import { RESOURCES_TYPES } from '@/constants/resourcesTypes';
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
import { AbilitySubject, CreditNoteAction } from '@/constants/abilityOption';
import { DRAWERS } from '@/constants/drawers';
/**
* Credit note universal search item select action.
*/
function CreditNoteUniversalSearchSelectComponent({
// #ownProps
resourceType,
resourceId,
onAction,
// #withDrawerActions
openDrawer,
}) {
if (resourceType === RESOURCES_TYPES.CREDIT_NOTE) {
openDrawer(DRAWERS.CREDIT_NOTE_DETAIL_DRAWER, { creditNoteId: resourceId });
onAction && onAction();
}
return null;
}
export const CreditNoteUniversalSearchSelect = withDrawerActions(
CreditNoteUniversalSearchSelectComponent,
);
/**
* Status accessor.
*/
function CreditNoteUniversalSearchStatus({ receipt }) {
return (
<Choose>
<Choose.When condition={receipt.is_closed}>
<TextStatus intent={Intent.SUCCESS}>
<T id={'closed'} />
</TextStatus>
</Choose.When>
<Choose.When condition={receipt.is_open}>
<TextStatus intent={Intent.WARNING}>
<T id={'open'} />
</TextStatus>
</Choose.When>
<Choose.Otherwise>
<TextStatus intent={Intent.NONE}>
<T id={'draft'} />
</TextStatus>
</Choose.Otherwise>
</Choose>
);
}
/**
* Credit note universal search item.
*/
export function CreditNoteUniversalSearchItem(
item,
{ handleClick, modifiers, query },
) {
return (
<MenuItem
active={modifiers.active}
text={
<div>
<div>{item.text}</div>
<span class="bp3-text-muted">
{item.reference.credit_note_number}{' '}
<Icon icon={'caret-right-16'} iconSize={16} />
{item.reference.formatted_credit_note_date}
</span>
</div>
}
label={
<>
<div class="amount">${item.reference.amount}</div>
<CreditNoteUniversalSearchStatus receipt={item.reference} />
</>
}
onClick={handleClick}
className={'universal-search__item--receipt'}
/>
);
}
/**
* Transformes receipt resource item to search item.
*/
const transformReceiptsToSearch = (creditNote) => ({
id: creditNote.id,
text: creditNote.customer.display_name,
label: creditNote.formatted_amount,
reference: creditNote,
});
/**
* Credit note universal search bind configuration.
*/
export const universalSearchCreditNoteBind = () => ({
resourceType: RESOURCES_TYPES.CREDIT_NOTE,
optionItemLabel: intl.get('credit_note.label'),
selectItemAction: CreditNoteUniversalSearchSelect,
itemRenderer: CreditNoteUniversalSearchItem,
itemSelect: transformReceiptsToSearch,
permission: {
ability: CreditNoteAction.View,
subject: AbilitySubject.CreditNote,
},
});

View File

@@ -0,0 +1,41 @@
// @ts-nocheck
import React from 'react';
const CreditNoteDeleteAlert = React.lazy(
() => import('@/containers/Alerts/CreditNotes/CreditNoteDeleteAlert'),
);
const RefundCreditNoteDeleteAlert = React.lazy(
() => import('@/containers/Alerts/CreditNotes/RefundCreditNoteDeleteAlert'),
);
const OpenCreditNoteAlert = React.lazy(
() => import('@/containers/Alerts/CreditNotes/CreditNoteOpenedAlert'),
);
const ReconcileCreditDeleteAlert = React.lazy(
() =>
import('@/containers/Alerts/CreditNotes/ReconcileCreditNoteDeleteAlert'),
);
/**
* Credit notes alerts.
*/
export default [
{
name: 'credit-note-delete',
component: CreditNoteDeleteAlert,
},
{
name: 'credit-note-open',
component: OpenCreditNoteAlert,
},
{
name: 'refund-credit-delete',
component: RefundCreditNoteDeleteAlert,
},
{
name: 'reconcile-credit-delete',
component: ReconcileCreditDeleteAlert,
},
];

View File

@@ -0,0 +1,147 @@
// @ts-nocheck
import React from 'react';
import {
Button,
Classes,
NavbarDivider,
NavbarGroup,
Alignment,
} from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import {
Icon,
Can,
FormattedMessage as T,
DashboardActionViewsList,
AdvancedFilterPopover,
DashboardFilterButton,
DashboardRowsHeightButton,
DashboardActionsBar,
} from '@/components';
import { useCreditNoteListContext } from './CreditNotesListProvider';
import { CreditNoteAction, AbilitySubject } from '@/constants/abilityOption';
import withCreditNotes from './withCreditNotes';
import withCreditNotesActions from './withCreditNotesActions';
import withSettings from '@/containers/Settings/withSettings';
import withSettingsActions from '@/containers/Settings/withSettingsActions';
import { compose } from '@/utils';
/**
* Credit note table actions bar.
*/
function CreditNotesActionsBar({
// #withCreditNotes
creditNoteFilterRoles,
// #withCreditNotesActions
setCreditNotesTableState,
// #withSettings
creditNoteTableSize,
// #withSettingsActions
addSetting,
}) {
const history = useHistory();
// credit note list context.
const { CreditNotesView, fields, refresh } = useCreditNoteListContext();
// Handle view tab change.
const handleTabChange = (view) => {
setCreditNotesTableState({ viewSlug: view ? view.slug : null });
};
// Handle click a new Credit.
const handleClickNewCreateNote = () => {
history.push('/credit-notes/new');
};
// Handle click a refresh credit note.
const handleRefreshBtnClick = () => {
refresh();
};
// Handle table row size change.
const handleTableRowSizeChange = (size) => {
addSetting('creditNote', 'tableSize', size);
};
return (
<DashboardActionsBar>
<NavbarGroup>
<DashboardActionViewsList
allMenuItem={true}
resourceName={'credit_notes'}
views={CreditNotesView}
onChange={handleTabChange}
/>
<NavbarDivider />
<Can I={CreditNoteAction.Create} a={AbilitySubject.CreditNote}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'plus'} />}
text={<T id={'credit_note.label.new_credit_note'} />}
onClick={handleClickNewCreateNote}
/>
</Can>
<AdvancedFilterPopover
advancedFilterProps={{
conditions: creditNoteFilterRoles,
defaultFieldKey: 'created_at',
fields: fields,
onFilterChange: (filterConditions) => {
setCreditNotesTableState({ filterRoles: filterConditions });
},
}}
>
<DashboardFilterButton
conditionsCount={creditNoteFilterRoles.length}
/>
</AdvancedFilterPopover>
<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'} />}
/>
<NavbarDivider />
<DashboardRowsHeightButton
initialValue={creditNoteTableSize}
onChange={handleTableRowSizeChange}
/>
<NavbarDivider />
</NavbarGroup>
<NavbarGroup align={Alignment.RIGHT}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon="refresh-16" iconSize={14} />}
onClick={handleRefreshBtnClick}
/>
</NavbarGroup>
</DashboardActionsBar>
);
}
export default compose(
withCreditNotesActions,
withSettingsActions,
withCreditNotes(({ creditNoteTableState }) => ({
creditNoteFilterRoles: creditNoteTableState.filterRoles,
})),
withSettings(({ creditNoteSettings }) => ({
creditNoteTableSize: creditNoteSettings?.tableSize,
})),
)(CreditNotesActionsBar);

View File

@@ -0,0 +1,161 @@
// @ts-nocheck
import React from 'react';
import { useHistory } from 'react-router-dom';
import { TABLES } from '@/constants/tables';
import {
DataTable,
DashboardContentTable,
TableSkeletonRows,
TableSkeletonHeader,
} from '@/components';
import { useMemorizedColumnsWidths } from '@/hooks';
import CreditNoteEmptyStatus from './CreditNotesEmptyStatus';
import withDashboardActions from '@/containers/Dashboard/withDashboardActions';
import withCreditNotesActions from './withCreditNotesActions';
import withAlertsActions from '@/containers/Alert/withAlertActions';
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import withSettings from '@/containers/Settings/withSettings';
import { useCreditNoteTableColumns, ActionsMenu } from './components';
import { useCreditNoteListContext } from './CreditNotesListProvider';
import { compose } from '@/utils';
/**
* Credit note data table.
*/
function CreditNotesDataTable({
// #withCreditNotesActions
setCreditNotesTableState,
// #withAlertsActions
openAlert,
// #withDrawerActions
openDrawer,
// #withDialogAction
openDialog,
// #withSettings
creditNoteTableSize,
}) {
const history = useHistory();
// Credit note list context.
const {
creditNotes,
pagination,
isEmptyStatus,
isCreditNotesFetching,
isCreditNotesLoading,
} = useCreditNoteListContext();
// Credit note table columns.
const columns = useCreditNoteTableColumns();
// Local storage memorizing columns widths.
const [initialColumnsWidths, , handleColumnResizing] =
useMemorizedColumnsWidths(TABLES.CREDIT_NOTES);
// Handles fetch data once the table state change.
const handleDataTableFetchData = React.useCallback(
({ pageSize, pageIndex, sortBy }) => {
setCreditNotesTableState({
pageSize,
pageIndex,
sortBy,
});
},
[setCreditNotesTableState],
);
// Display create note empty status instead of the table.
if (isEmptyStatus) {
return <CreditNoteEmptyStatus />;
}
const handleViewDetailCreditNote = ({ id }) => {
openDrawer('credit-note-detail-drawer', { creditNoteId: id });
};
// Handle delete credit note.
const handleDeleteCreditNote = ({ id }) => {
openAlert('credit-note-delete', { creditNoteId: id });
};
// Handle edit credit note.
const hanldeEditCreditNote = (creditNote) => {
history.push(`/credit-notes/${creditNote.id}/edit`);
};
// Handle cell click.
const handleCellClick = (cell, event) => {
openDrawer('credit-note-detail-drawer', {
creditNoteId: cell.row.original.id,
});
};
const handleRefundCreditNote = ({ id }) => {
openDialog('refund-credit-note', { creditNoteId: id });
};
// Handle cancel/confirm crdit note open.
const handleOpenCreditNote = ({ id }) => {
openAlert('credit-note-open', { creditNoteId: id });
};
// Handle reconcile credit note.
const handleReconcileCreditNote = ({ id }) => {
openDialog('reconcile-credit-note', { creditNoteId: id });
};
return (
<DashboardContentTable>
<DataTable
columns={columns}
data={creditNotes}
loading={isCreditNotesLoading}
headerLoading={isCreditNotesLoading}
progressBarLoading={isCreditNotesFetching}
onFetchData={handleDataTableFetchData}
manualSortBy={true}
selectionColumn={true}
noInitialFetch={true}
sticky={true}
pagination={true}
pagesCount={pagination.pagesCount}
TableLoadingRenderer={TableSkeletonRows}
TableHeaderSkeletonRenderer={TableSkeletonHeader}
ContextMenu={ActionsMenu}
onCellClick={handleCellClick}
initialColumnsWidths={initialColumnsWidths}
onColumnResizing={handleColumnResizing}
size={creditNoteTableSize}
payload={{
onViewDetails: handleViewDetailCreditNote,
onDelete: handleDeleteCreditNote,
onEdit: hanldeEditCreditNote,
onRefund: handleRefundCreditNote,
onOpen: handleOpenCreditNote,
onReconcile: handleReconcileCreditNote,
}}
/>
</DashboardContentTable>
);
}
export default compose(
withDashboardActions,
withCreditNotesActions,
withDrawerActions,
withAlertsActions,
withDialogActions,
withSettings(({ creditNoteSettings }) => ({
creditNoteTableSize: creditNoteSettings?.tableSize,
})),
)(CreditNotesDataTable);

View File

@@ -0,0 +1,37 @@
// @ts-nocheck
import React from 'react';
import { Button, Intent } from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import { EmptyStatus, Can, FormattedMessage as T } from '@/components';
import { CreditNoteAction, AbilitySubject } from '@/constants/abilityOption';
export default function CreditNotesEmptyStatus() {
const history = useHistory();
return (
<EmptyStatus
title={<T id={'credit_note.empty_status.title'} />}
description={
<p>
<T id={'credit_note.empty_status.description'} />
</p>
}
action={
<>
<Can I={CreditNoteAction.Create} a={AbilitySubject.CreditNote}>
<Button
intent={Intent.PRIMARY}
large={true}
onClick={() => history.push('/credit-notes/new')}
>
<T id={'credit_note.label.new_credit_note'} />
</Button>
<Button intent={Intent.NONE} large={true}>
<T id={'learn_more'} />
</Button>
</Can>
</>
}
/>
);
}

View File

@@ -0,0 +1,53 @@
// @ts-nocheck
import React from 'react';
import '@/style/pages/CreditNote/List.scss';
import { DashboardPageContent } from '@/components';
import CreditNotesActionsBar from './CreditNotesActionsBar';
import CreditNotesViewTabs from './CreditNotesViewTabs';
import CreditNotesDataTable from './CreditNotesDataTable';
import withCreditNotes from './withCreditNotes';
import withCreditNotesActions from './withCreditNotesActions';
import { CreditNotesListProvider } from './CreditNotesListProvider';
import { transformTableStateToQuery, compose } from '@/utils';
function CreditNotesList({
// #withCreditNotes
creditNoteTableState,
creditNoteTableStateChanged,
// #withCreditNotesActions
resetCreditNotesTableState,
}) {
// Resets the credit note table state once the page unmount.
React.useEffect(
() => () => {
resetCreditNotesTableState();
},
[resetCreditNotesTableState],
);
return (
<CreditNotesListProvider
query={transformTableStateToQuery(creditNoteTableState)}
tableStateChanged={creditNoteTableStateChanged}
>
<CreditNotesActionsBar />
<DashboardPageContent>
<CreditNotesViewTabs />
<CreditNotesDataTable />
</DashboardPageContent>
</CreditNotesListProvider>
);
}
export default compose(
withCreditNotesActions,
withCreditNotes(({ creditNoteTableState, creditNoteTableStateChanged }) => ({
creditNoteTableState,
creditNoteTableStateChanged,
})),
)(CreditNotesList);

View File

@@ -0,0 +1,77 @@
// @ts-nocheck
import React from 'react';
import { isEmpty } from 'lodash';
import { DashboardInsider } from '@/components/Dashboard';
import {
useResourceViews,
useResourceMeta,
useCreditNotes,
useRefreshCreditNotes,
} from '@/hooks/query';
import { getFieldsFromResourceMeta } from '@/utils';
const CreditNoteListContext = React.createContext();
/**
* Credit note data provider.
*/
function CreditNotesListProvider({ query, tableStateChanged, ...props }) {
// Credit notes refresh action.
const { refresh } = useRefreshCreditNotes();
// Fetch create notes resource views and fields.
const { data: CreditNotesView, isLoading: isViewsLoading } =
useResourceViews('credit_notes');
// Fetch the accounts resource fields.
const {
data: resourceMeta,
isLoading: isResourceLoading,
isFetching: isResourceFetching,
} = useResourceMeta('credit_notes');
// Fetch credit note list.
const {
data: { creditNotes, pagination, filterMeta },
isFetching: isCreditNotesFetching,
isLoading: isCreditNotesLoading,
} = useCreditNotes(query, { keepPreviousData: true });
// Detarmines the datatable empty status.S
const isEmptyStatus =
isEmpty(creditNotes) && !isCreditNotesLoading && !tableStateChanged;
// Provider payload.
const provider = {
creditNotes,
pagination,
CreditNotesView,
refresh,
resourceMeta,
fields: getFieldsFromResourceMeta(resourceMeta.fields),
isResourceLoading,
isResourceFetching,
isCreditNotesFetching,
isCreditNotesLoading,
isViewsLoading,
isEmptyStatus,
};
return (
<DashboardInsider
loading={isViewsLoading || isResourceLoading}
name={'credit-notes-list'}
>
<CreditNoteListContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const useCreditNoteListContext = () => React.useContext(CreditNoteListContext);
export { CreditNotesListProvider, useCreditNoteListContext };

View File

@@ -0,0 +1,51 @@
// @ts-nocheck
import React from 'react';
import { Alignment, Navbar, NavbarGroup } from '@blueprintjs/core';
import { DashboardViewsTabs } from '@/components';
import { compose, transfromViewsToTabs } from '@/utils';
import { useCreditNoteListContext } from './CreditNotesListProvider';
import withCreditNotes from './withCreditNotes';
import withCreditNotesActions from './withCreditNotesActions';
/**
* Credit Note views tabs.
*/
function CreditNotesViewTabs({
// #withCreditNotes
creditNoteCurrentView,
// #withCreditNotesActions
setCreditNotesTableState,
}) {
// Credit note list context.
const { CreditNotesView } = useCreditNoteListContext();
const tabs = transfromViewsToTabs(CreditNotesView);
// Handle tab change.
const handleTabsChange = (viewSlug) => {
setCreditNotesTableState({ viewSlug });
};
return (
<Navbar className={'navbar--dashboard-views'}>
<NavbarGroup align={Alignment.LEFT}>
<DashboardViewsTabs
currentViewSlug={creditNoteCurrentView}
resourceName={'credit_notes'}
tabs={tabs}
onChange={handleTabsChange}
/>
</NavbarGroup>
</Navbar>
);
}
export default compose(
withCreditNotesActions,
withCreditNotes(({ creditNoteTableState }) => ({
creditNoteCurrentView: creditNoteTableState.viewSlug,
})),
)(CreditNotesViewTabs);

View File

@@ -0,0 +1,180 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import clsx from 'classnames';
import { Intent, Tag, Menu, MenuItem, MenuDivider } from '@blueprintjs/core';
import { CLASSES } from '@/constants/classes';
import {
FormatDateCell,
FormattedMessage as T,
Choose,
If,
Icon,
Can,
} from '@/components';
import { safeCallback } from '@/utils';
import { CreditNoteAction, AbilitySubject } from '@/constants/abilityOption';
export function ActionsMenu({
payload: { onEdit, onDelete, onRefund, onOpen, onReconcile, onViewDetails },
row: { original },
}) {
return (
<Menu>
<MenuItem
icon={<Icon icon="reader-18" />}
text={intl.get('view_details')}
onClick={safeCallback(onViewDetails, original)}
/>
<Can I={CreditNoteAction.Edit} a={AbilitySubject.CreditNote}>
<MenuDivider />
<MenuItem
icon={<Icon icon="pen-18" />}
text={intl.get('credit_note.action.edit_credit_note')}
onClick={safeCallback(onEdit, original)}
/>
<If condition={original.is_draft}>
<MenuItem
icon={<Icon icon={'check'} iconSize={18} />}
text={intl.get('credit_note.action.make_as_open')}
onClick={safeCallback(onOpen, original)}
/>
</If>
</Can>
<Can I={CreditNoteAction.Refund} a={AbilitySubject.CreditNote}>
<If condition={!original.is_closed && original.is_published}>
<MenuItem
icon={<Icon icon="quick-payment-16" />}
text={intl.get('credit_note.action.refund_credit_note')}
onClick={safeCallback(onRefund, original)}
/>
</If>
</Can>
<Can I={CreditNoteAction.Edit} a={AbilitySubject.CreditNote}>
<If condition={!original.is_closed && original.is_published}>
<MenuItem
text={intl.get('credit_note.action.reconcile_with_invoices')}
icon={<Icon icon="receipt-24" iconSize={16} />}
onClick={safeCallback(onReconcile, original)}
/>
</If>
</Can>
<Can I={CreditNoteAction.Delete} a={AbilitySubject.CreditNote}>
<MenuDivider />
<MenuItem
text={intl.get('credit_note.action.delete_credit_note')}
intent={Intent.DANGER}
onClick={safeCallback(onDelete, original)}
icon={<Icon icon="trash-16" iconSize={16} />}
/>
</Can>
</Menu>
);
}
/**
* Status accessor.
*/
export function StatusAccessor(creditNote) {
return (
<div>
<Choose>
<Choose.When condition={creditNote.is_open}>
<Tag intent={Intent.WARNING} minimal={true} round={true}>
<T id={'open'} />
</Tag>
</Choose.When>
<Choose.When condition={creditNote.is_closed}>
<Tag intent={Intent.SUCCESS} minimal={true} round={true}>
<T id={'closed'} />
</Tag>
</Choose.When>
<Choose.When condition={creditNote.is_draft}>
<Tag intent={Intent.NONE} minimal={true} round={true}>
<T id={'draft'} />
</Tag>
</Choose.When>
</Choose>
</div>
);
}
/**
* Retrieve credit note table columns.
*/
export function useCreditNoteTableColumns() {
return React.useMemo(
() => [
{
id: 'credit_date',
Header: intl.get('credit_note.column.credit_date'),
accessor: 'formatted_credit_note_date',
Cell: FormatDateCell,
width: 110,
className: 'credit_date',
clickable: true,
textOverview: true,
},
{
id: 'customer',
Header: intl.get('customer_name'),
accessor: 'customer.display_name',
width: 180,
className: 'customer',
clickable: true,
textOverview: true,
},
{
id: 'credit_number',
Header: intl.get('credit_note.column.credit_note_no'),
accessor: 'credit_note_number',
width: 100,
className: 'credit_number',
clickable: true,
textOverview: true,
},
{
id: 'amount',
Header: intl.get('amount'),
accessor: 'formatted_amount',
width: 120,
align: 'right',
clickable: true,
textOverview: true,
className: clsx(CLASSES.FONT_BOLD),
},
{
id: 'balance',
Header: intl.get('balance'),
accessor: 'formatted_credits_remaining',
width: 120,
align: 'right',
clickable: true,
textOverview: true,
disableSortBy: true,
className: clsx(CLASSES.FONT_BOLD),
},
{
id: 'status',
Header: intl.get('status'),
accessor: StatusAccessor,
width: 160, // 160
className: 'status',
clickable: true,
},
{
id: 'reference_no',
Header: intl.get('reference_no'),
accessor: 'reference_no', // or note
width: 90,
className: 'reference_no',
clickable: true,
textOverview: true,
},
],
[],
);
}

View File

@@ -0,0 +1,30 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import { Intent } from '@blueprintjs/core';
import { AppToaster } from '@/components';
export const handleDeleteErrors = (errors) => {
if (
errors.find((error) => error.type === 'CREDIT_NOTE_HAS_APPLIED_INVOICES')
) {
AppToaster.show({
message: intl.get(
'credit_note.error.you_couldn_t_delete_credit_note_that_has_associated_invoice',
),
intent: Intent.DANGER,
});
}
if (
errors.find(
(error) => error.type === 'CREDIT_NOTE_HAS_REFUNDS_TRANSACTIONS',
)
) {
AppToaster.show({
message: intl.get(
'credit_note.error.you_couldn_t_delete_credit_note_that_has_associated_refund',
),
intent: Intent.DANGER,
});
}
};

View File

@@ -0,0 +1,20 @@
// @ts-nocheck
import { connect } from 'react-redux';
import {
getCreditNotesTableStateFactory,
isCreditNotesTableStateChangedFactory,
} from '@/store/CreditNote/creditNote.selector';
export default (mapState) => {
const getCreditNoteTableState = getCreditNotesTableStateFactory();
const isCreditNoteTableChanged = isCreditNotesTableStateChangedFactory();
const mapStateToProps = (state, props) => {
const mapped = {
creditNoteTableState: getCreditNoteTableState(state, props),
creditNoteTableStateChanged: isCreditNoteTableChanged(state, props),
};
return mapState ? mapState(mapped, state, props) : mapped;
};
return connect(mapStateToProps);
};

View File

@@ -0,0 +1,14 @@
// @ts-nocheck
import { connect } from 'react-redux';
import {
setCreditNoteTableState,
resetCreditNoteTableState,
} from '@/store/CreditNote/creditNote.actions';
const mapDipatchToProps = (dispatch) => ({
setCreditNotesTableState: (queries) =>
dispatch(setCreditNoteTableState(queries)),
resetCreditNotesTableState: () => dispatch(resetCreditNoteTableState()),
});
export default connect(null, mapDipatchToProps);

View File

@@ -0,0 +1,193 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import {
Intent,
Button,
ButtonGroup,
Popover,
PopoverInteractionKind,
Position,
Menu,
MenuItem,
} from '@blueprintjs/core';
import { If, Icon, FormattedMessage as T } from '@/components';
import { CLASSES } from '@/constants/classes';
import { useHistory } from 'react-router-dom';
import { useFormikContext } from 'formik';
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}
style={{ minWidth: '85px' }}
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>
);
}

View File

@@ -0,0 +1,61 @@
// @ts-nocheck
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import moment from 'moment';
import { DATATYPES_LENGTH } from '@/constants/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()
.min(Yup.ref('estimate_date'), ({ path, min }) =>
intl.get('estimate.validation.expiration_date', {
path,
min: moment(min).format('YYYY/MM/DD'),
}),
)
.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(),
branch_id: Yup.string(),
warehouse_id: Yup.string(),
exchange_rate: Yup.number(),
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;

View File

@@ -0,0 +1,178 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { Formik, Form } from 'formik';
import { Intent } from '@blueprintjs/core';
import { sumBy, isEmpty } from 'lodash';
import { useHistory } from 'react-router-dom';
import { CLASSES } from '@/constants/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 EstimtaeFormTopBar from './EstimtaeFormTopBar';
import withSettings from '@/containers/Settings/withSettings';
import withCurrentOrganization from '@/containers/Organization/withCurrentOrganization';
import { AppToaster } from '@/components';
import { compose, transactionNumber, orderingLinesIndexes } from '@/utils';
import { useEstimateFormContext } from './EstimateFormProvider';
import {
transformToEditForm,
defaultEstimate,
transfromsFormValuesToRequest,
handleErrors,
} 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) }
: {
...defaultEstimate,
...(estimateIncrementMode && {
estimate_number: estimateNumber,
}),
entries: orderingLinesIndexes(defaultEstimate.entries),
currency_code: base_currency,
}),
}),
[estimate, estimateNumber, estimateIncrementMode, base_currency],
);
// 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 = {
...transfromsFormValuesToRequest(values),
delivered: submitPayload.deliver,
};
// Handle the request success.
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();
}
};
// Handle the request error.
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>
<EstimtaeFormTopBar />
<EstimateFormHeader />
<EstimateItemsEntriesField />
<EstimateFormFooter />
<EstimateFloatingActions />
<EstimateFormDialogs />
</Form>
</Formik>
</div>
);
}
export default compose(
withSettings(({ estimatesSettings }) => ({
estimateNextNumber: estimatesSettings?.nextNumber,
estimateNumberPrefix: estimatesSettings?.numberPrefix,
estimateIncrementMode: estimatesSettings?.autoIncrement,
})),
withCurrentOrganization(),
)(EstimateForm);

View File

@@ -0,0 +1,22 @@
// @ts-nocheck
import React from 'react';
import { BaseCurrency, BaseCurrencyRoot } from '@/components';
import { useEstimateFormContext } from './EstimateFormProvider';
/**
* Estimate form currency tag.
* @returns
*/
export default function EstimateFromCurrencyTag() {
const { isForeignCustomer, selectCustomer } = useEstimateFormContext();
if (!isForeignCustomer) {
return null;
}
return (
<BaseCurrencyRoot>
<BaseCurrency currency={selectCustomer?.currency_code} />
</BaseCurrencyRoot>
);
}

View File

@@ -0,0 +1,26 @@
// @ts-nocheck
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}
/>
</>
);
}

View File

@@ -0,0 +1,34 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import styled from 'styled-components';
import { CLASSES } from '@/constants/classes';
import { Row, Col, Paper } from '@/components';
import { EstimateFormFooterLeft } from './EstimateFormFooterLeft';
import { EstimateFormFooterRight } from './EstimateFormFooterRight';
/**
* Estimate form footer.
*/
export default function EstiamteFormFooter() {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<EstimateFooterPaper>
<Row>
<Col md={8}>
<EstimateFormFooterLeft />
</Col>
<Col md={4}>
<EstimateFormFooterRight />
</Col>
</Row>
</EstimateFooterPaper>
</div>
);
}
const EstimateFooterPaper = styled(Paper)`
padding: 20px;
`;

View File

@@ -0,0 +1,60 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import styled from 'styled-components';
import { FFormGroup, FEditableText, FormattedMessage as T } from '@/components';
export function EstimateFormFooterLeft() {
return (
<React.Fragment>
{/* --------- Customer Note --------- */}
<EstimateMsgFormGroup
name={'note'}
label={<T id={'estimate_form.label.customer_note'} />}
hintText={'Will be displayed on the invoice'}
>
<FEditableText
name={'note'}
placeholder={intl.get('estimate_form.customer_note.placeholder')}
/>
</EstimateMsgFormGroup>
{/* --------- Terms and conditions --------- */}
<TermsConditsFormGroup
label={<T id={'estimate_form.label.terms_conditions'} />}
name={'terms_conditions'}
>
<FEditableText
name={'terms_conditions'}
placeholder={intl.get('estimate_form.terms_and_conditions.placeholder')}
/>
</TermsConditsFormGroup>
</React.Fragment>
);
}
const EstimateMsgFormGroup = styled(FFormGroup)`
&.bp3-form-group {
margin-bottom: 40px;
.bp3-label {
font-size: 12px;
margin-bottom: 12px;
}
.bp3-form-content {
margin-left: 10px;
}
}
`;
const TermsConditsFormGroup = styled(FFormGroup)`
&.bp3-form-group {
.bp3-label {
font-size: 12px;
margin-bottom: 12px;
}
.bp3-form-content {
margin-left: 10px;
}
}
`;

View File

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

View File

@@ -0,0 +1,35 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { useFormikContext } from 'formik';
import { CLASSES } from '@/constants/classes';
import EstimateFormHeaderFields from './EstimateFormHeaderFields';
import { getEntriesTotal } from '@/containers/Entries/utils';
import { PageFormBigNumber } from '@/components';
// Estimate form top header.
function EstimateFormHeader() {
const {
values: { entries, currency_code },
} = useFormikContext();
// Calculate the total due amount of bill entries.
const totalDueAmount = useMemo(() => getEntriesTotal(entries), [entries]);
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<EstimateFormHeaderFields />
<PageFormBigNumber
label={intl.get('amount')}
amount={totalDueAmount}
currencyCode={currency_code}
/>
</div>
);
}
export default EstimateFormHeader;

View File

@@ -0,0 +1,261 @@
// @ts-nocheck
import React from 'react';
import styled from 'styled-components';
import classNames from 'classnames';
import {
FormGroup,
InputGroup,
Position,
Classes,
ControlGroup,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FeatureCan, FFormGroup, FormattedMessage as T } from '@/components';
import { FastField, Field, ErrorMessage } from 'formik';
import {
momentFormatter,
compose,
tansformDateValue,
inputIntent,
handleDateChange,
} from '@/utils';
import { customersFieldShouldUpdate } from './utils';
import { CLASSES } from '@/constants/classes';
import { Features } from '@/constants';
import {
CustomerSelectField,
FieldRequiredHint,
Icon,
InputPrependButton,
CustomerDrawerLink,
} from '@/components';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import withSettings from '@/containers/Settings/withSettings';
import { ProjectsSelect } from '@/containers/Projects/components';
import {
EstimateExchangeRateInputField,
EstimateProjectSelectButton,
} from './components';
import { useObserveEstimateNoSettings } from './utils';
import { useEstimateFormContext } from './EstimateFormProvider';
/**
* Estimate form header.
*/
function EstimateFormHeader({
// #withDialogActions
openDialog,
// #withSettings
estimateAutoIncrement,
estimateNumberPrefix,
estimateNextNumber,
}) {
const { customers, projects } = 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'} />}
>
<CustomerSelectField
contacts={customers}
selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={(customer) => {
form.setFieldValue('customer_id', customer.id);
form.setFieldValue('currency_code', customer?.currency_code);
}}
popoverFill={true}
intent={inputIntent({ error, touched })}
allowCreate={true}
/>
{value && (
<CustomerButtonLink customerId={value}>
<T id={'view_customer_details'} />
</CustomerButtonLink>
)}
</FormGroup>
)}
</FastField>
{/* ----------- Exchange rate ----------- */}
<EstimateExchangeRateInputField
name={'exchange_rate'}
formGroupProps={{ label: ' ', inline: true }}
/>
{/* ----------- 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'} />}
labelInfo={<FieldRequiredHint />}
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 ----------- */}
<Field 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>
)}
</Field>
{/* ----------- 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>
{/*------------ Project name -----------*/}
<FeatureCan feature={Features.Projects}>
<FFormGroup
name={'project_id'}
label={<T id={'estimate.project_name.label'} />}
inline={true}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ProjectsSelect
name={'project_id'}
projects={projects}
input={EstimateProjectSelectButton}
popoverFill={true}
/>
</FFormGroup>
</FeatureCan>
</div>
);
}
export default compose(
withDialogActions,
withSettings(({ estimatesSettings }) => ({
estimateNextNumber: estimatesSettings?.nextNumber,
estimateNumberPrefix: estimatesSettings?.numberPrefix,
estimateAutoIncrement: estimatesSettings?.autoIncrement,
})),
)(EstimateFormHeader);
const CustomerButtonLink = styled(CustomerDrawerLink)`
font-size: 11px;
margin-top: 6px;
`;

View File

@@ -0,0 +1,22 @@
// @ts-nocheck
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>
);
}

View File

@@ -0,0 +1,129 @@
// @ts-nocheck
import React, { createContext, useContext } from 'react';
import { DashboardInsider } from '@/components/Dashboard';
import {
useEstimate,
useCustomers,
useWarehouses,
useBranches,
useItems,
useSettingsEstimates,
useCreateEstimate,
useEditEstimate,
} from '@/hooks/query';
import { Features } from '@/constants';
import { useProjects } from '@/containers/Projects/hooks';
import { useFeatureCan } from '@/hooks/state';
import { ITEMS_FILTER_ROLES } from './utils';
const EstimateFormContext = createContext();
/**
* Estimate form provider.
*/
function EstimateFormProvider({ query, estimateId, ...props }) {
// Features guard.
const { featureCan } = useFeatureCan();
const isWarehouseFeatureCan = featureCan(Features.Warehouses);
const isBranchFeatureCan = featureCan(Features.Branches);
const isProjectsFeatureCan = featureCan(Features.Projects);
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 },
isLoading: isCustomersLoading,
} = useCustomers({ page_size: 10000 });
// Fetch warehouses list.
const {
data: warehouses,
isLoading: isWarehouesLoading,
isSuccess: isWarehousesSuccess,
} = useWarehouses(query, { enabled: isWarehouseFeatureCan });
// Fetches the branches list.
const {
data: branches,
isLoading: isBranchesLoading,
isSuccess: isBranchesSuccess,
} = useBranches(query, { enabled: isBranchFeatureCan });
// Fetches the projects list.
const {
data: { projects },
isLoading: isProjectsLoading,
} = useProjects({}, { enabled: !!isProjectsFeatureCan });
// 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;
// Determines whether the warehouse and branches are loading.
const isFeatureLoading =
isWarehouesLoading || isBranchesLoading || isProjectsLoading;
// Provider payload.
const provider = {
estimateId,
estimate,
items,
customers,
branches,
warehouses,
projects,
isNewMode,
isItemsFetching,
isEstimateFetching,
isCustomersLoading,
isItemsLoading,
isEstimateLoading,
isFeatureLoading,
isBranchesSuccess,
isWarehousesSuccess,
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 };

View File

@@ -0,0 +1,42 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import { FastField } from 'formik';
import { CLASSES } from '@/constants/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>
);
}

View File

@@ -0,0 +1,115 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import {
Alignment,
NavbarGroup,
NavbarDivider,
Button,
Classes,
} from '@blueprintjs/core';
import {
useSetPrimaryBranchToForm,
useSetPrimaryWarehouseToForm,
} from './utils';
import { Features } from '@/constants';
import { useFeatureCan } from '@/hooks/state';
import {
Icon,
BranchSelect,
FeatureCan,
WarehouseSelect,
FormTopbar,
DetailsBarSkeletonBase,
} from '@/components';
import { useEstimateFormContext } from './EstimateFormProvider';
/**
* Estimate form topbar .
* @returns {JSX.Element}
*/
export default function EstimtaeFormTopBar() {
// Features guard.
const { featureCan } = useFeatureCan();
// Sets the primary warehouse to form.
useSetPrimaryWarehouseToForm();
// Sets the primary branch to form.
useSetPrimaryBranchToForm();
// Can't display the navigation bar if warehouses or branches feature is not enabled.
if (!featureCan(Features.Warehouses) && !featureCan(Features.Branches)) {
return null;
}
return (
<FormTopbar>
<NavbarGroup align={Alignment.LEFT}>
<FeatureCan feature={Features.Branches}>
<EstimateFormSelectBranch />
</FeatureCan>
{featureCan(Features.Warehouses) && featureCan(Features.Branches) && (
<NavbarDivider />
)}
<FeatureCan feature={Features.Warehouses}>
<EstimateFormSelectWarehouse />
</FeatureCan>
</NavbarGroup>
</FormTopbar>
);
}
function EstimateFormSelectBranch() {
// Estimate form context.
const { branches, isBranchesLoading } = useEstimateFormContext();
return isBranchesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<BranchSelect
name={'branch_id'}
branches={branches}
input={EstimateBranchSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function EstimateFormSelectWarehouse() {
// Estimate form context.
const { warehouses, isWarehouesLoading } = useEstimateFormContext();
return isWarehouesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<WarehouseSelect
name={'warehouse_id'}
warehouses={warehouses}
input={EstimateWarehouseSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function EstimateWarehouseSelectButton({ label }) {
return (
<Button
text={intl.get('estimate.warehouse_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'warehouse-16'} iconSize={16} />}
/>
);
}
function EstimateBranchSelectButton({ label }) {
return (
<Button
text={intl.get('estimate.branch_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'branch-16'} iconSize={16} />}
/>
);
}

View File

@@ -0,0 +1,40 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import { Button } from '@blueprintjs/core';
import { useFormikContext } from 'formik';
import { ExchangeRateInputGroup } from '@/components';
import { useCurrentOrganization } from '@/hooks/state';
import { useEstimateIsForeignCustomer } from './utils';
/**
* Estimate exchange rate input field.
* @returns {JSX.Element}
*/
export function EstimateExchangeRateInputField({ ...props }) {
const currentOrganization = useCurrentOrganization();
const { values } = useFormikContext();
const isForeignCustomer = useEstimateIsForeignCustomer();
// Can't continue if the customer is not foreign.
if (!isForeignCustomer) {
return null;
}
return (
<ExchangeRateInputGroup
fromCurrency={values.currency_code}
toCurrency={currentOrganization.base_currency}
{...props}
/>
);
}
/**
* Estimate project select.
* @returns {JSX.Element}
*/
export function EstimateProjectSelectButton({ label }) {
return <Button text={label ?? intl.get('select_project')} />;
}

View File

@@ -0,0 +1,237 @@
// @ts-nocheck
import React from 'react';
import * as R from 'ramda';
import intl from 'react-intl-universal';
import moment from 'moment';
import { useFormikContext } from 'formik';
import { omit, first } from 'lodash';
import {
defaultFastFieldShouldUpdate,
transactionNumber,
repeatValue,
transformToForm,
formattedAmount,
} from '@/utils';
import { useEstimateFormContext } from './EstimateFormProvider';
import {
updateItemsEntriesTotal,
ensureEntriesHaveEmptyLine,
} from '@/containers/Entries/utils';
import { useCurrentOrganization } from '@/hooks/state';
import { getEntriesTotal } from '@/containers/Entries/utils';
export const MIN_LINES_NUMBER = 1;
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: '',
branch_id: '',
warehouse_id: '',
exchange_rate: 1,
currency_code: '',
entries: [...repeatValue(defaultEstimateEntry, MIN_LINES_NUMBER)],
};
const ERRORS = {
ESTIMATE_NUMBER_IS_NOT_UNQIUE: 'ESTIMATE.NUMBER.IS.NOT.UNQIUE',
SALE_ESTIMATE_NO_IS_REQUIRED: 'SALE_ESTIMATE_NO_IS_REQUIRED',
};
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',
},
]);
/**
* Transform response errors to fields.
* @param {*} errors
* @param {*} param1
*/
export const handleErrors = (errors, { setErrors }) => {
if (errors.some((e) => e.type === ERRORS.ESTIMATE_NUMBER_IS_NOT_UNQIUE)) {
setErrors({
estimate_number: intl.get('estimate_number_is_not_unqiue'),
});
}
if (
errors.some((error) => error.type === ERRORS.SALE_ESTIMATE_NO_IS_REQUIRED)
) {
setErrors({
estimate_number: intl.get(
'estimate.field.error.estimate_number_required',
),
});
}
};
/**
* Transform the form values to request body.
*/
export const transfromsFormValuesToRequest = (values) => {
const entries = values.entries.filter(
(item) => item.item_id && item.quantity,
);
return {
...omit(values, ['estimate_number_manually', 'estimate_number']),
...(values.estimate_number_manually && {
estimate_number: values.estimate_number,
}),
entries: entries.map((entry) => ({ ...omit(entry, ['amount']) })),
};
};
export const useSetPrimaryWarehouseToForm = () => {
const { setFieldValue } = useFormikContext();
const { warehouses, isWarehousesSuccess } = useEstimateFormContext();
React.useEffect(() => {
if (isWarehousesSuccess) {
const primaryWarehouse =
warehouses.find((b) => b.primary) || first(warehouses);
if (primaryWarehouse) {
setFieldValue('warehouse_id', primaryWarehouse.id);
}
}
}, [isWarehousesSuccess, setFieldValue, warehouses]);
};
export const useSetPrimaryBranchToForm = () => {
const { setFieldValue } = useFormikContext();
const { branches, isBranchesSuccess } = useEstimateFormContext();
React.useEffect(() => {
if (isBranchesSuccess) {
const primaryBranch = branches.find((b) => b.primary) || first(branches);
if (primaryBranch) {
setFieldValue('branch_id', primaryBranch.id);
}
}
}, [isBranchesSuccess, setFieldValue, branches]);
};
/**
* Retreives the estimate totals.
*/
export const useEstimateTotals = () => {
const {
values: { entries, currency_code: currencyCode },
} = useFormikContext();
// Retrieves the invoice entries total.
const total = React.useMemo(() => getEntriesTotal(entries), [entries]);
// Retrieves the formatted total money.
const formattedTotal = React.useMemo(
() => formattedAmount(total, currencyCode),
[total, currencyCode],
);
// Retrieves the formatted subtotal.
const formattedSubtotal = React.useMemo(
() => formattedAmount(total, currencyCode, { money: false }),
[total, currencyCode],
);
return {
total,
formattedTotal,
formattedSubtotal,
};
};
/**
* Detarmines whether the estimate has foreign customer.
* @returns {boolean}
*/
export const useEstimateIsForeignCustomer = () => {
const { values } = useFormikContext();
const currentOrganization = useCurrentOrganization();
const isForeignCustomer = React.useMemo(
() => values.currency_code !== currentOrganization.base_currency,
[values.currency_code, currentOrganization.base_currency],
);
return isForeignCustomer;
};

View File

@@ -0,0 +1,37 @@
// @ts-nocheck
import React from 'react';
const EstimateDeleteAlert = React.lazy(
() => import('@/containers/Alerts/Estimates/EstimateDeleteAlert'),
);
const EstimateDeliveredAlert = React.lazy(
() => import('@/containers/Alerts/Estimates/EstimateDeliveredAlert'),
);
const EstimateApproveAlert = React.lazy(
() => import('@/containers/Alerts/Estimates/EstimateApproveAlert'),
);
const EstimateRejectAlert = React.lazy(
() => import('@/containers/Alerts/Estimates/EstimateRejectAlert'),
);
/**
* Estimates alert.
*/
export default [
{
name: 'estimate-delete',
component: EstimateDeleteAlert,
},
{
name: 'estimate-deliver',
component: EstimateDeliveredAlert,
},
{
name: 'estimate-Approve',
component: EstimateApproveAlert,
},
{
name: 'estimate-reject',
component: EstimateRejectAlert,
},
];

View File

@@ -0,0 +1,120 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import { MenuItem } from '@blueprintjs/core';
import { Choose, T, Icon } from '@/components';
import { RESOURCES_TYPES } from '@/constants/resourcesTypes';
import { AbilitySubject, SaleEstimateAction } from '@/constants/abilityOption';
import withDrawerActions from '@/containers/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,
permission: {
ability: SaleEstimateAction.View,
subject: AbilitySubject.Estimate,
},
});

View File

@@ -0,0 +1,167 @@
// @ts-nocheck
import React from 'react';
import {
Button,
Classes,
NavbarDivider,
NavbarGroup,
Intent,
Alignment,
} from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import {
FormattedMessage as T,
AdvancedFilterPopover,
If,
Icon,
Can,
DashboardActionViewsList,
DashboardFilterButton,
DashboardRowsHeightButton,
DashboardActionsBar,
} from '@/components';
import withEstimates from './withEstimates';
import withEstimatesActions from './withEstimatesActions';
import withSettings from '@/containers/Settings/withSettings';
import withSettingsActions from '@/containers/Settings/withSettingsActions';
import { useEstimatesListContext } from './EstimatesListProvider';
import { useRefreshEstimates } from '@/hooks/query/estimates';
import { SaleEstimateAction, AbilitySubject } from '@/constants/abilityOption';
import { compose } from '@/utils';
/**
* Estimates list actions bar.
*/
function EstimateActionsBar({
// #withEstimateActions
setEstimatesTableState,
// #withEstimates
estimatesFilterRoles,
// #withSettings
estimatesTableSize,
// #withSettingsActions
addSetting,
}) {
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();
};
// Handle table row size change.
const handleTableRowSizeChange = (size) => {
addSetting('salesEstimates', 'tableSize', size);
};
return (
<DashboardActionsBar>
<NavbarGroup>
<DashboardActionViewsList
resourceName={'estimates'}
allMenuItem={true}
allMenuItemText={<T id={'all'} />}
views={estimatesViews}
onChange={handleTabChange}
/>
<NavbarDivider />
<Can I={SaleEstimateAction.Create} a={AbilitySubject.Estimate}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'plus'} />}
text={<T id={'new_estimate'} />}
onClick={onClickNewEstimate}
/>
</Can>
<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'} />}
/>
<NavbarDivider />
<DashboardRowsHeightButton
initialValue={estimatesTableSize}
onChange={handleTableRowSizeChange}
/>
<NavbarDivider />
</NavbarGroup>
<NavbarGroup align={Alignment.RIGHT}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon="refresh-16" iconSize={14} />}
onClick={handleRefreshBtnClick}
/>
</NavbarGroup>
</DashboardActionsBar>
);
}
export default compose(
withEstimatesActions,
withSettingsActions,
withEstimates(({ estimatesTableState }) => ({
estimatesFilterRoles: estimatesTableState.filterRoles,
})),
withSettings(({ estimatesSettings }) => ({
estimatesTableSize: estimatesSettings?.tableSize,
})),
)(EstimateActionsBar);

View File

@@ -0,0 +1,169 @@
// @ts-nocheck
import React, { useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import EstimatesEmptyStatus from './EstimatesEmptyStatus';
import withEstimatesActions from './withEstimatesActions';
import withAlertsActions from '@/containers/Alert/withAlertActions';
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import withSettings from '@/containers/Settings/withSettings';
import { TABLES } from '@/constants/tables';
import {
DataTable,
DashboardContentTable,
TableSkeletonRows,
TableSkeletonHeader,
} from '@/components';
import { ActionsMenu, useEstiamtesTableColumns } from './components';
import { useEstimatesListContext } from './EstimatesListProvider';
import { useMemorizedColumnsWidths } from '@/hooks';
import { compose } from '@/utils';
/**
* Estimates datatable.
*/
function EstimatesDataTable({
// #withEstimatesActions
setEstimatesTableState,
// #withAlertsActions
openAlert,
// #withDrawerActions
openDrawer,
// #withDialogAction
openDialog,
// #withSettings
estimatesTableSize,
}) {
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}
size={estimatesTableSize}
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,
withSettings(({ estimatesSettings }) => ({
estimatesTableSize: estimatesSettings?.tableSize,
})),
)(EstimatesDataTable);

View File

@@ -0,0 +1,39 @@
// @ts-nocheck
import React from 'react';
import { Button, Intent } from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import { EmptyStatus } from '@/components';
import { Can, FormattedMessage as T } from '@/components';
import { SaleEstimateAction, AbilitySubject } from '@/constants/abilityOption';
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={
<>
<Can I={SaleEstimateAction.Create} a={AbilitySubject.Estimate}>
<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>
</Can>
</>
}
/>
);
}

View File

@@ -0,0 +1,57 @@
// @ts-nocheck
import React from 'react';
import { DashboardContentTable, DashboardPageContent } from '@/components';
import '@/style/pages/SaleEstimate/List.scss';
import EstimatesActionsBar from './EstimatesActionsBar';
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>
</EstimatesListProvider>
);
}
export default compose(
withEstimates(({ estimatesTableState, estimatesTableStateChanged }) => ({
estimatesTableState,
estimatesTableStateChanged,
})),
withEstimatesActions,
)(EstimatesList);

View File

@@ -0,0 +1,69 @@
// @ts-nocheck
import React, { createContext } from 'react';
import { isEmpty } from 'lodash';
import { DashboardInsider } from '@/components/Dashboard';
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 };

View File

@@ -0,0 +1,53 @@
// @ts-nocheck
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);

View File

@@ -0,0 +1,226 @@
// @ts-nocheck
import React from 'react';
import { Intent, Tag, Menu, MenuItem, MenuDivider } from '@blueprintjs/core';
import intl from 'react-intl-universal';
import clsx from 'classnames';
import { SaleEstimateAction, AbilitySubject } from '@/constants/abilityOption';
import { CLASSES } from '@/constants/classes';
import {
FormatDateCell,
FormattedMessage as T,
Money,
Choose,
Icon,
If,
Can,
} from '@/components';
import { safeCallback } from '@/utils';
/**
* Status accessor.
*/
export const statusAccessor = (row) => (
<Choose>
<Choose.When condition={row.is_approved}>
<Tag minimal={true} intent={Intent.SUCCESS} round={true}>
<T id={'approved'} />
</Tag>
</Choose.When>
<Choose.When condition={row.is_rejected}>
<Tag minimal={true} intent={Intent.DANGER} round={true}>
<T id={'rejected'} />
</Tag>
</Choose.When>
<Choose.When condition={row.is_expired}>
<Tag minimal={true} intent={Intent.WARNING} round={true}>
<T id={'estimate.status.expired'} />
</Tag>
</Choose.When>
<Choose.When condition={row.is_delivered}>
<Tag minimal={true} intent={Intent.SUCCESS} round={true}>
<T id={'delivered'} />
</Tag>
</Choose.When>
<Choose.Otherwise>
<Tag minimal={true} round={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)}
/>
<Can I={SaleEstimateAction.Edit} a={AbilitySubject.Estimate}>
<MenuDivider />
<MenuItem
icon={<Icon icon="pen-18" />}
text={intl.get('edit_estimate')}
onClick={safeCallback(onEdit, original)}
/>
<If condition={!original.is_converted_to_invoice}>
<MenuItem
icon={<Icon icon="convert_to" />}
text={intl.get('convert_to_invoice')}
onClick={safeCallback(onConvert, original)}
/>
</If>
<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>
</Can>
<Can I={SaleEstimateAction.View} a={AbilitySubject.Estimate}>
<MenuItem
icon={<Icon icon={'print-16'} iconSize={16} />}
text={intl.get('print')}
onClick={safeCallback(onPrint, original)}
/>
</Can>
<Can I={SaleEstimateAction.Delete} a={AbilitySubject.Estimate}>
<MenuDivider />
<MenuItem
text={intl.get('delete_estimate')}
intent={Intent.DANGER}
onClick={safeCallback(onDelete, original)}
icon={<Icon icon="trash-16" iconSize={16} />}
/>
</Can>
</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,
},
],
[],
);
}

View File

@@ -0,0 +1,20 @@
// @ts-nocheck
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);
};

View File

@@ -0,0 +1,13 @@
// @ts-nocheck
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);

View File

@@ -0,0 +1,12 @@
// @ts-nocheck
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);
};

View File

@@ -0,0 +1,193 @@
// @ts-nocheck
import React from 'react';
import {
Intent,
Button,
ButtonGroup,
Popover,
PopoverInteractionKind,
Position,
Menu,
MenuItem,
} from '@blueprintjs/core';
import classNames from 'classnames';
import { CLASSES } from '@/constants/classes';
import { useFormikContext } from 'formik';
import { If, Icon, FormattedMessage as T } from '@/components';
import { useHistory } from 'react-router-dom';
import { useInvoiceFormContext } from './InvoiceFormProvider';
/**
* 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}
style={{ minWidth: '85px' }}
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>
);
}

View File

@@ -0,0 +1,64 @@
// @ts-nocheck
import * as Yup from 'yup';
import moment from 'moment';
import intl from 'react-intl-universal';
import { DATATYPES_LENGTH } from '@/constants/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()
.min(Yup.ref('invoice_date'), ({ path, min }) =>
intl.get('invoice.validation.due_date', {
path,
min: moment(min).format('YYYY/MM/DD'),
}),
)
.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')),
exchange_rate: Yup.number(),
branch_id: Yup.string(),
warehouse_id: Yup.string(),
project_id: Yup.string(),
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;

View File

@@ -0,0 +1,190 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { Formik, Form } from 'formik';
import { Intent } from '@blueprintjs/core';
import { sumBy, isEmpty } from 'lodash';
import { useHistory } from 'react-router-dom';
import { CLASSES } from '@/constants/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 InvoiceFormTopBar from './InvoiceFormTopBar';
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 { useInvoiceFormContext } from './InvoiceFormProvider';
import {
transformToEditForm,
defaultInvoice,
transformErrors,
transformValueToRequest,
} 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) }
: {
...defaultInvoice,
...(invoiceIncrementMode && {
invoice_no: invoiceNumber,
}),
entries: orderingLinesIndexes(defaultInvoice.entries),
currency_code: base_currency,
...newInvoice,
}),
}),
[invoice, newInvoice, invoiceNumber, invoiceIncrementMode, base_currency],
);
// 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;
}
// Transformes the values of the form to request.
const form = {
...transformValueToRequest(values),
delivered: submitPayload.deliver,
from_estimate_id: estimateId,
};
// 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);
}
};
// Create invoice form schema.
const CreateInvoiceFormSchema = getCreateInvoiceFormSchema();
// Edit invoice form schema.
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>
<InvoiceFormTopBar />
<InvoiceFormHeader />
<InvoiceItemsEntriesEditorField />
<InvoiceFormFooter />
<InvoiceFloatingActions />
<InvoiceFormDialogs />
</Form>
</Formik>
</div>
);
}
export default compose(
withDashboardActions,
withSettings(({ invoiceSettings }) => ({
invoiceNextNumber: invoiceSettings?.nextNumber,
invoiceNumberPrefix: invoiceSettings?.numberPrefix,
invoiceIncrementMode: invoiceSettings?.autoIncrement,
})),
withCurrentOrganization(),
)(InvoiceForm);

View File

@@ -0,0 +1,25 @@
// @ts-nocheck
import React from 'react';
import { useFormikContext } from 'formik';
import { BaseCurrency, BaseCurrencyRoot } from '@/components';
import { useInvoiceFormContext } from './InvoiceFormProvider';
/**
* Invoice form currency tag.
*/
export default function InvoiceFormCurrencyTag() {
const { isForeignCustomer } = useInvoiceFormContext();
const {
values: { currency_code },
} = useFormikContext();
if (!isForeignCustomer) {
return null;
}
return (
<BaseCurrencyRoot>
<BaseCurrency currency={currency_code} />
</BaseCurrencyRoot>
);
}

View File

@@ -0,0 +1,26 @@
// @ts-nocheck
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}
/>
</>
);
}

View File

@@ -0,0 +1,31 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import styled from 'styled-components';
import { CLASSES } from '@/constants/classes';
import { Paper, Row, Col } from '@/components';
import { InvoiceFormFooterLeft } from './InvoiceFormFooterLeft';
import { InvoiceFormFooterRight } from './InvoiceFormFooterRight';
export default function InvoiceFormFooter() {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<InvoiceFooterPaper>
<Row>
<Col md={8}>
<InvoiceFormFooterLeft />
</Col>
<Col md={4}>
<InvoiceFormFooterRight />
</Col>
</Row>
</InvoiceFooterPaper>
</div>
);
}
const InvoiceFooterPaper = styled(Paper)`
padding: 20px;
`;

View File

@@ -0,0 +1,61 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import styled from 'styled-components';
import { FFormGroup, FEditableText, FormattedMessage as T } from '@/components';
export function InvoiceFormFooterLeft() {
return (
<React.Fragment>
{/* --------- Invoice message --------- */}
<InvoiceMsgFormGroup
name={'invoice_message'}
label={<T id={'invoice_message'} />}
>
<FEditableText
name={'invoice_message'}
placeholder={intl.get('invoice_form.invoice_message.placeholder')}
/>
</InvoiceMsgFormGroup>
{/* --------- Terms and conditions --------- */}
<TermsConditsFormGroup
label={<T id={'invoice_form.label.terms_conditions'} />}
name={'terms_conditions'}
>
<FEditableText
name={'terms_conditions'}
placeholder={intl.get(
'invoice_form.terms_and_conditions.placeholder',
)}
/>
</TermsConditsFormGroup>
</React.Fragment>
);
}
const InvoiceMsgFormGroup = styled(FFormGroup)`
&.bp3-form-group {
margin-bottom: 40px;
.bp3-label {
font-size: 12px;
margin-bottom: 12px;
}
.bp3-form-content {
margin-left: 10px;
}
}
`;
const TermsConditsFormGroup = styled(FFormGroup)`
&.bp3-form-group {
.bp3-label {
font-size: 12px;
margin-bottom: 12px;
}
.bp3-form-content {
margin-left: 10px;
}
}
`;

View File

@@ -0,0 +1,53 @@
// @ts-nocheck
import React from 'react';
import styled from 'styled-components';
import {
T,
TotalLines,
TotalLine,
TotalLineBorderStyle,
TotalLineTextStyle,
} from '@/components';
import { useInvoiceTotals } from './utils';
export function InvoiceFormFooterRight() {
// Calculate the total due amount of invoice entries.
const {
formattedSubtotal,
formattedTotal,
formattedDueTotal,
formattedPaymentTotal,
} = useInvoiceTotals();
return (
<InvoiceTotalLines labelColWidth={'180px'} amountColWidth={'180px'}>
<TotalLine
title={<T id={'invoice_form.label.subtotal'} />}
value={formattedSubtotal}
borderStyle={TotalLineBorderStyle.None}
/>
<TotalLine
title={<T id={'invoice_form.label.total'} />}
value={formattedTotal}
borderStyle={TotalLineBorderStyle.SingleDark}
textStyle={TotalLineTextStyle.Bold}
/>
<TotalLine
title={<T id={'invoice_form.label.payment_amount'} />}
value={formattedPaymentTotal}
borderStyle={TotalLineBorderStyle.None}
/>
<TotalLine
title={<T id={'invoice_form.label.due_amount'} />}
value={formattedDueTotal}
textStyle={TotalLineTextStyle.Bold}
/>
</InvoiceTotalLines>
);
}
const InvoiceTotalLines = styled(TotalLines)`
width: 100%;
color: #555555;
`;

View File

@@ -0,0 +1,35 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { useFormikContext } from 'formik';
import InvoiceFormHeaderFields from './InvoiceFormHeaderFields';
import { CLASSES } from '@/constants/classes';
import { PageFormBigNumber } from '@/components';
import { useInvoiceTotal } from './utils';
/**
* Invoice form header section.
*/
function InvoiceFormHeader() {
const {
values: { currency_code },
} = useFormikContext();
// Calculate the total due amount of invoice entries.
const totalDueAmount = useInvoiceTotal();
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<InvoiceFormHeaderFields />
<PageFormBigNumber
label={intl.get('due_amount')}
amount={totalDueAmount}
currencyCode={currency_code}
/>
</div>
);
}
export default InvoiceFormHeader;

View File

@@ -0,0 +1,279 @@
// @ts-nocheck
import React from 'react';
import styled from 'styled-components';
import classNames from 'classnames';
import {
FormGroup,
InputGroup,
Position,
Classes,
ControlGroup,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FastField, Field, ErrorMessage, useFormikContext } from 'formik';
import {
FFormGroup,
FormattedMessage as T,
Col,
Row,
CustomerDrawerLink,
CustomerSelectField,
FieldRequiredHint,
Icon,
InputPrependButton,
FeatureCan,
} from '@/components';
import { momentFormatter, compose, tansformDateValue } from '@/utils';
import { CLASSES } from '@/constants/classes';
import { inputIntent, handleDateChange } from '@/utils';
import {
useObserveInvoiceNoSettings,
customerNameFieldShouldUpdate,
} from './utils';
import { useInvoiceFormContext } from './InvoiceFormProvider';
import {
InvoiceExchangeRateInputField,
InvoiceProjectSelectButton,
} from './components';
import {
ProjectsSelect,
ProjectBillableEntriesLink,
} from '@/containers/Projects/components';
import { Features } from '@/constants';
import withSettings from '@/containers/Settings/withSettings';
import withDialogActions from '@/containers/Dialog/withDialogActions';
/**
* Invoice form header fields.
*/
function InvoiceFormHeaderFields({
// #withDialogActions
openDialog,
// #withSettings
invoiceAutoIncrement,
invoiceNumberPrefix,
invoiceNextNumber,
}) {
// Invoice form context.
const { customers, projects } = useInvoiceFormContext();
// Formik context.
const { values } = useFormikContext();
// 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 } }) => (
<FFormGroup
name={'customer_id'}
label={<T id={'customer_name'} />}
inline={true}
className={classNames(
'form-group--customer-name',
'form-group--select-list',
CLASSES.FILL,
)}
labelInfo={<FieldRequiredHint />}
>
<CustomerSelectField
contacts={customers}
selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={(customer) => {
form.setFieldValue('customer_id', customer.id);
form.setFieldValue('currency_code', customer?.currency_code);
}}
popoverFill={true}
allowCreate={true}
/>
{value && (
<CustomerButtonLink customerId={value}>
<T id={'view_customer_details'} />
</CustomerButtonLink>
)}
</FFormGroup>
)}
</FastField>
{/* ----------- Exchange rate ----------- */}
<InvoiceExchangeRateInputField
name={'exchange_rate'}
formGroupProps={{ label: ' ', inline: true }}
/>
<Row>
<Col xs={6}>
{/* ----------- 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,
}}
/>
</FormGroup>
)}
</FastField>
</Col>
<Col xs={6}>
{/* ----------- Due date ----------- */}
<FastField name={'due_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'due_date'} />}
labelInfo={<FieldRequiredHint />}
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,
}}
/>
</FormGroup>
)}
</FastField>
</Col>
</Row>
{/* ----------- 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>
{/*------------ Project name -----------*/}
<FeatureCan feature={Features.Projects}>
<FFormGroup
name={'project_id'}
label={<T id={'invoice.project_name.label'} />}
inline={true}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ProjectsSelect
name={'project_id'}
projects={projects}
input={InvoiceProjectSelectButton}
popoverFill={true}
/>
{values?.project_id && (
<ProjectBillableEntriesLink projectId={values?.project_id}>
<T id={'add_billable_entries'} />
</ProjectBillableEntriesLink>
)}
</FFormGroup>
</FeatureCan>
</div>
);
}
export default compose(
withDialogActions,
withSettings(({ invoiceSettings }) => ({
invoiceAutoIncrement: invoiceSettings?.autoIncrement,
invoiceNextNumber: invoiceSettings?.nextNumber,
invoiceNumberPrefix: invoiceSettings?.numberPrefix,
})),
)(InvoiceFormHeaderFields);
const CustomerButtonLink = styled(CustomerDrawerLink)`
font-size: 11px;
margin-top: 6px;
`;

View File

@@ -0,0 +1,22 @@
// @ts-nocheck
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>
);
}

View File

@@ -0,0 +1,151 @@
// @ts-nocheck
import React, { createContext, useState } from 'react';
import { isEmpty, pick } from 'lodash';
import { useLocation } from 'react-router-dom';
import { Features } from '@/constants';
import { useFeatureCan } from '@/hooks/state';
import { DashboardInsider } from '@/components/Dashboard';
import { transformToEditForm, ITEMS_FILTER_ROLES_QUERY } from './utils';
import {
useInvoice,
useItems,
useCustomers,
useWarehouses,
useBranches,
useCreateInvoice,
useEditInvoice,
useSettingsInvoices,
useEstimate,
} from '@/hooks/query';
import { useProjects } from '@/containers/Projects/hooks';
const InvoiceFormContext = createContext();
/**
* Accounts chart data provider.
*/
function InvoiceFormProvider({ invoiceId, baseCurrency, ...props }) {
const { state } = useLocation();
const estimateId = state?.action;
// Features guard.
const { featureCan } = useFeatureCan();
const isWarehouseFeatureCan = featureCan(Features.Warehouses);
const isBranchFeatureCan = featureCan(Features.Branches);
const isProjectsFeatureCan = featureCan(Features.Projects);
const { data: invoice, isLoading: isInvoiceLoading } = useInvoice(invoiceId, {
enabled: !!invoiceId,
});
// Fetch project list.
const {
data: { projects },
isLoading: isProjectsLoading,
} = useProjects({}, { enabled: !!isProjectsFeatureCan });
// 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', 'currency_code', '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 });
// Fetch warehouses list.
const {
data: warehouses,
isLoading: isWarehouesLoading,
isSuccess: isWarehousesSuccess,
} = useWarehouses({}, { enabled: isWarehouseFeatureCan });
// Fetches the branches list.
const {
data: branches,
isLoading: isBranchesLoading,
isSuccess: isBranchesSuccess,
} = useBranches({}, { enabled: isBranchFeatureCan });
// 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;
// Determines whether the warehouse and branches are loading.
const isFeatureLoading =
isWarehouesLoading || isBranchesLoading || isProjectsLoading;
const provider = {
invoice,
items,
customers,
newInvoice,
estimateId,
invoiceId,
submitPayload,
branches,
warehouses,
projects,
isInvoiceLoading,
isItemsLoading,
isCustomersLoading,
isSettingsLoading,
isWarehouesLoading,
isBranchesLoading,
isFeatureLoading,
isBranchesSuccess,
isWarehousesSuccess,
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 };

View File

@@ -0,0 +1,124 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import styled from 'styled-components';
import {
Alignment,
NavbarGroup,
NavbarDivider,
Button,
Classes,
} from '@blueprintjs/core';
import {
useSetPrimaryWarehouseToForm,
useSetPrimaryBranchToForm,
} from './utils';
import { Features } from '@/constants';
import { useInvoiceFormContext } from './InvoiceFormProvider';
import { useFeatureCan } from '@/hooks/state';
import {
Icon,
BranchSelect,
FeatureCan,
WarehouseSelect,
FormTopbar,
} from '@/components';
/**
* Invoice form topbar .
* @returns {JSX.Element}
*/
export default function InvoiceFormTopBar() {
// Features guard.
const { featureCan } = useFeatureCan();
// Sets the primary warehouse to form.
useSetPrimaryWarehouseToForm();
// Sets the primary branch to form.
useSetPrimaryBranchToForm();
// Can't display the navigation bar if warehouses or branches feature is not enabled.
if (!featureCan(Features.Warehouses) && !featureCan(Features.Branches)) {
return null;
}
return (
<FormTopbar>
<NavbarGroup align={Alignment.LEFT}>
<FeatureCan feature={Features.Branches}>
<InvoiceFormSelectBranch />
</FeatureCan>
{featureCan(Features.Warehouses) && featureCan(Features.Branches) && (
<NavbarDivider />
)}
<FeatureCan feature={Features.Warehouses}>
<InvoiceFormSelectWarehouse />
</FeatureCan>
</NavbarGroup>
</FormTopbar>
);
}
function InvoiceFormSelectBranch() {
// Invoice form context.
const { branches, isBranchesLoading } = useInvoiceFormContext();
return isBranchesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<BranchSelect
name={'branch_id'}
branches={branches}
input={InvoiceBranchSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function InvoiceFormSelectWarehouse() {
// Invoice form context.
const { warehouses, isWarehouesLoading } = useInvoiceFormContext();
return isWarehouesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<WarehouseSelect
name={'warehouse_id'}
warehouses={warehouses}
input={InvoiceWarehouseSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function InvoiceWarehouseSelectButton({ label }) {
return (
<Button
text={intl.get('invoice.warehouse_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'warehouse-16'} iconSize={16} />}
/>
);
}
function InvoiceBranchSelectButton({ label }) {
return (
<Button
text={intl.get('invoice.branch_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'branch-16'} iconSize={16} />}
/>
);
}
const DetailsBarSkeletonBase = styled.div`
letter-spacing: 10px;
margin-right: 10px;
margin-left: 10px;
font-size: 8px;
width: 140px;
height: 10px;
`;

View File

@@ -0,0 +1,42 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import { FastField } from 'formik';
import { CLASSES } from '@/constants/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>
);
}

View File

@@ -0,0 +1,39 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import { Button } from '@blueprintjs/core';
import { useFormikContext } from 'formik';
import { ExchangeRateInputGroup } from '@/components';
import { useCurrentOrganization } from '@/hooks/state';
import { useInvoiceIsForeignCustomer } from './utils';
/**
* Invoice exchange rate input field.
* @returns {JSX.Element}
*/
export function InvoiceExchangeRateInputField({ ...props }) {
const currentOrganization = useCurrentOrganization();
const { values } = useFormikContext();
const isForeignCustomer = useInvoiceIsForeignCustomer();
// Can't continue if the customer is not foreign.
if (!isForeignCustomer) {
return null;
}
return (
<ExchangeRateInputGroup
fromCurrency={values.currency_code}
toCurrency={currentOrganization.base_currency}
{...props}
/>
);
}
/**
* Invoice project select.
* @returns {JSX.Element}
*/
export function InvoiceProjectSelectButton({ label }) {
return <Button text={label ?? intl.get('select_project')} />;
}

View File

@@ -0,0 +1,281 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import moment from 'moment';
import { Intent } from '@blueprintjs/core';
import { omit, first } from 'lodash';
import {
compose,
transformToForm,
repeatValue,
transactionNumber,
} from '@/utils';
import { useFormikContext } from 'formik';
import { formattedAmount, defaultFastFieldShouldUpdate } from '@/utils';
import { ERROR } from '@/constants/errors';
import { AppToaster } from '@/components';
import { useCurrentOrganization } from '@/hooks/state';
import { getEntriesTotal } from '@/containers/Entries/utils';
import { useInvoiceFormContext } from './InvoiceFormProvider';
import {
updateItemsEntriesTotal,
ensureEntriesHaveEmptyLine,
} from '@/containers/Entries/utils';
export const MIN_LINES_NUMBER = 1;
// 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: '',
exchange_rate: 1,
currency_code: '',
branch_id: '',
warehouse_id: '',
project_id: '',
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',
},
]);
/**
* Transformes the form values to request body values.
*/
export function transformValueToRequest(values) {
const entries = values.entries.filter(
(item) => item.item_id && item.quantity,
);
return {
...omit(values, ['invoice_no', 'invoice_no_manually']),
...(values.invoice_no_manually && {
invoice_no: values.invoice_no,
}),
entries: entries.map((entry) => ({ ...omit(entry, ['amount']) })),
delivered: false,
};
}
export const useSetPrimaryWarehouseToForm = () => {
const { setFieldValue } = useFormikContext();
const { warehouses, isWarehousesSuccess } = useInvoiceFormContext();
React.useEffect(() => {
if (isWarehousesSuccess) {
const primaryWarehouse =
warehouses.find((b) => b.primary) || first(warehouses);
if (primaryWarehouse) {
setFieldValue('warehouse_id', primaryWarehouse.id);
}
}
}, [isWarehousesSuccess, setFieldValue, warehouses]);
};
export const useSetPrimaryBranchToForm = () => {
const { setFieldValue } = useFormikContext();
const { branches, isBranchesSuccess } = useInvoiceFormContext();
React.useEffect(() => {
if (isBranchesSuccess) {
const primaryBranch = branches.find((b) => b.primary) || first(branches);
if (primaryBranch) {
setFieldValue('branch_id', primaryBranch.id);
}
}
}, [isBranchesSuccess, setFieldValue, branches]);
};
export const useInvoiceTotal = () => {
const {
values: { entries },
} = useFormikContext();
// Calculate the total due amount of invoice entries.
return React.useMemo(() => getEntriesTotal(entries), [entries]);
};
/**
* Retreives the invoice totals.
*/
export const useInvoiceTotals = () => {
const {
values: { entries, currency_code: currencyCode },
} = useFormikContext();
// Retrieves the invoice entries total.
const total = React.useMemo(() => getEntriesTotal(entries), [entries]);
// Retrieves the formatted total money.
const formattedTotal = React.useMemo(
() => formattedAmount(total, currencyCode),
[total, currencyCode],
);
// Retrieves the formatted subtotal.
const formattedSubtotal = React.useMemo(
() => formattedAmount(total, currencyCode, { money: false }),
[total, currencyCode],
);
// Retrieves the payment total.
const paymentTotal = React.useMemo(() => 0, []);
// Retireves the formatted payment total.
const formattedPaymentTotal = React.useMemo(
() => formattedAmount(paymentTotal, currencyCode),
[paymentTotal, currencyCode],
);
// Retrieves the formatted due total.
const dueTotal = React.useMemo(
() => total - paymentTotal,
[total, paymentTotal],
);
// Retrieves the formatted due total.
const formattedDueTotal = React.useMemo(
() => formattedAmount(dueTotal, currencyCode),
[dueTotal, currencyCode],
);
return {
total,
paymentTotal,
dueTotal,
formattedTotal,
formattedSubtotal,
formattedPaymentTotal,
formattedDueTotal,
};
};
/**
* Detarmines whether the invoice has foreign customer.
* @returns {boolean}
*/
export const useInvoiceIsForeignCustomer = () => {
const { values } = useFormikContext();
const currentOrganization = useCurrentOrganization();
const isForeignCustomer = React.useMemo(
() => values.currency_code !== currentOrganization.base_currency,
[values.currency_code, currentOrganization.base_currency],
);
return isForeignCustomer;
};

View File

@@ -0,0 +1,126 @@
// @ts-nocheck
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 '@/constants/resourcesTypes';
import { AbilitySubject, SaleInvoiceAction } from '@/constants/abilityOption';
import withDrawerActions from '@/containers/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,
permission: {
ability: SaleInvoiceAction.View,
subject: AbilitySubject.Invoice,
},
});

View File

@@ -0,0 +1,22 @@
// @ts-nocheck
import React from 'react';
const InvoiceDeleteAlert = React.lazy(
() => import('@/containers/Alerts/Invoices/InvoiceDeleteAlert'),
);
const InvoiceDeliverAlert = React.lazy(
() => import('@/containers/Alerts/Invoices/InvoiceDeliverAlert'),
);
const CancelBadDebtAlert = React.lazy(
() => import('@/containers/Alerts/Invoices/CancelBadDebtAlert'),
);
/**
* Invoices alert.
*/
export default [
{ name: 'invoice-delete', component: InvoiceDeleteAlert },
{ name: 'invoice-deliver', component: InvoiceDeliverAlert },
{ name: 'cancel-bad-debt', component: CancelBadDebtAlert },
];

View File

@@ -0,0 +1,59 @@
// @ts-nocheck
import React from 'react';
import { useHistory } from 'react-router';
import { Alignment, Navbar, NavbarGroup } from '@blueprintjs/core';
import { DashboardViewsTabs } from '@/components';
import { compose, transfromViewsToTabs } from '@/utils';
import { useInvoicesListContext } from './InvoicesListProvider';
import withInvoices from './withInvoices';
import withInvoiceActions from './withInvoiceActions';
/**
* 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);

View File

@@ -0,0 +1,160 @@
// @ts-nocheck
import React from 'react';
import {
Button,
Classes,
NavbarDivider,
NavbarGroup,
Intent,
Alignment,
} from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import {
Icon,
FormattedMessage as T,
AdvancedFilterPopover,
DashboardFilterButton,
DashboardRowsHeightButton,
DashboardActionsBar,
} from '@/components';
import { Can, If, DashboardActionViewsList } from '@/components';
import { SaleInvoiceAction, AbilitySubject } from '@/constants/abilityOption';
import { useRefreshInvoices } from '@/hooks/query/invoices';
import { useInvoicesListContext } from './InvoicesListProvider';
import withInvoices from './withInvoices';
import withInvoiceActions from './withInvoiceActions';
import withSettings from '@/containers/Settings/withSettings';
import withSettingsActions from '@/containers/Settings/withSettingsActions';
import { compose } from '@/utils';
/**
* Invoices table actions bar.
*/
function InvoiceActionsBar({
// #withInvoiceActions
setInvoicesTableState,
// #withInvoices
invoicesFilterRoles,
// #withSettings
invoicesTableSize,
// #withSettingsActions
addSetting,
}) {
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();
};
// Handle table row size change.
const handleTableRowSizeChange = (size) => {
addSetting('salesInvoices', 'tableSize', size);
};
return (
<DashboardActionsBar>
<NavbarGroup>
<DashboardActionViewsList
allMenuItem={true}
resourceName={'invoices'}
views={invoicesViews}
onChange={handleTabChange}
/>
<NavbarDivider />
<Can I={SaleInvoiceAction.Create} a={AbilitySubject.Invoice}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'plus'} />}
text={<T id={'new_invoice'} />}
onClick={handleClickNewInvoice}
/>
</Can>
<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'} />}
/>
<NavbarDivider />
<DashboardRowsHeightButton
initialValue={invoicesTableSize}
onChange={handleTableRowSizeChange}
/>
<NavbarDivider />
</NavbarGroup>
<NavbarGroup align={Alignment.RIGHT}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon="refresh-16" iconSize={14} />}
onClick={handleRefreshBtnClick}
/>
</NavbarGroup>
</DashboardActionsBar>
);
}
export default compose(
withInvoiceActions,
withSettingsActions,
withInvoices(({ invoicesTableState }) => ({
invoicesFilterRoles: invoicesTableState.filterRoles,
})),
withSettings(({ invoiceSettings }) => ({
invoicesTableSize: invoiceSettings?.tableSize,
})),
)(InvoiceActionsBar);

View File

@@ -0,0 +1,175 @@
// @ts-nocheck
import React, { useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import InvoicesEmptyStatus from './InvoicesEmptyStatus';
import { TABLES } from '@/constants/tables';
import {
DataTable,
DashboardContentTable,
TableSkeletonHeader,
TableSkeletonRows,
} from '@/components';
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 withDashboardActions from '@/containers/Dashboard/withDashboardActions';
import withSettings from '@/containers/Settings/withSettings';
import { useMemorizedColumnsWidths } from '@/hooks';
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,
// #withSettings
invoicesTableSize,
}) {
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 convert to credit note.
const handleConvertToCreitNote = ({ id }) => {
history.push(`/credit-notes/new?from_invoice_id=${id}`, { invoiceId: id });
};
// 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}
size={invoicesTableSize}
payload={{
onDelete: handleDeleteInvoice,
onDeliver: handleDeliverInvoice,
onEdit: handleEditInvoice,
onQuick: handleQuickPaymentReceive,
onViewDetails: handleViewDetailInvoice,
onPrint: handlePrintInvoice,
onConvert: handleConvertToCreitNote,
}}
/>
</DashboardContentTable>
);
}
export default compose(
withDashboardActions,
withInvoiceActions,
withAlertsActions,
withDrawerActions,
withDialogActions,
withInvoices(({ invoicesTableState }) => ({ invoicesTableState })),
withSettings(({ invoiceSettings }) => ({
invoicesTableSize: invoiceSettings?.tableSize,
})),
)(InvoicesDataTable);

View File

@@ -0,0 +1,39 @@
// @ts-nocheck
import React from 'react';
import { Button, Intent } from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import { EmptyStatus, Can, FormattedMessage as T } from '@/components';
import { SaleInvoiceAction, AbilitySubject } from '@/constants/abilityOption';
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={
<>
<Can I={SaleInvoiceAction.Create} a={AbilitySubject.Invoice}>
<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>
</Can>
</>
}
/>
);
}

View File

@@ -0,0 +1,60 @@
// @ts-nocheck
import React from 'react';
import '@/style/pages/SaleInvoice/List.scss';
import { DashboardPageContent } from '@/components';
import { InvoicesListProvider } from './InvoicesListProvider';
import InvoiceViewTabs from './InvoiceViewTabs';
import InvoicesDataTable from './InvoicesDataTable';
import InvoicesActionsBar from './InvoicesActionsBar';
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>
</InvoicesListProvider>
);
}
export default compose(
withInvoices(({ invoicesTableState, invoicesTableStateChanged }) => ({
invoicesTableState,
invoicesTableStateChanged,
})),
withInvoiceActions,
withAlertsActions,
)(InvoicesList);

View File

@@ -0,0 +1,66 @@
// @ts-nocheck
import React, { createContext } from 'react';
import { isEmpty } from 'lodash';
import { DashboardInsider } from '@/components/Dashboard';
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 };

View File

@@ -0,0 +1,266 @@
// @ts-nocheck
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 '@/constants/classes';
import {
FormatDateCell,
FormattedMessage as T,
AppToaster,
Choose,
If,
Icon,
Can,
} from '@/components';
import { formattedAmount, safeCallback, calculateStatus } from '@/utils';
import {
SaleInvoiceAction,
PaymentReceiveAction,
AbilitySubject,
} from '@/constants/abilityOption';
export function InvoiceStatus({ invoice }) {
return (
<Choose>
<Choose.When condition={invoice.is_fully_paid && invoice.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={invoice.is_delivered}>
<Choose>
<Choose.When condition={invoice.is_overdue}>
<span className={'overdue-status'}>
{intl.get('overdue_by', { overdue: invoice.overdue_days })}
</span>
</Choose.When>
<Choose.Otherwise>
<span className={'due-status'}>
{intl.get('due_in', { due: invoice.remaining_days })}
</span>
</Choose.Otherwise>
</Choose>
<If condition={invoice.is_partially_paid}>
<span class="partial-paid">
{intl.get('day_partially_paid', {
due: formattedAmount(invoice.due_amount, invoice.currency_code),
})}
</span>
<ProgressBar
animate={false}
stripes={false}
intent={Intent.PRIMARY}
value={calculateStatus(invoice.balance_amount, invoice.balance)}
/>
</If>
</Choose.When>
<Choose.Otherwise>
<Tag minimal={true} round={true}>
<T id={'draft'} />
</Tag>
</Choose.Otherwise>
</Choose>
);
}
export const statusAccessor = (row) => {
return (
<div className={'status-accessor'}>
<InvoiceStatus invoice={row} />
</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,
});
}
if (
errors.find(
(error) => error.type === 'SALE_INVOICE_HAS_APPLIED_TO_CREDIT_NOTES',
)
) {
AppToaster.show({
message: intl.get(
'invoices.error.you_couldn_t_delete_sale_invoice_that_has_reconciled',
),
intent: Intent.DANGER,
});
}
};
export function ActionsMenu({
payload: {
onEdit,
onDeliver,
onDelete,
onConvert,
onQuick,
onViewDetails,
onPrint,
},
row: { original },
}) {
return (
<Menu>
<MenuItem
icon={<Icon icon="reader-18" />}
text={intl.get('view_details')}
onClick={safeCallback(onViewDetails, original)}
/>
<Can I={SaleInvoiceAction.Edit} a={AbilitySubject.Invoice}>
<MenuDivider />
<MenuItem
icon={<Icon icon="pen-18" />}
text={intl.get('edit_invoice')}
onClick={safeCallback(onEdit, original)}
/>
<MenuItem
icon={<Icon icon="convert_to" />}
text={intl.get('invoice.convert_to_credit_note')}
onClick={safeCallback(onConvert, original)}
/>
<If condition={!original.is_delivered}>
<MenuItem
icon={<Icon icon="send" iconSize={16} />}
text={intl.get('mark_as_delivered')}
onClick={safeCallback(onDeliver, original)}
/>
</If>
</Can>
<Can I={PaymentReceiveAction.Create} a={AbilitySubject.PaymentReceive}>
<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>
</Can>
<Can I={SaleInvoiceAction.View} a={AbilitySubject.Invoice}>
<MenuItem
icon={<Icon icon={'print-16'} iconSize={16} />}
text={intl.get('print')}
onClick={safeCallback(onPrint, original)}
/>
</Can>
<Can I={SaleInvoiceAction.Delete} a={AbilitySubject.Invoice}>
<MenuDivider />
<MenuItem
text={intl.get('delete_invoice')}
intent={Intent.DANGER}
onClick={safeCallback(onDelete, original)}
icon={<Icon icon="trash-16" iconSize={16} />}
/>
</Can>
</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,
},
],
[],
);
}

View File

@@ -0,0 +1,13 @@
// @ts-nocheck
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);

View File

@@ -0,0 +1,20 @@
// @ts-nocheck
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);
};

View File

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

View File

@@ -0,0 +1,117 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import {
Intent,
Button,
ButtonGroup,
Popover,
PopoverInteractionKind,
Position,
Menu,
MenuItem,
} from '@blueprintjs/core';
import { Icon, FormattedMessage as T } from '@/components';
import { useHistory } from 'react-router-dom';
import { useFormikContext } from 'formik';
import { CLASSES } from '@/constants/classes';
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}
style={{ minWidth: '85px' }}
text={!isNewMode ? <T id={'edit'} /> : <T id={'save'} />}
/>
<Popover
content={
<Menu>
<MenuItem
text={<T id={'save_and_new'} />}
onClick={handleSubmitAndNewClick}
/>
<MenuItem
text={<T id={'save_continue_editing'} />}
onClick={handleSubmitContinueEditingBtnClick}
/>
</Menu>
}
minimal={true}
interactionKind={PopoverInteractionKind.CLICK}
position={Position.BOTTOM_LEFT}
>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
/>
</Popover>
</ButtonGroup>
{/* ----------- Clear & Reset----------- */}
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={handleClearBtnClick}
text={!isNewMode ? <T id={'reset'} /> : <T id={'clear'} />}
/>
{/* ----------- Cancel ----------- */}
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={handleCancelBtnClick}
text={<T id={'cancel'} />}
/>
</div>
);
}

View File

@@ -0,0 +1,37 @@
// @ts-nocheck
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import { DATATYPES_LENGTH } from '@/constants/dataTypes';
const Schema = Yup.object().shape({
customer_id: Yup.string().label(intl.get('customer_name_')).required(),
payment_date: Yup.date().required().label(intl.get('payment_date_')),
deposit_account_id: Yup.number()
.required()
.label(intl.get('deposit_account_')),
full_amount: Yup.number().nullable(),
payment_receive_no: Yup.string()
.nullable()
.max(DATATYPES_LENGTH.STRING)
.label(intl.get('payment_receive_no_')),
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING).nullable(),
// statement: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
branch_id: Yup.string(),
exchange_rate: Yup.number(),
entries: Yup.array().of(
Yup.object().shape({
id: Yup.number().nullable(),
due_amount: Yup.number().nullable(),
payment_amount: Yup.number().nullable().max(Yup.ref('due_amount')),
invoice_id: Yup.number()
.nullable()
.when(['payment_amount'], {
is: (payment_amount) => payment_amount,
then: Yup.number().required(),
}),
}),
),
});
export const CreatePaymentReceiveFormSchema = Schema;
export const EditPaymentReceiveFormSchema = Schema;

View File

@@ -0,0 +1,198 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { Formik, Form } from 'formik';
import { omit, sumBy, pick, isEmpty, defaultTo } from 'lodash';
import { Intent } from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import '@/style/pages/PaymentReceive/PageForm.scss';
import { CLASSES } from '@/constants/classes';
import PaymentReceiveHeader from './PaymentReceiveFormHeader';
import PaymentReceiveFormBody from './PaymentReceiveFormBody';
import PaymentReceiveFloatingActions from './PaymentReceiveFloatingActions';
import PaymentReceiveFormFooter from './PaymentReceiveFormFooter';
import PaymentReceiveFormAlerts from './PaymentReceiveFormAlerts';
import PaymentReceiveFormDialogs from './PaymentReceiveFormDialogs';
import PaymentReceiveFormTopBar from './PaymentReceiveFormTopBar';
import { PaymentReceiveInnerProvider } from './PaymentReceiveInnerProvider';
import withSettings from '@/containers/Settings/withSettings';
import withCurrentOrganization from '@/containers/Organization/withCurrentOrganization';
import {
EditPaymentReceiveFormSchema,
CreatePaymentReceiveFormSchema,
} from './PaymentReceiveForm.schema';
import { AppToaster } from '@/components';
import { transactionNumber, compose } from '@/utils';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import {
defaultPaymentReceive,
transformToEditForm,
transformFormToRequest,
transformErrors,
} 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);
// Calculates the total payment amount of entries.
const totalPaymentAmount = sumBy(values.entries, 'payment_amount');
if (totalPaymentAmount <= 0) {
AppToaster.show({
message: intl.get('you_cannot_make_payment_with_zero_total_amount'),
intent: Intent.DANGER,
});
return;
}
// Transformes the form values to request body.
const form = transformFormToRequest(values);
// 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 },
},
}) => {
if (errors) {
transformErrors(errors, { setFieldError });
}
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>
<PaymentReceiveFormTopBar />
<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?.preferredDepositAccount,
})),
withCurrentOrganization(),
)(PaymentReceiveForm);

View File

@@ -0,0 +1,27 @@
// @ts-nocheck
import React from 'react';
import { useFormikContext } from 'formik';
import ClearingAllLinesAlert from '@/containers/Alerts/PaymentReceives/ClearingAllLinesAlert';
import { clearAllPaymentEntries } from './utils';
/**
* Payment receive form alerts.
*/
export default function PaymentReceiveFormAlerts() {
const { values: { entries }, setFieldValue } = useFormikContext();
const handleClearingAllLines = () => {
const newEntries = clearAllPaymentEntries(entries);
setFieldValue('entries', newEntries);
setFieldValue('full_amount', '');
};
return (
<>
<ClearingAllLinesAlert
name={'clear-all-lines-payment-receive'}
onConfirm={handleClearingAllLines}
/>
</>
);
}

View File

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

View File

@@ -0,0 +1,22 @@
// @ts-nocheck
import React from 'react';
import { BaseCurrency, BaseCurrencyRoot } from '@/components';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
/**
* Payment reecevie form currnecy tag.
* @returns
*/
export default function PaymentReceiveFormCurrencyTag() {
const { isForeignCustomer, selectCustomer } = usePaymentReceiveFormContext();
if (!isForeignCustomer) {
return null;
}
return (
<BaseCurrencyRoot>
<BaseCurrency currency={selectCustomer?.currency_code} />
</BaseCurrencyRoot>
);
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,47 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import classNames from 'classnames';
import { sumBy } from 'lodash';
import { useFormikContext } from 'formik';
import { Money } from '@/components';
import { FormattedMessage as T } from '@/components';
import { CLASSES } from '@/constants/classes';
import PaymentReceiveHeaderFields from './PaymentReceiveHeaderFields';
/**
* Payment receive form header.
*/
function PaymentReceiveFormHeader() {
// Formik form context.
const {
values: { currency_code, entries },
} = useFormikContext();
// Calculates the total payment amount from due amount.
const paymentFullAmount = useMemo(
() => sumBy(entries, 'payment_amount'),
[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={currency_code} />
</h1>
</div>
</div>
</div>
</div>
);
}
export default PaymentReceiveFormHeader;

View File

@@ -0,0 +1,20 @@
// @ts-nocheck
import React from 'react';
import { useParams } from 'react-router-dom';
import { PaymentReceiveFormProvider } from './PaymentReceiveFormProvider';
import PaymentReceiveForm from './PaymentReceiveForm';
/**
* Payment receive form page.
*/
export default function PaymentReceiveFormPage() {
const { id: paymentReceiveId } = useParams();
const paymentReceiveIdInt = parseInt(paymentReceiveId, 10);
return (
<PaymentReceiveFormProvider paymentReceiveId={paymentReceiveIdInt}>
<PaymentReceiveForm paymentReceiveId={paymentReceiveIdInt} />
</PaymentReceiveFormProvider>
);
}

View File

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

View File

@@ -0,0 +1,69 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import { Alignment, NavbarGroup, Button, Classes } from '@blueprintjs/core';
import { useSetPrimaryBranchToForm } from './utils';
import { useFeatureCan } from '@/hooks/state';
import {
Icon,
BranchSelect,
FeatureCan,
FormTopbar,
DetailsBarSkeletonBase,
} from '@/components';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import { Features } from '@/constants';
/**
* Payment receive from top bar.
* @returns
*/
export default function PaymentReceiveFormTopBar() {
// Features guard.
const { featureCan } = useFeatureCan();
// Sets the primary branch to form.
useSetPrimaryBranchToForm();
// Can't display the navigation bar if branches feature is not enabled.
if (!featureCan(Features.Branches)) {
return null;
}
return (
<FormTopbar>
<NavbarGroup align={Alignment.LEFT}>
<FeatureCan feature={Features.Branches}>
<PaymentReceiveFormSelectBranch />
</FeatureCan>
</NavbarGroup>
</FormTopbar>
);
}
function PaymentReceiveFormSelectBranch() {
// payment receive form context.
const { branches, isBranchesLoading } = usePaymentReceiveFormContext();
return isBranchesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<BranchSelect
name={'branch_id'}
branches={branches}
input={PaymentReceiveBranchSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function PaymentReceiveBranchSelectButton({ label }) {
return (
<Button
text={intl.get('payment_receive.branch_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'branch-16'} iconSize={16} />}
/>
);
}

View File

@@ -0,0 +1,376 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import classNames from 'classnames';
import styled from 'styled-components';
import {
FormGroup,
InputGroup,
Position,
Classes,
ControlGroup,
Button,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { toSafeInteger } from 'lodash';
import { FeatureCan, FormattedMessage as T } from '@/components';
import { FastField, Field, useFormikContext, ErrorMessage } from 'formik';
import { useAutofocus } from '@/hooks';
import { CLASSES } from '@/constants/classes';
import {
compose,
safeSumBy,
momentFormatter,
tansformDateValue,
handleDateChange,
inputIntent,
} from '@/utils';
import {
FFormGroup,
AccountsSelectList,
CustomerSelectField,
FieldRequiredHint,
Icon,
InputPrependButton,
MoneyInputGroup,
InputPrependText,
CustomerDrawerLink,
Hint,
Money,
} from '@/components';
import { usePaymentReceiveFormContext } from './PaymentReceiveFormProvider';
import { ACCOUNT_TYPE } from '@/constants/accountTypes';
import { ProjectsSelect } from '@/containers/Projects/components';
import {
PaymentReceiveExchangeRateInputField,
PaymentReceiveProjectSelectButton,
} from './components';
import 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 { Features } from '@/constants';
/**
* Payment receive header fields.
*/
function PaymentReceiveHeaderFields({
// #withCurrentOrganization
organization: { base_currency },
// #withDialogActions
openDialog,
// #withSettings
paymentReceiveAutoIncrement,
paymentReceiveNumberPrefix,
paymentReceiveNextNumber,
}) {
// Payment receive form context.
const { customers, accounts, projects, 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'} />}
>
<CustomerSelectField
contacts={customers}
selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={(customer) => {
form.setFieldValue('customer_id', customer.id);
form.setFieldValue('full_amount', '');
form.setFieldValue('currency_code', customer?.currency_code);
}}
popoverFill={true}
disabled={!isNewMode}
buttonProps={{
elementRef: (ref) => (customerFieldRef.current = ref),
}}
allowCreate={true}
/>
{value && (
<CustomerButtonLink customerId={value}>
<T id={'view_customer_details'} />
</CustomerButtonLink>
)}
</FormGroup>
)}
</FastField>
{/* ----------- Exchange rate ----------- */}
<PaymentReceiveExchangeRateInputField
name={'exchange_rate'}
formGroupProps={{ label: ' ', inline: true }}
/>
{/* ------------- Payment date ------------- */}
<FastField name={'payment_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'payment_date'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
className={classNames('form-group--select-list', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="payment_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('payment_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
inputProps={{
leftIcon: <Icon icon={'date-range'} />,
}}
/>
</FormGroup>
)}
</FastField>
{/* ------------ Full amount ------------ */}
<Field name={'full_amount'}>
{({
form: {
setFieldValue,
values: { currency_code },
},
field: { value, onChange },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'full_amount'} />}
inline={true}
className={('form-group--full-amount', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
labelInfo={<Hint />}
helperText={<ErrorMessage name="full_amount" />}
>
<ControlGroup>
<InputPrependText text={currency_code} />
<MoneyInputGroup
value={value}
onChange={(value) => {
setFieldValue('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={currency_code} />)
</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}
labelInfo={<FieldRequiredHint />}
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>
{/*------------ Project name -----------*/}
<FeatureCan feature={Features.Projects}>
<FFormGroup
name={'project_id'}
label={<T id={'payment_receive.project_name.label'} />}
inline={true}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ProjectsSelect
name={'project_id'}
projects={projects}
input={PaymentReceiveProjectSelectButton}
popoverFill={true}
/>
</FFormGroup>
</FeatureCan>
</div>
);
}
export default compose(
withSettings(({ paymentReceiveSettings }) => ({
paymentReceiveNextNumber: paymentReceiveSettings?.nextNumber,
paymentReceiveNumberPrefix: paymentReceiveSettings?.numberPrefix,
paymentReceiveAutoIncrement: paymentReceiveSettings?.autoIncrement,
})),
withDialogActions,
withCurrentOrganization(),
)(PaymentReceiveHeaderFields);
const CustomerButtonLink = styled(CustomerDrawerLink)`
font-size: 11px;
margin-top: 6px;
`;

View File

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

Some files were not shown because too many files have changed in this diff Show More