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,18 @@
import React from 'react';
import { AllocateLandedCostDialogProvider } from './AllocateLandedCostDialogProvider';
import AllocateLandedCostForm from './AllocateLandedCostForm';
/**
* Allocate landed cost dialog content.
*/
export default function AllocateLandedCostDialogContent({
// #ownProps
dialogName,
billId,
}) {
return (
<AllocateLandedCostDialogProvider billId={billId} dialogName={dialogName}>
<AllocateLandedCostForm />
</AllocateLandedCostDialogProvider>
);
}

View File

@@ -0,0 +1,47 @@
import React from 'react';
import { DialogContent } from 'components';
import { useBill, useCreateLandedCost } from 'hooks/query';
const AllocateLandedCostDialogContext = React.createContext();
/**
* Allocate landed cost provider.
*/
function AllocateLandedCostDialogProvider({
billId,
query,
dialogName,
...props
}) {
// Handle fetch bill details.
const { isLoading: isBillLoading, data: bill } = useBill(billId, {
enabled: !!billId,
});
// Create landed cost mutations.
const { mutateAsync: createLandedCostMutate } = useCreateLandedCost();
// provider payload.
const provider = {
isBillLoading,
bill,
dialogName,
query,
createLandedCostMutate,
billId,
};
return (
<DialogContent isLoading={isBillLoading} name={'allocate-landed-cost'}>
<AllocateLandedCostDialogContext.Provider value={provider} {...props} />
</DialogContent>
);
}
const useAllocateLandedConstDialogContext = () =>
React.useContext(AllocateLandedCostDialogContext);
export {
AllocateLandedCostDialogProvider,
useAllocateLandedConstDialogContext,
};

View File

@@ -0,0 +1,72 @@
import React from 'react';
import intl from 'react-intl-universal';
import { MoneyFieldCell, DataTableEditable } from 'components';
import { compose, updateTableCell } from 'utils';
/**
* Allocate landed cost entries table.
*/
export default function AllocateLandedCostEntriesTable({
onUpdateData,
entries,
}) {
// Allocate landed cost entries table columns.
const columns = React.useMemo(
() => [
{
Header: intl.get('item'),
accessor: 'item.name',
disableSortBy: true,
width: '150',
},
{
Header: intl.get('quantity'),
accessor: 'quantity',
disableSortBy: true,
width: '100',
},
{
Header: intl.get('rate'),
accessor: 'rate',
disableSortBy: true,
width: '100',
},
{
Header: intl.get('amount'),
accessor: 'amount',
disableSortBy: true,
width: '100',
},
{
Header: intl.get('cost'),
accessor: 'cost',
width: '150',
Cell: MoneyFieldCell,
disableSortBy: true,
},
],
[],
);
// Handle update data.
const handleUpdateData = React.useCallback(
(rowIndex, columnId, value) => {
const newRows = compose(updateTableCell(rowIndex, columnId, value))(
entries,
);
onUpdateData(newRows);
},
[onUpdateData, entries],
);
return (
<DataTableEditable
columns={columns}
data={entries}
payload={{
errors: [],
updateData: handleUpdateData,
}}
/>
);
}

View File

@@ -0,0 +1,42 @@
import React from 'react';
import { Intent, Button, Classes } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { useFormikContext } from 'formik';
import { useAllocateLandedConstDialogContext } from './AllocateLandedCostDialogProvider';
import withDialogActions from 'containers/Dialog/withDialogActions';
import { compose } from 'utils';
function AllocateLandedCostFloatingActions({
// #withDialogActions
closeDialog,
}) {
// Formik context.
const { isSubmitting } = useFormikContext();
const { dialogName } = useAllocateLandedConstDialogContext();
// Handle cancel button click.
const handleCancelBtnClick = (event) => {
closeDialog(dialogName);
};
return (
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button onClick={handleCancelBtnClick} style={{ minWidth: '85px' }}>
<T id={'cancel'} />
</Button>
<Button
intent={Intent.PRIMARY}
style={{ minWidth: '85px' }}
type="submit"
loading={isSubmitting}
>
{<T id={'save'} />}
</Button>
</div>
</div>
);
}
export default compose(withDialogActions)(AllocateLandedCostFloatingActions);

