chrone: sperate client and server to different repos.

This commit is contained in:
a.bouhuolia
2021-09-21 17:13:53 +02:00
parent e011b2a82b
commit 18df5530c7
10015 changed files with 17686 additions and 97524 deletions

View File

@@ -0,0 +1,192 @@
import React from 'react';
import {
Intent,
Button,
ButtonGroup,
Popover,
PopoverInteractionKind,
Position,
Menu,
MenuItem,
} from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { useHistory } from 'react-router-dom';
import { CLASSES } from 'common/classes';
import classNames from 'classnames';
import { useFormikContext } from 'formik';
import { If, Icon } from 'components';
import { useBillFormContext } from './BillFormProvider';
/**
* Bill floating actions bar.
*/
export default function BillFloatingActions() {
const history = useHistory();
// Formik context.
const { resetForm, submitForm, isSubmitting } = useFormikContext();
// Bill form context.
const { bill, setSubmitPayload } = useBillFormContext();
// Handle submit as open button click.
const handleSubmitOpenBtnClick = (event) => {
setSubmitPayload({ redirect: true, status: true });
submitForm();
};
// Handle submit, open and anothe new button click.
const handleSubmitOpenAndNewBtnClick = (event) => {
setSubmitPayload({ redirect: false, status: true, resetForm: true });
submitForm();
};
// Handle submit as open & continue editing button click.
const handleSubmitOpenContinueEditingBtnClick = (event) => {
setSubmitPayload({ redirect: false, status: true });
submitForm();
};
// Handle submit as draft button click.
const handleSubmitDraftBtnClick = (event) => {
setSubmitPayload({ redirect: true, status: false });
submitForm();
};
// handle submit as draft & new button click.
const handleSubmitDraftAndNewBtnClick = (event) => {
setSubmitPayload({ redirect: false, status: false, resetForm: true });
submitForm();
};
// Handle submit as draft & continue editing button click.
const handleSubmitDraftContinueEditingBtnClick = (event) => {
setSubmitPayload({ redirect: false, status: false, });
submitForm();
};
// Handle cancel button click.
const handleCancelBtnClick = (event) => {
history.goBack();
};
const handleClearBtnClick = (event) => {
resetForm();
};
return (
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
{/* ----------- Save And Open ----------- */}
<If condition={!bill || !bill?.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={bill && bill?.is_open}>
<ButtonGroup>
<Button
loading={isSubmitting}
intent={Intent.PRIMARY}
onClick={handleSubmitOpenBtnClick}
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={bill ? <T id={'reset'} /> : <T id={'clear'} />}
/>
{/* ----------- Cancel ----------- */}
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={handleCancelBtnClick}
text={<T id={'cancel'} />}
/>
</div>
);
}

View File

@@ -0,0 +1,149 @@
import React, { useMemo } from 'react';
import { Formik, Form } from 'formik';
import { Intent } from '@blueprintjs/core';
import classNames from 'classnames';
import * as R from 'ramda';
import intl from 'react-intl-universal';
import { useHistory } from 'react-router-dom';
import { isEmpty } from 'lodash';
import { CLASSES } from 'common/classes';
import { EditBillFormSchema, CreateBillFormSchema } from './BillForm.schema';
import BillFormHeader from './BillFormHeader';
import BillFloatingActions from './BillFloatingActions';
import BillFormFooter from './BillFormFooter';
import BillItemsEntriesEditor from './BillItemsEntriesEditor';
import { AppToaster } from 'components';
import { ERROR } from 'common/errors';
import { useBillFormContext } from './BillFormProvider';
import { compose, safeSumBy } from 'utils';
import {
defaultBill,
transformToEditForm,
transformEntriesToSubmit,
} from './utils';
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
/**
* Bill form.
*/
function BillForm({
// #withCurrentOrganization
organization: { base_currency },
}) {
const history = useHistory();
// Bill form context.
const { bill, isNewMode, submitPayload, createBillMutate, editBillMutate } =
useBillFormContext();
// Initial values in create and edit mode.
const initialValues = useMemo(
() => ({
...(!isEmpty(bill)
? {
...transformToEditForm(bill),
currency_code: base_currency,
}
: {
...defaultBill,
currency_code: base_currency,
}),
}),
[bill, base_currency],
);
// Transform response error to fields.
const handleErrors = (errors, { setErrors }) => {
if (errors.some((e) => e.type === ERROR.BILL_NUMBER_EXISTS)) {
setErrors({
bill_number: intl.get('bill_number_exists'),
});
}
};
// Handles form submit.
const handleFormSubmit = (
values,
{ setSubmitting, setErrors, resetForm },
) => {
const entries = values.entries.filter(
(item) => item.item_id && item.quantity,
);
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 = {
...values,
open: submitPayload.status,
entries: transformEntriesToSubmit(entries),
};
// Handle the request success.
const onSuccess = (response) => {
AppToaster.show({
message: intl.get(
isNewMode
? 'the_bill_has_been_created_successfully'
: 'the_bill_has_been_edited_successfully',
{ number: values.bill_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
if (submitPayload.redirect) {
history.push('/bills');
}
if (submitPayload.resetForm) {
resetForm();
}
};
// Handle the request error.
const onError = ({
response: {
data: { errors },
},
}) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
};
if (isNewMode) {
createBillMutate(form).then(onSuccess).catch(onError);
} else {
editBillMutate([bill.id, form]).then(onSuccess).catch(onError);
}
};
return (
<div
className={classNames(
CLASSES.PAGE_FORM,
CLASSES.PAGE_FORM_STRIP_STYLE,
CLASSES.PAGE_FORM_BILL,
)}
>
<Formik
validationSchema={isNewMode ? CreateBillFormSchema : EditBillFormSchema}
initialValues={initialValues}
onSubmit={handleFormSubmit}
>
<Form>
<BillFormHeader />
<BillItemsEntriesEditor />
<BillFormFooter />
<BillFloatingActions />
</Form>
</Formik>
</div>
);
}
export default compose(withCurrentOrganization())(BillForm);

View File

@@ -0,0 +1,52 @@
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import { DATATYPES_LENGTH } from 'common/dataTypes';
import { isBlank } from 'utils';
const BillFormSchema = Yup.object().shape({
vendor_id: Yup.number()
.required()
.label(intl.get('vendor_name_')),
bill_date: Yup.date()
.required()
.label(intl.get('bill_date_')),
due_date: Yup.date()
.required()
.label(intl.get('due_date_')),
bill_number: Yup.string()
.max(DATATYPES_LENGTH.STRING)
.label(intl.get('bill_number_')),
reference_no: Yup.string().nullable().min(1).max(DATATYPES_LENGTH.STRING),
note: Yup.string()
.trim()
.min(1)
.max(DATATYPES_LENGTH.TEXT)
.label(intl.get('note')),
open: Yup.boolean(),
entries: Yup.array().of(
Yup.object().shape({
quantity: Yup.number()
.nullable()
.max(DATATYPES_LENGTH.INT_10)
.when(['rate'], {
is: (rate) => rate,
then: Yup.number().required(),
}),
rate: Yup.number().nullable().max(DATATYPES_LENGTH.INT_10),
item_id: Yup.number()
.nullable()
.when(['quantity', 'rate'], {
is: (quantity, rate) => !isBlank(quantity) && !isBlank(rate),
then: Yup.number().required(),
}),
total: Yup.number().nullable(),
discount: Yup.number().nullable().min(0).max(DATATYPES_LENGTH.INT_10),
description: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
}),
),
});
const CreateBillFormSchema = BillFormSchema;
const EditBillFormSchema = BillFormSchema;
export { CreateBillFormSchema, EditBillFormSchema };

View File

@@ -0,0 +1,43 @@
import React from 'react';
import { FormGroup, TextArea } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { FastField } from 'formik';
import classNames from 'classnames';
import { Postbox, Row, Col } from 'components';
import { CLASSES } from 'common/classes';
import Dragzone from 'components/Dragzone';
import { inputIntent } from 'utils';
// Bill form floating actions.
export default function BillFormFooter() {
return (
<div class={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Postbox title={<T id={'bill_details'} />} defaultOpen={false}>
<Row>
<Col md={8}>
<FastField name={'note'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'note'} />}
className={'form-group--note'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup>
)}
</FastField>
</Col>
<Col md={4}>
<Dragzone
initialFiles={[]}
// onDrop={onDropFiles}
// onDeleteFile={onDropFiles}
hint={<T id={'attachments_maximum'} />}
/>
</Col>
</Row>
</Postbox>
</div>
);
}

View File

@@ -0,0 +1,41 @@
import React, { useMemo } from 'react';
import classNames from 'classnames';
import { sumBy } from 'lodash';
import { useFormikContext } from 'formik';
import intl from 'react-intl-universal';
import { CLASSES } from 'common/classes';
import BillFormHeaderFields from './BillFormHeaderFields';
import { PageFormBigNumber } from 'components';
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
import { compose } from 'redux';
/**
* Fill form header.
*/
function BillFormHeader({
// #withCurrentOrganization
organization: { base_currency },
}) {
const { values } = useFormikContext();
// Calculate the total due amount of bill entries.
const totalDueAmount = useMemo(
() => sumBy(values.entries, 'amount'),
[values.entries],
);
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<BillFormHeaderFields />
<PageFormBigNumber
label={intl.get('due_amount')}
amount={totalDueAmount}
currencyCode={base_currency}
/>
</div>
);
}
export default compose(withCurrentOrganization())(BillFormHeader);

View File

@@ -0,0 +1,145 @@
import React from 'react';
import { FormGroup, InputGroup, Position } from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FormattedMessage as T } from 'components';
import { FastField, ErrorMessage } from 'formik';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import { ContactSelecetList, FieldRequiredHint, Icon } from 'components';
import { vendorsFieldShouldUpdate } from './utils';
import { useBillFormContext } from './BillFormProvider';
import withDialogActions from 'containers/Dialog/withDialogActions';
import {
momentFormatter,
compose,
tansformDateValue,
handleDateChange,
inputIntent,
} from 'utils';
/**
* Fill form header.
*/
function BillFormHeader() {
// Bill form context.
const { vendors } = useBillFormContext();
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
{/* ------- Vendor name ------ */}
<FastField
name={'vendor_id'}
vendors={vendors}
shouldUpdate={vendorsFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'vendor_name'} />}
inline={true}
className={classNames(CLASSES.FILL, 'form-group--vendor')}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name={'vendor_id'} />}
>
<ContactSelecetList
contactsList={vendors}
selectedContactId={value}
defaultSelectText={<T id={'select_vender_account'} />}
onContactSelected={(contact) => {
form.setFieldValue('vendor_id', contact.id);
}}
popoverFill={true}
/>
</FormGroup>
)}
</FastField>
{/* ------- Bill date ------- */}
<FastField name={'bill_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'bill_date'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
className={classNames(CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="bill_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('bill_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
inputProps={{ leftIcon: <Icon icon={'date-range'} /> }}
/>
</FormGroup>
)}
</FastField>
{/* ------- Due date ------- */}
<FastField name={'due_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'due_date'} />}
inline={true}
className={classNames(
'form-group--due-date',
'form-group--select-list',
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, minimal: true }}
inputProps={{
leftIcon: <Icon icon={'date-range'} />,
}}
/>
</FormGroup>
)}
</FastField>
{/* ------- Bill number ------- */}
<FastField name={'bill_number'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'bill_number'} />}
inline={true}
className={('form-group--bill_number', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="bill_number" />}
>
<InputGroup minimal={true} {...field} />
</FormGroup>
)}
</FastField>
{/* ------- Reference ------- */}
<FastField name={'reference_no'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'reference'} />}
inline={true}
className={classNames('form-group--reference', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="reference" />}
>
<InputGroup minimal={true} {...field} />
</FormGroup>
)}
</FastField>
</div>
);
}
export default compose(withDialogActions)(BillFormHeader);

