mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-17 21:30:31 +00:00
re-structure to monorepo.
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
`;
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -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;
|
||||
`;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
`;
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 };
|
||||
@@ -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;
|
||||
`;
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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')} />;
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
Reference in New Issue
Block a user