View File

@@ -0,0 +1,102 @@
import React from 'react';
import { Formik } from 'formik';
import { Intent } from '@blueprintjs/core';
import intl from 'react-intl-universal';
import moment from 'moment';
import { sumBy } from 'lodash';
import 'style/pages/AllocateLandedCost/AllocateLandedCostForm.scss';
import { AppToaster } from 'components';
import { AllocateLandedCostFormSchema } from './AllocateLandedCostForm.schema';
import { useAllocateLandedConstDialogContext } from './AllocateLandedCostDialogProvider';
import AllocateLandedCostFormContent from './AllocateLandedCostFormContent';
import withDialogActions from 'containers/Dialog/withDialogActions';
import { compose, transformToForm } from 'utils';
// Default form initial values.
const defaultInitialValues = {
transaction_type: 'Bill',
transaction_date: moment(new Date()).format('YYYY-MM-DD'),
transaction_id: '',
transaction_entry_id: '',
amount: '',
allocation_method: 'quantity',
items: [
{
entry_id: '',
cost: '',
},
],
};
/**
* Allocate landed cost form.
*/
function AllocateLandedCostForm({
// #withDialogActions
closeDialog,
}) {
const { dialogName, bill, billId, createLandedCostMutate } =
useAllocateLandedConstDialogContext();
// Initial form values.
const initialValues = {
...defaultInitialValues,
items: bill.entries.map((entry) => ({
...entry,
entry_id: entry.id,
cost: '',
})),
};
const amount = sumBy(initialValues.items, 'amount');
// Handle form submit.
const handleFormSubmit = (values, { setSubmitting }) => {
setSubmitting(false);
// Filters the entries has no cost.
const entries = values.items
.filter((entry) => entry.entry_id && entry.cost)
.map((entry) => transformToForm(entry, defaultInitialValues.items[0]));
if (entries.length <= 0) {
AppToaster.show({ message: 'Something wrong!', intent: Intent.DANGER });
return;
}
const form = {
...values,
items: entries,
};
// Handle the request success.
const onSuccess = (response) => {
AppToaster.show({
message: intl.get('the_landed_cost_has_been_created_successfully'),
intent: Intent.SUCCESS,
});
setSubmitting(false);
closeDialog(dialogName);
};
// Handle the request error.
const onError = () => {
setSubmitting(false);
AppToaster.show({ message: 'Something went wrong!', intent: Intent.DANGER });
};
createLandedCostMutate([billId, form]).then(onSuccess).catch(onError);
};
// Computed validation schema.
const validationSchema = AllocateLandedCostFormSchema(amount);
return (
<Formik
validationSchema={validationSchema}
initialValues={initialValues}
onSubmit={handleFormSubmit}
component={AllocateLandedCostFormContent}
/>
);
}
export default compose(withDialogActions)(AllocateLandedCostForm);

View File

@@ -0,0 +1,18 @@
import * as Yup from 'yup';
import intl from 'react-intl-universal';
export const AllocateLandedCostFormSchema = (minAmount) =>
Yup.object().shape({
transaction_type: Yup.string().label(intl.get('transaction_type')),
transaction_date: Yup.date().label(intl.get('transaction_date')),
transaction_id: Yup.string().label(intl.get('transaction_number')),
transaction_entry_id: Yup.string().label(intl.get('transaction_line')),
amount: Yup.number().max(minAmount).label(intl.get('amount')),
allocation_method: Yup.string().trim(),
items: Yup.array().of(
Yup.object().shape({
entry_id: Yup.number().nullable(),
cost: Yup.number().nullable(),
}),
),
});

View File

@@ -0,0 +1,26 @@
import React from 'react';
import { FastField } from 'formik';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import AllocateLandedCostEntriesTable from './AllocateLandedCostEntriesTable';
export default function AllocateLandedCostFormBody() {
return (
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
<FastField name={'items'}>
{({
form: { setFieldValue, values },
field: { value },
meta: { error, touched },
}) => (
<AllocateLandedCostEntriesTable
entries={value}
onUpdateData={(newEntries) => {
setFieldValue('items', newEntries);
}}
/>
)}
</FastField>
</div>
);
}