View File

@@ -0,0 +1,18 @@
import React from 'react';
import { useParams } from 'react-router-dom';
import BillForm from './BillForm';
import { BillFormProvider } from './BillFormProvider';
import 'style/pages/Bills/PageForm.scss';
export default function BillFormPage() {
const { id } = useParams();
const billId = parseInt(id, 10);
return (
<BillFormProvider billId={billId}>
<BillForm />
</BillFormProvider>
);
}

View File

@@ -0,0 +1,93 @@
import React, { createContext, useState } from 'react';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import {
useAccounts,
useVendors,
useItems,
useBill,
useSettings,
useCreateBill,
useEditBill,
} from 'hooks/query';
const BillFormContext = createContext();
// Filter all purchasable items only.
const stringifiedFilterRoles = JSON.stringify([
{ index: 1, fieldKey: 'purchasable', value: true, condition: '&&', comparator: 'equals' },
{ index: 2, fieldKey: 'active', value: true, condition: '&&', comparator: 'equals' },
]);
/**
* Bill form provider.
*/
function BillFormProvider({ billId, ...props }) {
// Handle fetch accounts.
const { data: accounts, isLoading: isAccountsLoading } = useAccounts();
// Handle fetch vendors data table
const {
data: { vendors },
isLoading: isVendorsLoading,
} = useVendors({ page_size: 10000 });
// Handle fetch Items data table or list
const {
data: { items },
isLoading: isItemsLoading,
} = useItems({
page_size: 10000,
stringified_filter_roles: stringifiedFilterRoles,
});
// Handle fetch bill details.
const { data: bill, isLoading: isBillLoading } = useBill(billId, {
enabled: !!billId,
});
// Handle fetching bill settings.
const { isFetching: isSettingLoading } = useSettings();
// Form submit payload.
const [submitPayload, setSubmitPayload] = useState({});
// Create and edit bills mutations.
const { mutateAsync: createBillMutate } = useCreateBill();
const { mutateAsync: editBillMutate } = useEditBill();
const isNewMode = !billId;
const provider = {
accounts,
vendors,
items,
bill,
submitPayload,
isNewMode,
isSettingLoading,
isBillLoading,
isAccountsLoading,
isItemsLoading,
isVendorsLoading,
createBillMutate,
editBillMutate,
setSubmitPayload,
};
return (
<DashboardInsider
loading={
isVendorsLoading || isItemsLoading || isAccountsLoading || isBillLoading
}
name={'bill-form'}
>
<BillFormContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const useBillFormContext = () => React.useContext(BillFormContext);
export { BillFormProvider, useBillFormContext };

View File

@@ -0,0 +1,44 @@
import React from 'react';
import classNames from 'classnames';
import { FastField } from 'formik';
import { CLASSES } from 'common/classes';
import { useBillFormContext } from './BillFormProvider';
import ItemsEntriesTable from 'containers/Entries/ItemsEntriesTable';
import { entriesFieldShouldUpdate } from './utils';
import { ITEM_TYPE } from 'containers/Entries/utils';
/**
* Bill form body.
*/
export default function BillFormBody({ defaultBill }) {
const { items } = useBillFormContext();
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}
itemType={ITEM_TYPE.PURCHASABLE}
landedCost={true}
/>
)}
</FastField>
</div>
);
}

