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,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;
};