View File

@@ -0,0 +1,16 @@
import React from 'react';
import { Form } from 'formik';
import AllocateLandedCostFormFields from './AllocateLandedCostFormFields';
import AllocateLandedCostFloatingActions from './AllocateLandedCostFloatingActions';
/**
* Allocate landed cost form content.
*/
export default function AllocateLandedCostFormContent() {
return (
<Form>
<AllocateLandedCostFormFields />
<AllocateLandedCostFloatingActions />
</Form>
);
}

View File

@@ -0,0 +1,202 @@
import React from 'react';
import { FastField, Field, ErrorMessage, useFormikContext } from 'formik';
import {
Classes,
FormGroup,
RadioGroup,
Radio,
InputGroup,
} from '@blueprintjs/core';
import classNames from 'classnames';
import { FormattedMessage as T, If } from 'components';
import intl from 'react-intl-universal';
import { inputIntent, handleStringChange } from 'utils';
import { FieldRequiredHint, ListSelect } from 'components';
import { CLASSES } from 'common/classes';
import allocateLandedCostType from 'common/allocateLandedCostType';
import { useLandedCostTransaction } from 'hooks/query';
import AllocateLandedCostFormBody from './AllocateLandedCostFormBody';
import { getEntriesByTransactionId, allocateCostToEntries } from './utils';
/**
* Allocate landed cost form fields.
*/
export default function AllocateLandedCostFormFields() {
const { values } = useFormikContext();
const {
data: { transactions },
} = useLandedCostTransaction(values.transaction_type);
// Retrieve entries of the given transaction id.
const transactionEntries = React.useMemo(
() => getEntriesByTransactionId(transactions, values.transaction_id),
[transactions, values.transaction_id],
);
return (
<div className={Classes.DIALOG_BODY}>
{/*------------Transaction type -----------*/}
<FastField name={'transaction_type'}>
{({
form: { values, setFieldValue },
field: { value },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'transaction_type'} />}
labelInfo={<FieldRequiredHint />}
helperText={<ErrorMessage name="transaction_type" />}
intent={inputIntent({ error, touched })}
inline={true}
className={classNames(CLASSES.FILL, 'form-group--transaction_type')}
>
<ListSelect
items={allocateLandedCostType}
onItemSelect={(type) => {
setFieldValue('transaction_type', type.value);
setFieldValue('transaction_id', '');
setFieldValue('transaction_entry_id', '');
}}
filterable={false}
selectedItem={value}
selectedItemProp={'value'}
textProp={'name'}
popoverProps={{ minimal: true }}
/>
</FormGroup>
)}
</FastField>
{/*------------ Transaction -----------*/}
<Field name={'transaction_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'transaction_id'} />}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="transaction_id" />}
className={classNames(CLASSES.FILL, 'form-group--transaction_id')}
inline={true}
>
<ListSelect
items={transactions}
onItemSelect={({ id }) => {
form.setFieldValue('transaction_id', id);
form.setFieldValue('transaction_entry_id', '');
}}
filterable={false}
selectedItem={value}
selectedItemProp={'id'}
textProp={'name'}
labelProp={'id'}
defaultText={intl.get('Select transaction')}
popoverProps={{ minimal: true }}
/>
</FormGroup>
)}
</Field>
{/*------------ Transaction line -----------*/}
<If condition={transactionEntries.length > 0}>
<Field name={'transaction_entry_id'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'transaction_line'} />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="transaction_entry_id" />}
className={classNames(
CLASSES.FILL,
'form-group--transaction_entry_id',
)}
inline={true}
>
<ListSelect
items={transactionEntries}
onItemSelect={({ id, amount }) => {
const { items, allocation_method } = form.values;
form.setFieldValue('amount', amount);
form.setFieldValue('transaction_entry_id', id);
form.setFieldValue(
'items',
allocateCostToEntries(amount, allocation_method, items),
);
}}
filterable={false}
selectedItem={value}
selectedItemProp={'id'}
textProp={'name'}
defaultText={intl.get('Select transaction entry')}
popoverProps={{ minimal: true }}
/>
</FormGroup>
)}
</Field>
</If>
{/*------------ Amount -----------*/}
<FastField name={'amount'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'amount'} />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="amount" />}
className={'form-group--amount'}
inline={true}
>
<InputGroup
{...field}
onBlur={(e) => {
const amount = e.target.value;
const { allocation_method, items } = form.values;
form.setFieldValue(
'items',
allocateCostToEntries(amount, allocation_method, items),
);
}}
/>
</FormGroup>
)}
</FastField>
{/*------------ Allocation method -----------*/}
<Field name={'allocation_method'}>
{({ form, field: { value }, meta: { touched, error } }) => (
<FormGroup
medium={true}
label={<T id={'allocation_method'} />}
labelInfo={<FieldRequiredHint />}
className={'form-group--allocation_method'}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="allocation_method" />}
inline={true}
>
<RadioGroup
onChange={handleStringChange((_value) => {
const { amount, items, allocation_method } = form.values;
form.setFieldValue('allocation_method', _value);
form.setFieldValue(
'items',
allocateCostToEntries(amount, allocation_method, items),
);
})}
selectedValue={value}
inline={true}
>
<Radio label={<T id={'quantity'} />} value="quantity" />
<Radio label={<T id={'valuation'} />} value="value" />
</RadioGroup>
</FormGroup>
)}
</Field>
{/*------------ Allocate Landed cost Table -----------*/}
<AllocateLandedCostFormBody />
</div>
);
}