View File

@@ -0,0 +1,120 @@
import moment from 'moment';
import intl from 'react-intl-universal';
import * as R from 'ramda';
import { Intent } from '@blueprintjs/core';
import { AppToaster } from 'components';
import {
defaultFastFieldShouldUpdate,
transformToForm,
repeatValue,
orderingLinesIndexes,
} from 'utils';
import {
updateItemsEntriesTotal,
ensureEntriesHaveEmptyLine,
} from 'containers/Entries/utils';
import { isLandedCostDisabled } from '../../../Entries/utils';
export const MIN_LINES_NUMBER = 4;
// Default bill entry.
export const defaultBillEntry = {
index: 0,
item_id: '',
rate: '',
discount: '',
quantity: '',
description: '',
amount: '',
landed_cost: false,
};
// Default bill.
export const defaultBill = {
vendor_id: '',
bill_number: '',
bill_date: moment(new Date()).format('YYYY-MM-DD'),
due_date: moment(new Date()).format('YYYY-MM-DD'),
reference_no: '',
note: '',
open: '',
entries: [...repeatValue(defaultBillEntry, MIN_LINES_NUMBER)],
};
/**
* Transformes the bill to initial values of edit form.
*/
export const transformToEditForm = (bill) => {
const initialEntries = [
...bill.entries.map((entry) => ({
...transformToForm(entry, defaultBillEntry),
landed_cost_disabled: isLandedCostDisabled(entry.item),
})),
...repeatValue(
defaultBillEntry,
Math.max(MIN_LINES_NUMBER - bill.entries.length, 0),
),
];
const entries = R.compose(
ensureEntriesHaveEmptyLine(defaultBillEntry),
updateItemsEntriesTotal,
)(initialEntries);
return {
...transformToForm(bill, defaultBill),
entries,
};
};
/**
* Transformes bill entries to submit request.
*/
export const transformEntriesToSubmit = (entries) => {
const transformBillEntry = R.curry(transformToForm)(R.__, defaultBillEntry);
return R.compose(orderingLinesIndexes, R.map(transformBillEntry))(entries);
};
/**
* Handle delete errors.
*/
export const handleDeleteErrors = (errors) => {
if (
errors.find((error) => error.type === 'BILL_HAS_ASSOCIATED_PAYMENT_ENTRIES')
) {
AppToaster.show({
message: intl.get('cannot_delete_bill_that_has_payment_transactions'),
intent: Intent.DANGER,
});
}
if (
errors.find((error) => error.type === 'BILL_HAS_ASSOCIATED_LANDED_COSTS')
) {
AppToaster.show({
message: intl.get(
'cannot_delete_bill_that_has_associated_landed_cost_transactions',
),
intent: Intent.DANGER,
});
}
};
/**
* Detarmines vendors fast field should update
*/
export const vendorsFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.vendors !== oldProps.vendors ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Detarmines entries fast field should update.
*/
export const entriesFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.items !== oldProps.items ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};