View File

@@ -0,0 +1,36 @@
import React, { lazy } from 'react';
import { FormattedMessage as T, Dialog, DialogSuspense } from 'components';
import withDialogRedux from 'components/DialogReduxConnect';
import { compose } from 'utils';
const AllocateLandedCostDialogContent = lazy(() =>
import('./AllocateLandedCostDialogContent'),
);
/**
* Allocate landed cost dialog.
*/
function AllocateLandedCostDialog({
dialogName,
payload = { billId: null },
isOpen,
}) {
return (
<Dialog
name={dialogName}
title={<T id={'allocate_landed_coast'} />}
canEscapeKeyClose={true}
isOpen={isOpen}
className="dialog--allocate-landed-cost-form"
>
<DialogSuspense>
<AllocateLandedCostDialogContent
billId={payload.billId}
dialogName={dialogName}
/>
</DialogSuspense>
</Dialog>
);
}
export default compose(withDialogRedux())(AllocateLandedCostDialog);

View File

@@ -0,0 +1,62 @@
import { sumBy, round } from 'lodash';
import * as R from 'ramda';
/**
* Retrieve transaction entries of the given transaction id.
*/
export function getEntriesByTransactionId(transactions, id) {
const transaction = transactions.find((trans) => trans.id === id);
return transaction ? transaction.entries : [];
}
export function allocateCostToEntries(total, allocateType, entries) {
return R.compose(
R.when(
R.always(allocateType === 'value'),
R.curry(allocateCostByValue)(total),
),
R.when(
R.always(allocateType === 'quantity'),
R.curry(allocateCostByQuantity)(total),
),
)(entries);
}
/**
* Allocate total cost on entries on value.
* @param {*} entries
* @param {*} total
* @returns
*/
export function allocateCostByValue(total, entries) {
const totalAmount = sumBy(entries, 'amount');
const _entries = entries.map((entry) => ({
...entry,
percentageOfValue: entry.amount / totalAmount,
}));
return _entries.map((entry) => ({
...entry,
cost: round(entry.percentageOfValue * total, 2),
}));
}
/**
* Allocate total cost on entries by quantity.
* @param {*} entries
* @param {*} total
* @returns
*/
export function allocateCostByQuantity(total, entries) {
const totalQuantity = sumBy(entries, 'quantity');
const _entries = entries.map((entry) => ({
...entry,
percentageOfQuantity: entry.quantity / totalQuantity,
}));
return _entries.map((entry) => ({
...entry,
cost: round(entry.percentageOfQuantity * total, 2),
}));
}