Merge branch 'feature/landed-cost'

This commit is contained in:
a.bouhuolia
2021-07-27 05:49:20 +02:00
237 changed files with 5482 additions and 926 deletions

View File

@@ -67,4 +67,4 @@ export const useManualJournalsColumns = () => {
],
[],
);
};
};

View File

@@ -3,16 +3,28 @@ import { FastField } from 'formik';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import MakeJournalEntriesTable from './MakeJournalEntriesTable';
import { defaultEntry, MIN_LINES_NUMBER } from './utils';
import { entriesFieldShouldUpdate, defaultEntry, MIN_LINES_NUMBER } from './utils';
import { useMakeJournalFormContext } from './MakeJournalProvider';
/**
* Make journal entries field.
*/
export default function MakeJournalEntriesField() {
const { accounts, contacts } = useMakeJournalFormContext();
return (
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
<FastField name={'entries'}>
{({ form:{values ,setFieldValue}, field: { value }, meta: { error, touched } }) => (
<FastField
name={'entries'}
contacts={contacts}
accounts={accounts}
shouldUpdate={entriesFieldShouldUpdate}
>
{({
form: { values, setFieldValue },
field: { value },
meta: { error, touched },
}) => (
<MakeJournalEntriesTable
onChange={(entries) => {
setFieldValue('entries', entries);

View File

@@ -29,7 +29,10 @@ import {
import withSettings from 'containers/Settings/withSettings';
import { useMakeJournalFormContext } from './MakeJournalProvider';
import withDialogActions from 'containers/Dialog/withDialogActions';
import { useObserveJournalNoSettings } from './utils';
import {
currenciesFieldShouldUpdate,
useObserveJournalNoSettings,
} from './utils';
/**
* Make journal entries header.
*/
@@ -182,7 +185,11 @@ function MakeJournalEntriesHeader({
</FastField>
{/*------------ Currency -----------*/}
<FastField name={'currency_code'}>
<FastField
name={'currency_code'}
currencies={currencies}
shouldUpdate={currenciesFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'currency'} />}

View File

@@ -1,13 +1,13 @@
import React from 'react';
import { Intent } from '@blueprintjs/core';
import { sumBy, setWith, toSafeInteger, get, values } from 'lodash';
import { sumBy, setWith, toSafeInteger, get } from 'lodash';
import moment from 'moment';
import {
transactionNumber,
updateTableRow,
repeatValue,
transformToForm,
defaultFastFieldShouldUpdate,
} from 'utils';
import { AppToaster } from 'components';
import intl from 'react-intl-universal';
@@ -123,17 +123,17 @@ export const transformErrors = (resErrors, { setErrors, errors }) => {
setEntriesErrors(error.indexes, 'contact_id', 'error');
}
if ((error = getError(ERROR.ENTRIES_SHOULD_ASSIGN_WITH_CONTACT))) {
if (error.meta.find(meta => meta.contact_type === 'customer')) {
if (error.meta.find((meta) => meta.contact_type === 'customer')) {
toastMessages.push(
intl.get('receivable_accounts_should_assign_with_customers'),
);
}
if (error.meta.find(meta => meta.contact_type === 'vendor')) {
if (error.meta.find((meta) => meta.contact_type === 'vendor')) {
toastMessages.push(
intl.get('payable_accounts_should_assign_with_vendors'),
);
}
const indexes = error.meta.map((meta => meta.indexes)).flat();
const indexes = error.meta.map((meta) => meta.indexes).flat();
setEntriesErrors(indexes, 'contact_id', 'error');
}
if ((error = getError(ERROR.JOURNAL_NUMBER_ALREADY_EXISTS))) {
@@ -159,7 +159,28 @@ export const useObserveJournalNoSettings = (prefix, nextNumber) => {
const { setFieldValue } = useFormikContext();
React.useEffect(() => {
const journalNo = transactionNumber(prefix, nextNumber);
const journalNo = transactionNumber(prefix, nextNumber);
setFieldValue('journal_number', journalNo);
}, [setFieldValue, prefix, nextNumber]);
};
/**
* Detarmines entries fast field should update.
*/
export const entriesFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.accounts !== oldProps.accounts ||
newProps.contacts !== oldProps.contacts ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Detarmines currencies fast field should update.
*/
export const currenciesFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.currencies !== oldProps.currencies ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};

View File

@@ -0,0 +1,67 @@
import React from 'react';
import { Intent, Alert } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import intl from 'react-intl-universal';
import { useDeleteLandedCost } from 'hooks/query';
import { AppToaster } from 'components';
import withAlertActions from 'containers/Alert/withAlertActions';
import withAlertStoreConnect from 'containers/Alert/withAlertStoreConnect';
import { compose } from 'utils';
/**
* Bill transaction delete alert.
*/
function BillTransactionDeleteAlert({
name,
// #withAlertStoreConnect
isOpen,
payload: { BillId },
// #withAlertActions
closeAlert,
}) {
const { mutateAsync: deleteLandedCostMutate, isLoading } =
useDeleteLandedCost();
// Handle cancel delete.
const handleCancelAlert = () => {
closeAlert(name);
};
// Handle confirm delete .
const handleConfirmLandedCostDelete = () => {
deleteLandedCostMutate(BillId)
.then(() => {
AppToaster.show({
message: intl.get('the_landed_cost_has_been_deleted_successfully'),
intent: Intent.SUCCESS,
});
closeAlert(name);
})
.catch(() => {
closeAlert(name);
});
};
return (
<Alert
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={<T id={'delete'} />}
icon="trash"
intent={Intent.DANGER}
isOpen={isOpen}
onCancel={handleCancelAlert}
onConfirm={handleConfirmLandedCostDelete}
loading={isLoading}
>
<p><T id={`Once your delete this located landed cost, you won't be able to restore it later, Are your sure you want to delete this transaction?`}/></p>
</Alert>
);
}
export default compose(
withAlertStoreConnect(),
withAlertActions,
)(BillTransactionDeleteAlert);

View File

@@ -21,11 +21,7 @@ function ExpenseDeleteAlert({
isOpen,
payload: { expenseId },
}) {
const {
mutateAsync: deleteExpenseMutate,
isLoading,
} = useDeleteExpense();
const { mutateAsync: deleteExpenseMutate, isLoading } = useDeleteExpense();
// Handle cancel expense journal.
const handleCancelExpenseDelete = () => {
@@ -34,17 +30,34 @@ function ExpenseDeleteAlert({
// Handle confirm delete expense.
const handleConfirmExpenseDelete = () => {
deleteExpenseMutate(expenseId).then(() => {
AppToaster.show({
message: intl.get(
'the_expense_has_been_deleted_successfully',
{ number: expenseId },
),
intent: Intent.SUCCESS,
});
}).finally(() => {
closeAlert('expense-delete');
});
deleteExpenseMutate(expenseId)
.then(() => {
AppToaster.show({
message: intl.get('the_expense_has_been_deleted_successfully', {
number: expenseId,
}),
intent: Intent.SUCCESS,
});
closeAlert('expense-delete');
})
.catch(
({
response: {
data: { errors },
},
}) => {
if (
errors.find((e) => e.type === 'EXPENSE_HAS_ASSOCIATED_LANDED_COST')
) {
AppToaster.show({
intent: Intent.DANGER,
message: intl.get(
'couldn_t_delete_expense_transaction_has_associated_located_landed_cost_transaction',
),
});
}
},
);
};
return (
@@ -68,4 +81,4 @@ function ExpenseDeleteAlert({
export default compose(
withAlertStoreConnect(),
withAlertActions,
)(ExpenseDeleteAlert);
)(ExpenseDeleteAlert);

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, updateTableRow } 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(updateTableRow(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),
}));
}

View File

@@ -26,13 +26,10 @@ function PaymentViaLicenseDialogContent({
// #withDialog
closeDialog,
}) {
const history = useHistory();
// Payment via voucher
const {
mutateAsync: paymentViaVoucherMutate,
} = usePaymentByVoucher();
const { mutateAsync: paymentViaVoucherMutate } = usePaymentByVoucher();
// Handle submit.
const handleSubmit = (values, { setSubmitting, setErrors }) => {
@@ -41,7 +38,7 @@ function PaymentViaLicenseDialogContent({
paymentViaVoucherMutate({ ...values })
.then(() => {
Toaster.show({
message: 'Payment has been done successfully.',
message: intl.get('payment_has_been_done_successfully'),
intent: Intent.SUCCESS,
});
return closeDialog('payment-via-voucher');

View File

@@ -1,4 +1,7 @@
import React from 'react';
import 'style/components/Drawers/AccountDrawer.scss';
import { AccountDrawerProvider } from './AccountDrawerProvider';
import AccountDrawerDetails from './AccountDrawerDetails';

View File

@@ -5,8 +5,6 @@ import AccountDrawerHeader from './AccountDrawerHeader';
import AccountDrawerTable from './AccountDrawerTable';
import { useAccountDrawerContext } from './AccountDrawerProvider';
import 'style/components/Drawer/AccountDrawer.scss';
/**
* Account view details.
*/

View File

@@ -0,0 +1,13 @@
import React from 'react';
import BillLocatedLandedCostDeleteAlert from 'containers/Alerts/Bills/BillLocatedLandedCostDeleteAlert';
/**
* Bill drawer alert.
*/
export default function BillDrawerAlerts() {
return (
<div class="bills-alerts">
<BillLocatedLandedCostDeleteAlert name="bill-located-cost-delete" />
</div>
);
}

View File

@@ -0,0 +1,22 @@
import React from 'react';
import 'style/components/Drawers/BillDrawer.scss';
import { BillDrawerProvider } from './BillDrawerProvider';
import BillDrawerDetails from './BillDrawerDetails';
import BillDrawerAlerts from './BillDrawerAlerts';
/**
* Bill drawer content.
*/
export default function BillDrawerContent({
// #ownProp
bill,
}) {
return (
<BillDrawerProvider billId={bill}>
<BillDrawerDetails />
<BillDrawerAlerts />
</BillDrawerProvider>
);
}

View File

@@ -0,0 +1,23 @@
import React from 'react';
import { Tabs, Tab } from '@blueprintjs/core';
import intl from 'react-intl-universal';
import LocatedLandedCostTable from './LocatedLandedCostTable';
/**
* Bill view details.
*/
export default function BillDrawerDetails() {
return (
<div className="bill-drawer">
<Tabs animate={true} large={true} selectedTabId="landed_cost">
<Tab title={intl.get('details')} id={'details'} disabled={true} />
<Tab
title={intl.get('located_landed_cost')}
id={'landed_cost'}
panel={<LocatedLandedCostTable />}
/>
</Tabs>
</div>
);
}

View File

@@ -0,0 +1,37 @@
import React from 'react';
import intl from 'react-intl-universal';
import { DrawerHeaderContent, DashboardInsider } from 'components';
import { useBillLocatedLandedCost } from 'hooks/query';
const BillDrawerContext = React.createContext();
/**
* Bill drawer provider.
*/
function BillDrawerProvider({ billId, ...props }) {
// Handle fetch bill located landed cost transaction.
const { isLoading: isLandedCostLoading, data: transactions } =
useBillLocatedLandedCost(billId, {
enabled: !!billId,
});
//provider.
const provider = {
transactions,
billId,
};
return (
<DashboardInsider loading={isLandedCostLoading}>
<DrawerHeaderContent
name="bill-drawer"
title={intl.get('bill_details')}
/>
<BillDrawerContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const useBillDrawerContext = () => React.useContext(BillDrawerContext);
export { BillDrawerProvider, useBillDrawerContext };

View File

@@ -0,0 +1,91 @@
import React from 'react';
import { DataTable, Card } from 'components';
import { Button, Classes, NavbarGroup } from '@blueprintjs/core';
import { useLocatedLandedCostColumns, ActionsMenu } from './components';
import { useBillDrawerContext } from './BillDrawerProvider';
import withAlertsActions from 'containers/Alert/withAlertActions';
import withDialogActions from 'containers/Dialog/withDialogActions';
import withDrawerActions from 'containers/Drawer/withDrawerActions';
import { compose } from 'utils';
import DashboardActionsBar from 'components/Dashboard/DashboardActionsBar';
import Icon from 'components/Icon';
/**
* Located landed cost table.
*/
function LocatedLandedCostTable({
// #withAlertsActions
openAlert,
// #withDialogActions
openDialog,
// #withDrawerActions
openDrawer,
}) {
const columns = useLocatedLandedCostColumns();
const { transactions, billId } = useBillDrawerContext();
// Handle the transaction delete action.
const handleDeleteTransaction = ({ id }) => {
openAlert('bill-located-cost-delete', { BillId: id });
};
// Handle allocate landed cost button click.
const handleAllocateCostClick = () => {
openDialog('allocate-landed-cost', { billId });
};
// Handle from transaction link click.
const handleFromTransactionClick = (original) => {
const { from_transaction_type, from_transaction_id } = original;
switch (from_transaction_type) {
case 'Expense':
openDrawer('expense-drawer', { expenseId: from_transaction_id });
break;
case 'Bill':
default:
openDrawer('bill-drawer', { billId: from_transaction_id });
break;
}
};
return (
<div>
<DashboardActionsBar>
<NavbarGroup>
<Button
className={Classes.MINIMAL}
icon={<Icon icon="receipt-24" />}
text={'Allocate landed cost'}
onClick={handleAllocateCostClick}
/>
</NavbarGroup>
</DashboardActionsBar>
<Card>
<DataTable
columns={columns}
data={transactions}
ContextMenu={ActionsMenu}
payload={{
onDelete: handleDeleteTransaction,
onFromTranscationClick: handleFromTransactionClick,
}}
className={'datatable--landed-cost-transactions'}
/>
</Card>
</div>
);
}
export default compose(
withAlertsActions,
withDialogActions,
withDrawerActions,
)(LocatedLandedCostTable);

View File

@@ -0,0 +1,75 @@
import React from 'react';
import intl from 'react-intl-universal';
import { Intent, MenuItem, Menu } from '@blueprintjs/core';
import { safeCallback } from 'utils';
import { Icon } from 'components';
/**
* Actions menu.
*/
export function ActionsMenu({ row: { original }, payload: { onDelete } }) {
return (
<Menu>
<MenuItem
icon={<Icon icon="trash-16" iconSize={16} />}
text={intl.get('delete_transaction')}
intent={Intent.DANGER}
onClick={safeCallback(onDelete, original)}
/>
</Menu>
);
}
/**
* From transaction table cell.
*/
export function FromTransactionCell({
row: { original },
payload: { onFromTranscationClick }
}) {
// Handle the link click
const handleAnchorClick = () => {
onFromTranscationClick && onFromTranscationClick(original);
};
return (
<a href="#" onClick={handleAnchorClick}>
{original.from_transaction_type} {original.from_transaction_id}
</a>
);
}
/**
* Retrieve bill located landed cost table columns.
*/
export function useLocatedLandedCostColumns() {
return React.useMemo(
() => [
{
Header: intl.get('name'),
accessor: 'description',
width: 150,
className: 'name',
},
{
Header: intl.get('amount'),
accessor: 'formatted_amount',
width: 100,
className: 'amount',
},
{
id: 'from_transaction',
Header: intl.get('From transaction'),
Cell: FromTransactionCell,
width: 100,
className: 'from-transaction',
},
{
Header: intl.get('allocation_method'),
accessor: 'allocation_method_formatted',
width: 100,
className: 'allocation-method',
},
],
[],
);
}

View File

@@ -0,0 +1,27 @@
import React from 'react';
import { Drawer, DrawerSuspense } from 'components';
import withDrawers from 'containers/Drawer/withDrawers';
import { compose } from 'utils';
const BillDrawerContent = React.lazy(() => import('./BillDrawerContent'));
/**
* Bill drawer.
*/
function BillDrawer({
name,
// #withDrawer
isOpen,
payload: { billId },
}) {
return (
<Drawer isOpen={isOpen} name={name} size={'750px'}>
<DrawerSuspense>
<BillDrawerContent bill={billId} />
</DrawerSuspense>
</Drawer>
);
}
export default compose(withDrawers())(BillDrawer);

View File

@@ -1,4 +1,7 @@
import React from 'react';
import 'style/components/Drawers/ViewDetails.scss';
import { ExpenseDrawerProvider } from './ExpenseDrawerProvider';
import ExpenseDrawerDetails from './ExpenseDrawerDetails';

View File

@@ -4,7 +4,6 @@ import ExpenseDrawerHeader from './ExpenseDrawerHeader';
import ExpenseDrawerTable from './ExpenseDrawerTable';
import ExpenseDrawerFooter from './ExpenseDrawerFooter';
import { useExpenseDrawerContext } from './ExpenseDrawerProvider';
import 'style/components/Drawer/ViewDetails.scss';
/**
* Expense view details.

View File

@@ -1,6 +1,7 @@
import React, { lazy } from 'react';
import { Drawer, DrawerSuspense } from 'components';
import withDrawers from 'containers/Drawer/withDrawers';
import intl from 'react-intl-universal';
import { compose } from 'utils';
@@ -17,7 +18,7 @@ function ExpenseDrawer({
payload: { expenseId, title },
}) {
return (
<Drawer isOpen={isOpen} name={name} title={'Expense'}>
<Drawer isOpen={isOpen} name={name} title={intl.get('expense')}>
<DrawerSuspense>
<ExpenseDrawerContent expenseId={expenseId} />
</DrawerSuspense>

View File

@@ -1,4 +1,7 @@
import React from 'react';
import 'style/components/Drawers/ViewDetails.scss';
import { ManualJournalDrawerProvider } from './ManualJournalDrawerProvider';
import ManualJournalDrawerDetails from './ManualJournalDrawerDetails';

View File

@@ -6,8 +6,6 @@ import ManualJournalDrawerFooter from './ManualJournalDrawerFooter';
import { useManualJournalDrawerContext } from 'containers/Drawers/ManualJournalDrawer/ManualJournalDrawerProvider';
import 'style/components/Drawer/ViewDetails.scss';
/**
* Manual journal view details.
*/

View File

@@ -1,4 +1,5 @@
import React from 'react';
import intl from 'react-intl-universal';
import { useJournal } from 'hooks/query';
import { DashboardInsider, DrawerHeaderContent } from 'components';
@@ -25,7 +26,9 @@ function ManualJournalDrawerProvider({ manualJournalId, ...props }) {
<DashboardInsider loading={isJournalLoading}>
<DrawerHeaderContent
name={'journal-drawer'}
title={`Manual Journal ${manualJournal?.journal_number}`}
title={intl.get('manual_journal_number', {
number: manualJournal?.journal_number,
})}
/>
<ManualJournalDrawerContext.Provider value={provider} {...props} />
</DashboardInsider>

View File

@@ -69,6 +69,7 @@ export default function ManualJournalDrawerTable({
return (
<div className="journal-drawer__content--table">
<DataTable columns={columns} data={entries} />
<If condition={description}>
<p className={'desc'}>
<b>Description</b>: {description}

View File

@@ -1,11 +1,13 @@
import React from 'react';
import 'style/components/Drawers/DrawerTemplate.scss';
import PaperTemplateHeader from './PaperTemplateHeader';
import PaperTemplateTable from './PaperTemplateTable';
import PaperTemplateFooter from './PaperTemplateFooter';
import { updateItemsEntriesTotal } from 'containers/Entries/utils';
import intl from 'react-intl-universal';
import 'style/components/Drawer/DrawerTemplate.scss';
function PaperTemplate({ labels: propLabels, paperData, entries }) {
const labels = {

View File

@@ -1,5 +1,6 @@
import React from 'react';
import { If } from 'components';
import intl from 'react-intl-universal';
export default function PaperTemplateFooter({
footerData: { terms_conditions },
@@ -8,7 +9,7 @@ export default function PaperTemplateFooter({
<div className="template__terms">
<If condition={terms_conditions}>
<div className="template__terms__title">
<h4>Conditions and terms</h4>
<h4>{intl.get('conditions_and_terms')}</h4>
</div>
<ul>

View File

@@ -1,9 +1,11 @@
import React from 'react';
import 'style/components/Drawers/DrawerTemplate.scss';
import PaymentPaperTemplateHeader from './PaymentPaperTemplateHeader';
import PaymentPaperTemplateTable from './PaymentPaperTemplateTable';
import intl from 'react-intl-universal';
import 'style/components/Drawer/DrawerTemplate.scss';
export default function PaymentPaperTemplate({
labels: propLabels,

View File

@@ -30,6 +30,7 @@ function ItemsEntriesTable({
linesNumber,
currencyCode,
itemType, // sellable or purchasable
landedCost = false
}) {
const [rows, setRows] = React.useState(initialEntries);
const [rowItem, setRowItem] = React.useState(null);
@@ -94,7 +95,7 @@ function ItemsEntriesTable({
}, [entries, rows]);
// Editiable items entries columns.
const columns = useEditableItemsEntriesColumns();
const columns = useEditableItemsEntriesColumns({ landedCost });
// Handles the editor data update.
const handleUpdateData = useCallback(

View File

@@ -1,7 +1,7 @@
import React from 'react';
import { FormattedMessage as T } from 'components';
import intl from 'react-intl-universal';
import { Tooltip, Button, Intent, Position } from '@blueprintjs/core';
import { Tooltip, Button, Checkbox, Intent, Position } from '@blueprintjs/core';
import { Hint, Icon } from 'components';
import { formattedAmount, safeSumBy } from 'utils';
import {
@@ -10,6 +10,7 @@ import {
ItemsListCell,
PercentFieldCell,
NumericInputCell,
CheckBoxFieldCell,
} from 'components/DataTableCells';
/**
@@ -28,7 +29,11 @@ export function ItemHeaderCell() {
* Item column footer cell.
*/
export function ItemFooterCell() {
return <span><T id={'total'}/></span>;
return (
<span>
<T id={'total'} />
</span>
);
}
/**
@@ -86,12 +91,26 @@ export function IndexTableCell({ row: { index } }) {
return <span>{index + 1}</span>;
}
/**
* Landed cost header cell.
*/
const LandedCostHeaderCell = () => {
return (
<>
<T id={'Landed'} />
<Hint
content={
'This options allows you to be able to add additional cost eg. freight then allocate cost to the items in your bills.'
}
/>
</>
);
};
/**
* Retrieve editable items entries columns.
*/
export function useEditableItemsEntriesColumns() {
export function useEditableItemsEntriesColumns({ landedCost }) {
return React.useMemo(
() => [
{
@@ -155,6 +174,19 @@ export function useEditableItemsEntriesColumns() {
width: 100,
className: 'total',
},
...(landedCost
? [
{
Header: LandedCostHeaderCell,
accessor: 'landed_cost',
Cell: CheckBoxFieldCell,
width: 100,
disableSortBy: true,
disableResizing: true,
className: 'landed-cost',
},
]
: []),
{
Header: '',
accessor: 'action',

View File

@@ -79,7 +79,10 @@ function ExpenseForm({
}
const categories = values.categories.filter(
(category) =>
category.amount && category.index && category.expense_account_id,
category.amount &&
category.index &&
category.expense_account_id &&
category.landed_cost,
);
const form = {

View File

@@ -8,9 +8,7 @@ const Schema = Yup.object().shape({
payment_account_id: Yup.number()
.required()
.label(intl.get('payment_account_')),
payment_date: Yup.date()
.required()
.label(intl.get('payment_date_')),
payment_date: Yup.date().required().label(intl.get('payment_date_')),
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING).nullable(),
currency_code: Yup.string()
.nullable()
@@ -33,6 +31,7 @@ const Schema = Yup.object().shape({
is: (amount) => !isBlank(amount),
then: Yup.number().required(),
}),
landed_cost: Yup.boolean(),
description: Yup.string().max(DATATYPES_LENGTH.TEXT).nullable(),
}),
),

View File

@@ -1,14 +1,22 @@
import { FastField } from 'formik';
import React from 'react';
import ExpenseFormEntriesTable from './ExpenseFormEntriesTable';
import { defaultExpenseEntry } from './utils';
import { useExpenseFormContext } from './ExpenseFormPageProvider';
import { defaultExpenseEntry, accountsFieldShouldUpdate } from './utils';
/**
* Expense form entries field.
*/
export default function ExpenseFormEntriesField({ linesNumber = 4 }) {
// Expense form context.
const { accounts } = useExpenseFormContext();
return (
<FastField name={'categories'}>
<FastField
name={'categories'}
accounts={accounts}
shouldUpdate={accountsFieldShouldUpdate}
>
{({
form: { values, setFieldValue },
field: { value },

View File

@@ -22,12 +22,13 @@ export default function ExpenseFormEntriesTable({
error,
onChange,
currencyCode,
landedCost = true,
}) {
// Expense form context.
const { accounts } = useExpenseFormContext();
// Memorized data table columns.
const columns = useExpenseFormTableColumns();
const columns = useExpenseFormTableColumns({ landedCost });
// Handles update datatable data.
const handleUpdateData = useCallback(
@@ -61,6 +62,7 @@ export default function ExpenseFormEntriesTable({
return (
<DataTableEditable
name={'expense-form'}
columns={columns}
data={entries}
sticky={true}

View File

@@ -11,6 +11,7 @@ import {
inputIntent,
handleDateChange,
} from 'utils';
import { customersFieldShouldUpdate, accountsFieldShouldUpdate } from './utils';
import {
CurrencySelectList,
ContactSelecetList,
@@ -51,7 +52,11 @@ export default function ExpenseFormHeader() {
)}
</FastField>
<FastField name={'payment_account_id'}>
<FastField
name={'payment_account_id'}
accounts={accounts}
shouldUpdate={accountsFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'payment_account'} />}
@@ -118,7 +123,11 @@ export default function ExpenseFormHeader() {
)}
</FastField>
<FastField name={'customer_id'}>
<FastField
name={'customer_id'}
customers={customers}
shouldUpdate={customersFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'customer'} />}

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { Button, Tooltip, Intent, Position } from '@blueprintjs/core';
import { Button, Tooltip, Intent, Position, Checkbox } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { Icon, Hint } from 'components';
import intl from 'react-intl-universal';
@@ -7,6 +7,7 @@ import {
InputGroupCell,
MoneyFieldCell,
AccountsListFieldCell,
CheckBoxFieldCell,
} from 'components/DataTableCells';
import { formattedAmount, safeSumBy } from 'utils';
@@ -49,6 +50,22 @@ const ActionsCellRenderer = ({
);
};
/**
* Landed cost header cell.
*/
const LandedCostHeaderCell = () => {
return (
<>
<T id={'Landed'} />
<Hint
content={
'This options allows you to be able to add additional cost eg. freight then allocate cost to the items in your bills.'
}
/>
</>
);
};
/**
* Amount footer cell.
*/
@@ -74,7 +91,7 @@ function ExpenseAccountFooterCell() {
/**
* Retrieve expense form table entries columns.
*/
export function useExpenseFormTableColumns() {
export function useExpenseFormTableColumns({ landedCost }) {
return React.useMemo(
() => [
{
@@ -114,6 +131,19 @@ export function useExpenseFormTableColumns() {
className: 'description',
width: 100,
},
...(landedCost
? [
{
Header: LandedCostHeaderCell,
accessor: 'landed_cost',
Cell: CheckBoxFieldCell,
disableSortBy: true,
disableResizing: true,
width: 100,
className: 'landed-cost',
},
]
: []),
{
Header: '',
accessor: 'action',

View File

@@ -1,7 +1,11 @@
import { AppToaster } from 'components';
import moment from 'moment';
import intl from 'react-intl-universal';
import { transformToForm, repeatValue } from 'utils';
import {
defaultFastFieldShouldUpdate,
transformToForm,
repeatValue,
} from 'utils';
const ERROR = {
EXPENSE_ALREADY_PUBLISHED: 'EXPENSE.ALREADY.PUBLISHED',
@@ -27,6 +31,7 @@ export const defaultExpenseEntry = {
amount: '',
expense_account_id: '',
description: '',
landed_cost: false,
};
export const defaultExpense = {
@@ -61,3 +66,23 @@ export const transformToEditForm = (
],
};
};
/**
* Detarmine cusotmers fast-field should update.
*/
export const customersFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.customers !== oldProps.customers ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Detarmine accounts fast-field should update.
*/
export const accountsFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.accounts !== oldProps.accounts ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};

View File

@@ -30,6 +30,7 @@ function APAgingSummary({
asDate: moment().endOf('day').format('YYYY-MM-DD'),
agingBeforeDays: 30,
agingPeriods: 3,
vendorsIds: [],
});
// Handle filter submit.
@@ -63,7 +64,7 @@ function APAgingSummary({
<APAgingSummarySheetLoadingBar />
<DashboardPageContent>
<FinancialStatement>
<FinancialStatement name={'AP-aging-summary'}>
<APAgingSummaryHeader
pageFilter={filter}
onSubmitFilter={handleFilterSubmit}

View File

@@ -12,6 +12,7 @@ import withAPAgingSummary from './withAPAgingSummary';
import withAPAgingSummaryActions from './withAPAgingSummaryActions';
import { compose } from 'utils';
import { transformToForm } from '../../../utils';
/**
* AP Aging Summary Report - Drawer Header.
@@ -25,16 +26,17 @@ function APAgingSummaryHeader({
toggleAPAgingSummaryFilterDrawer: toggleFilterDrawerDisplay,
// #withAPAgingSummary
isFilterDrawerOpen
isFilterDrawerOpen,
}) {
// Validation schema.
const validationSchema = Yup.object({
as_date: Yup.date().required().label('asDate'),
aging_days_before: Yup.number()
asDate: Yup.date().required().label('asDate'),
agingDaysBefore: Yup.number()
.required()
.integer()
.positive()
.label('agingBeforeDays'),
aging_periods: Yup.number()
agingPeriods: Yup.number()
.required()
.integer()
.positive()
@@ -42,11 +44,14 @@ function APAgingSummaryHeader({
});
// Initial values.
const initialValues = {
as_date: moment(pageFilter.asDate).toDate(),
aging_days_before: 30,
aging_periods: 3,
const defaultValues = {
asDate: moment(pageFilter.asDate).toDate(),
agingDaysBefore: 30,
agingPeriods: 3,
vendorsIds: [],
};
// Formik initial values.
const initialValues = transformToForm(pageFilter, defaultValues);
// Handle form submit.
const handleSubmit = (values, { setSubmitting }) => {
@@ -55,18 +60,17 @@ function APAgingSummaryHeader({
setSubmitting(false);
};
// handle cancel button click.
const handleCancelClick = () => {
toggleFilterDrawerDisplay(false);
};
// Handle cancel button click.
const handleCancelClick = () => { toggleFilterDrawerDisplay(false); };
// Handle the drawer closing.
const handleDrawerClose = () => {
toggleFilterDrawerDisplay(false);
};
const handleDrawerClose = () => { toggleFilterDrawerDisplay(false); };
return (
<FinancialStatementHeader isOpen={isFilterDrawerOpen} drawerProps={{ onClose: handleDrawerClose }}>
<FinancialStatementHeader
isOpen={isFilterDrawerOpen}
drawerProps={{ onClose: handleDrawerClose }}
>
<Formik
initialValues={initialValues}
validationSchema={validationSchema}

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { FastField } from 'formik';
import { FastField, Field } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import {
Intent,
@@ -51,9 +51,10 @@ export default function APAgingSummaryHeaderGeneral() {
</FastField>
</Col>
</Row>
<Row>
<Col xs={5}>
<FastField name={'aging_days_before'}>
<FastField name={'agingDaysBefore'}>
{({ field, meta: { error } }) => (
<FormGroup
label={<T id={'aging_before_days'} />}
@@ -66,9 +67,10 @@ export default function APAgingSummaryHeaderGeneral() {
</FastField>
</Col>
</Row>
<Row>
<Col xs={5}>
<FastField name={'aging_periods'}>
<FastField name={'agingPeriods'}>
{({ field, meta: { error } }) => (
<FormGroup
label={<T id={'aging_periods'} />}
@@ -81,17 +83,29 @@ export default function APAgingSummaryHeaderGeneral() {
</FastField>
</Col>
</Row>
<Row>
<Col xs={5}>
<FormGroup
label={<T id={'specific_vendors'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
defaultText={<T id={'all_vendors'} />}
contacts={vendors}
/>
</FormGroup>
<Field name={'vendorsIds'}>
{({
form: { setFieldValue },
field: { value },
}) => (
<FormGroup
label={<T id={'specific_vendors'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
defaultText={<T id={'all_vendors'} />}
contacts={vendors}
contactsSelected={value}
onContactSelect={(contactsIds) => {
setFieldValue('vendorsIds', contactsIds);
}}
/>
</FormGroup>
)}
</Field>
</Col>
</Row>
</div>

View File

@@ -18,7 +18,7 @@ import withSettings from 'containers/Settings/withSettings';
import { compose } from 'utils';
/**
* AR aging summary report.
* A/R aging summary report.
*/
function ReceivableAgingSummarySheet({
// #withSettings
@@ -31,6 +31,7 @@ function ReceivableAgingSummarySheet({
asDate: moment().endOf('day').format('YYYY-MM-DD'),
agingDaysBefore: 30,
agingPeriods: 3,
customersIds: [],
});
// Handle filter submit.
@@ -61,7 +62,7 @@ function ReceivableAgingSummarySheet({
<ARAgingSummarySheetLoadingBar />
<DashboardPageContent>
<FinancialStatement>
<FinancialStatement name={'AR-aging-summary'}>
<ARAgingSummaryHeader
pageFilter={filter}
onSubmitFilter={handleFilterSubmit}

View File

@@ -11,7 +11,7 @@ import ARAgingSummaryHeaderGeneral from './ARAgingSummaryHeaderGeneral';
import withARAgingSummary from './withARAgingSummary';
import withARAgingSummaryActions from './withARAgingSummaryActions';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
/**
* AR Aging Summary Report - Drawer Header.
@@ -41,11 +41,20 @@ function ARAgingSummaryHeader({
.label('agingPeriods'),
});
// Initial values.
const initialValues = {
asDate: moment(pageFilter.asDate).toDate(),
const defaultValues = {
asDate: moment().toDate(),
agingDaysBefore: 30,
agingPeriods: 3,
customersIds: [],
};
// Initial values.
const initialValues = transformToForm(
{
...pageFilter,
asDate: moment(pageFilter.asDate).toDate(),
},
defaultValues,
);
// Handle form submit.
const handleSubmit = (values, { setSubmitting }) => {
@@ -58,7 +67,7 @@ function ARAgingSummaryHeader({
const handleCancelClick = () => {
toggleFilterDrawerDisplay(false);
};
// Handle the drawer close.
const handleDrawerClose = () => {
toggleFilterDrawerDisplay(false);

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { FastField } from 'formik';
import { FastField, Field } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import {
Intent,
@@ -93,14 +93,24 @@ export default function ARAgingSummaryHeaderGeneral() {
</Row>
<Row>
<Col xs={5}>
<FormGroup
label={<T id={'specific_customers'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect contacts={customers} />
</FormGroup>
<Field name="customersIds">
{({ form: { setFieldValue }, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'specific_customers'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
contacts={customers}
contactsSelected={value}
onContactSelect={(contactsIds) => {
setFieldValue('customersIds', contactsIds);
}}
/>
</FormGroup>
)}
</Field>
</Col>
</Row>
</div>
);
}
}

View File

@@ -11,7 +11,7 @@ import FinancialStatementHeader from 'containers/FinancialStatements/FinancialSt
import withBalanceSheet from './withBalanceSheet';
import withBalanceSheetActions from './withBalanceSheetActions';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
import BalanceSheetHeaderGeneralPanal from './BalanceSheetHeaderGeneralPanal';
/**
@@ -28,20 +28,25 @@ function BalanceSheetHeader({
// #withBalanceSheetActions
toggleBalanceSheetFilterDrawer: toggleFilterDrawer,
}) {
// Filter form initial values.
const initialValues = {
basis: 'cash',
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
const defaultValues = {
basic: 'cash',
fromDate: moment().toDate(),
toDate: moment().toDate(),
};
// Filter form initial values.
const initialValues = transformToForm(
{
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
},
defaultValues,
);
// Validation schema.
const validationSchema = Yup.object().shape({
dateRange: Yup.string().optional(),
fromDate: Yup.date()
.required()
.label(intl.get('fromDate')),
fromDate: Yup.date().required().label(intl.get('fromDate')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
@@ -58,14 +63,10 @@ function BalanceSheetHeader({
};
// Handle cancel button click.
const handleCancelClick = () => {
toggleFilterDrawer(false);
};
const handleCancelClick = () => { toggleFilterDrawer(false); };
// Handle drawer close action.
const handleDrawerClose = () => {
toggleFilterDrawer(false);
};
const handleDrawerClose = () => { toggleFilterDrawer(false); };
return (
<FinancialStatementHeader

View File

@@ -12,7 +12,7 @@ import CashFlowStatementGeneralPanel from './CashFlowStatementGeneralPanel';
import withCashFlowStatement from './withCashFlowStatement';
import withCashFlowStatementActions from './withCashFlowStatementActions';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
/**
* Cash flow statement header.
@@ -22,18 +22,24 @@ function CashFlowStatementHeader({
onSubmitFilter,
pageFilter,
//#withCashFlowStatement
// #withCashFlowStatement
isFilterDrawerOpen,
//#withCashStatementActions
// #withCashStatementActions
toggleCashFlowStatementFilterDrawer,
}) {
// filter form initial values.
const initialValues = {
// Filter form default values.
const defaultValues = {
fromDate: moment().toDate(),
toDate: moment().toDate(),
};
// Initial form values.
const initialValues = transformToForm({
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
};
}, defaultValues);
// Validation schema.
const validationSchema = Yup.object().shape({

View File

@@ -1,14 +1,9 @@
import React from 'react';
import { FastField } from 'formik';
import { FastField, Field } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import {
FormGroup,
Position,
Classes,
Checkbox,
} from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { Classes, FormGroup, Position, Checkbox } from '@blueprintjs/core';
import { ContactsMultiSelect, FormattedMessage as T } from 'components';
import classNames from 'classnames';
import { Row, Col, FieldHint } from 'components';
import {
momentFormatter,
@@ -16,11 +11,14 @@ import {
inputIntent,
handleDateChange,
} from 'utils';
import { useCustomersBalanceSummaryContext } from './CustomersBalanceSummaryProvider';
/**
* Customers balance header - general panel.
*/
export default function CustomersBalanceSummaryGeneralPanel() {
const { customers } = useCustomersBalanceSummaryContext();
return (
<div>
<Row>
@@ -48,6 +46,7 @@ export default function CustomersBalanceSummaryGeneralPanel() {
</FastField>
</Col>
</Row>
<Row>
<Col xs={5}>
<FastField name={'percentage'} type={'checkbox'}>
@@ -57,7 +56,7 @@ export default function CustomersBalanceSummaryGeneralPanel() {
inline={true}
name={'percentage'}
small={true}
label={<T id={'percentage_of_column'}/>}
label={<T id={'percentage_of_column'} />}
{...field}
/>
</FormGroup>
@@ -65,6 +64,31 @@ export default function CustomersBalanceSummaryGeneralPanel() {
</FastField>
</Col>
</Row>
<Row>
<Col xs={5}>
<Field name={'customersIds'}>
{({
form: { setFieldValue },
field: { value },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'Specific customers'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
onContactSelect={(contactsIds) => {
setFieldValue('customersIds', contactsIds);
}}
contacts={customers}
contactsSelected={value}
/>
</FormGroup>
)}
</Field>
</Col>
</Row>
</div>
);
}

View File

@@ -4,14 +4,13 @@ import { Formik, Form } from 'formik';
import moment from 'moment';
import { Tabs, Tab, Button, Intent } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import intl from 'react-intl-universal';
import FinancialStatementHeader from 'containers/FinancialStatements/FinancialStatementHeader';
import withCustomersBalanceSummary from './withCustomersBalanceSummary';
import withCustomersBalanceSummaryActions from './withCustomersBalanceSummaryActions';
import CustomersBalanceSummaryGeneralPanel from './CustomersBalanceSummaryGeneralPanel';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
/**
* Customers balance summary.
@@ -33,11 +32,17 @@ function CustomersBalanceSummaryHeader({
asDate: Yup.date().required().label('asDate'),
});
// filter form initial values.
const initialValues = {
// Default form values.
const defaultValues = {
asDate: moment().toDate(),
customersIds: [],
};
// Filter form initial values.
const initialValues = transformToForm({
...pageFilter,
asDate: moment(pageFilter.asDate).toDate(),
};
}, defaultValues);
// handle form submit.
const handleSubmit = (values, { setSubmitting }) => {

View File

@@ -1,6 +1,6 @@
import React, { createContext, useContext } from 'react';
import FinancialReportPage from '../FinancialReportPage';
import { useCustomerBalanceSummaryReport } from 'hooks/query';
import { useCustomerBalanceSummaryReport, useCustomers } from 'hooks/query';
import { transformFilterFormToQuery } from '../common';
const CustomersBalanceSummaryContext = createContext();
@@ -14,6 +14,7 @@ function CustomersBalanceSummaryProvider({ filter, ...props }) {
filter,
]);
// Fetches customers balance summary report based on the given report.
const {
data: CustomerBalanceSummary,
isLoading: isCustomersBalanceLoading,
@@ -23,10 +24,22 @@ function CustomersBalanceSummaryProvider({ filter, ...props }) {
keepPreviousData: true,
});
// Fetches the customers list.
const {
data: { customers },
isFetching: isCustomersFetching,
isLoading: isCustomersLoading,
} = useCustomers();
const provider = {
CustomerBalanceSummary,
isCustomersBalanceFetching,
isCustomersBalanceLoading,
isCustomersLoading,
isCustomersFetching,
customers,
refetch,
};
return (

View File

@@ -12,7 +12,7 @@ import CustomersTransactionsHeaderGeneralPanel from './CustomersTransactionsHead
import withCustomersTransactions from './withCustomersTransactions';
import withCustomersTransactionsActions from './withCustomersTransactionsActions';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
/**
* Customers transactions header.
@@ -28,14 +28,18 @@ function CustomersTransactionsHeader({
//#withCustomersTransactionsActions
toggleCustomersTransactionsFilterDrawer: toggleFilterDrawer,
}) {
// Filter form initial values.
const initialValues = {
// Default form values.
const defaultValues = {
fromDate: moment().toDate(),
toDate: moment().toDate(),
customersIds: [],
};
// Initial form values.
const initialValues = transformToForm({
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
};
}, defaultValues);
// Validation schema.
const validationSchema = Yup.object().shape({
@@ -54,11 +58,8 @@ function CustomersTransactionsHeader({
toggleFilterDrawer(false);
setSubmitting(false);
};
// Handle drawer close action.
const handleDrawerClose = () => {
toggleFilterDrawer(false);
};
const handleDrawerClose = () => { toggleFilterDrawer(false); };
return (
<FinancialStatementHeader

View File

@@ -1,13 +1,45 @@
import React from 'react';
import classNames from 'classnames';
import { Field } from 'formik';
import { Classes, FormGroup } from '@blueprintjs/core';
import FinancialStatementDateRange from 'containers/FinancialStatements/FinancialStatementDateRange';
import { Row, Col } from 'components';
import { ContactsMultiSelect, FormattedMessage as T } from 'components';
import { useCustomersTransactionsContext } from './CustomersTransactionsProvider';
/**
* Customers transactions header - General panel.
*/
export default function CustomersTransactionsHeaderGeneralPanel() {
const { customers } = useCustomersTransactionsContext();
return (
<div>
<FinancialStatementDateRange />
<Row>
<Col xs={5}>
<Field name={'customersIds'}>
{({
form: { setFieldValue },
field: { value },
}) => (
<FormGroup
label={<T id={'specific_customers'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
onContactSelect={(contactsIds) => {
setFieldValue('customersIds', contactsIds);
}}
contacts={customers}
contactsSelected={value}
/>
</FormGroup>
)}
</Field>
</Col>
</Row>
</div>
);
}

View File

@@ -1,6 +1,6 @@
import React, { createContext, useContext, useMemo } from 'react';
import FinancialReportPage from '../FinancialReportPage';
import { useCustomersTransactionsReport } from 'hooks/query';
import { useCustomersTransactionsReport, useCustomers } from 'hooks/query';
import { transformFilterFormToQuery } from '../common';
const CustomersTransactionsContext = createContext();
@@ -21,11 +21,23 @@ function CustomersTransactionsProvider({ filter, ...props }) {
refetch: CustomersTransactionsRefetch,
} = useCustomersTransactionsReport(query, { keepPreviousData: true });
// Fetches the customers list.
const {
data: { customers },
isFetching: isCustomersFetching,
isLoading: isCustomersLoading,
} = useCustomers();
const provider = {
customersTransactions,
isCustomersTransactionsFetching,
isCustomersTransactionsLoading,
CustomersTransactionsRefetch,
customers,
isCustomersLoading,
isCustomersFetching,
filter,
query
};

View File

@@ -11,7 +11,7 @@ import GeneralLedgerHeaderGeneralPane from './GeneralLedgerHeaderGeneralPane';
import withGeneralLedger from './withGeneralLedger';
import withGeneralLedgerActions from './withGeneralLedgerActions';
import { compose, saveInvoke } from 'utils';
import { compose, transformToForm, saveInvoke } from 'utils';
/**
* Geenral Ledger (GL) - Header.
@@ -27,13 +27,22 @@ function GeneralLedgerHeader({
// #withGeneralLedger
isFilterDrawerOpen,
}) {
// Initial values.
const initialValues = {
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
// Default values.
const defaultValues = {
fromDate: moment().toDate(),
toDate: moment().toDate(),
};
// Initial values.
const initialValues = transformToForm(
{
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
},
defaultValues,
);
// Validation schema.
const validationSchema = Yup.object().shape({
dateRange: Yup.string().optional(),

View File

@@ -33,7 +33,7 @@ function InventoryItemDetails({
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
});
// Handle filter submit.
const handleFilterSubmit = (filter) => {
const _filter = {
...filter,
@@ -61,10 +61,14 @@ function InventoryItemDetails({
/>
<InventoryItemDetailsLoadingBar />
<InventoryItemDetailsAlerts />
<DashboardPageContent>
<FinancialStatement>
<div className={'financial-statement--inventory-details'}>
<div
className={
'financial-statement financial-statement--inventory-details'
}
>
<InventoryItemDetailsHeader
pageFilter={filter}
onSubmitFilter={handleFilterSubmit}

View File

@@ -12,7 +12,7 @@ import InventoryItemDetailsHeaderGeneralPanel from './InventoryItemDetailsHeader
import withInventoryItemDetails from './withInventoryItemDetails';
import withInventoryItemDetailsActions from './withInventoryItemDetailsActions';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
/**
* Inventory item details header.
@@ -21,20 +21,25 @@ function InventoryItemDetailsHeader({
// #ownProps
onSubmitFilter,
pageFilter,
//#withInventoryItemDetails
// #withInventoryItemDetails
isFilterDrawerOpen,
//#withInventoryItemDetailsActions
// #withInventoryItemDetailsActions
toggleInventoryItemDetailsFilterDrawer: toggleFilterDrawer,
}) {
// Default form values.
const defaultValues = {
fromDate: moment().toDate(),
toDate: moment().toDate(),
itemsIds: [],
};
//Filter form initial values.
const initialValues = {
// Filter form initial values.
const initialValues = transformToForm({
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
};
}, defaultValues);
// Validation schema.
const validationSchema = Yup.object().shape({
@@ -56,9 +61,7 @@ function InventoryItemDetailsHeader({
};
// Handle drawer close action.
const handleDrawerClose = () => {
toggleFilterDrawer(false);
};
const handleDrawerClose = () => { toggleFilterDrawer(false); };
return (
<FinancialStatementHeader

View File

@@ -1,13 +1,46 @@
import React from 'react';
import classNames from 'classnames';
import { FormGroup, Classes } from '@blueprintjs/core';
import { Field } from 'formik';
import { Row, Col, FormattedMessage as T } from 'components';
import { ItemsMultiSelect } from 'components';
import FinancialStatementDateRange from 'containers/FinancialStatements/FinancialStatementDateRange';
import { useInventoryItemDetailsContext } from './InventoryItemDetailsProvider';
/**
* Inventory item details header - General panel.
*/
export default function InventoryItemDetailsHeaderGeneralPanel() {
const { items } = useInventoryItemDetailsContext();
return (
<div>
<FinancialStatementDateRange />
<Row>
<Col xs={4}>
<Field name={'itemsIds'}>
{({
form: { setFieldValue },
field: { value },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'Specific items'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ItemsMultiSelect
items={items}
selectedItems={value}
onItemSelect={(itemsIds) => {
setFieldValue('itemsIds', itemsIds);
}}
/>
</FormGroup>
)}
</Field>
</Col>
</Row>
</div>
);
}

View File

@@ -1,6 +1,6 @@
import React from 'react';
import FinancialReportPage from '../FinancialReportPage';
import { useInventoryItemDetailsReport } from 'hooks/query';
import { useItems, useInventoryItemDetailsReport } from 'hooks/query';
import { transformFilterFormToQuery } from '../common';
const InventoryItemDetailsContext = React.createContext();
@@ -14,7 +14,7 @@ function InventoryItemDetailsProvider({ filter, ...props }) {
[filter],
);
// fetch inventory item details.
// Fetching inventory item details report based on the givne query.
const {
data: inventoryItemDetails,
isFetching: isInventoryItemDetailsFetching,
@@ -22,11 +22,23 @@ function InventoryItemDetailsProvider({ filter, ...props }) {
refetch: inventoryItemDetailsRefetch,
} = useInventoryItemDetailsReport(query, { keepPreviousData: true });
// Handle fetching the items based on the given query.
const {
data: { items },
isLoading: isItemsLoading,
isFetching: isItemsFetching,
} = useItems({ page_size: 10000 });
const provider = {
inventoryItemDetails,
isInventoryItemDetailsFetching,
isInventoryItemDetailsLoading,
inventoryItemDetailsRefetch,
isItemsFetching,
isItemsLoading,
items,
query,
filter,
};

View File

@@ -64,7 +64,7 @@ function InventoryValuation({
<InventoryValuationLoadingBar />
<DashboardPageContent>
<div class="financial-statement">
<div class="financial-statement financial-statement--inventory-valuation">
<InventoryValuationHeader
pageFilter={filter}
onSubmitFilter={handleFilterSubmit}

View File

@@ -2,7 +2,6 @@ import React from 'react';
import * as Yup from 'yup';
import moment from 'moment';
import { FormattedMessage as T } from 'components';
import intl from 'react-intl-universal';
import { Formik, Form } from 'formik';
import { Tabs, Tab, Button, Intent } from '@blueprintjs/core';
@@ -11,7 +10,7 @@ import InventoryValuationHeaderGeneralPanel from './InventoryValuationHeaderGene
import withInventoryValuation from './withInventoryValuation';
import withInventoryValuationActions from './withInventoryValuationActions';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
/**
* inventory valuation header.
@@ -27,18 +26,23 @@ function InventoryValuationHeader({
// #withInventoryValuationActions
toggleInventoryValuationFilterDrawer,
}) {
// Form validation schema.
const validationSchema = Yup.object().shape({
as_date: Yup.date().required().label('asDate'),
asDate: Yup.date().required().label('asDate'),
});
// Initial values.
const initialValues = {
as_date: moment(pageFilter.asDate).toDate(),
// Default values.
const defaultValues = {
asDate: moment().toDate(),
itemsIds: [],
};
// Initial values.
const initialValues = transformToForm({
...pageFilter,
asDate: moment(pageFilter.asDate).toDate(),
}, defaultValues);
// Handle the form of header submit.
const handleSubmit = (values, { setSubmitting }) => {
onSubmitFilter(values);
toggleInventoryValuationFilterDrawer(false);

View File

@@ -1,20 +1,24 @@
import React from 'react';
import { FastField } from 'formik';
import { FastField, Field } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import { FormGroup, Position } from '@blueprintjs/core';
import { FormGroup, Position, Classes } from '@blueprintjs/core';
import classNames from 'classnames';
import { FormattedMessage as T } from 'components';
import { Row, Col, FieldHint } from 'components';
import { ItemsMultiSelect, Row, Col, FieldHint } from 'components';
import {
momentFormatter,
tansformDateValue,
inputIntent,
handleDateChange,
} from 'utils';
import { useInventoryValuationContext } from './InventoryValuationProvider';
/**
* inventory valuation - Drawer Header - General panel.
* Inventory valuation - Drawer Header - General panel.
*/
export default function InventoryValuationHeaderGeneralPanel() {
const { items } = useInventoryValuationContext();
return (
<div>
<Row>
@@ -42,6 +46,31 @@ export default function InventoryValuationHeaderGeneralPanel() {
</FastField>
</Col>
</Row>
<Row>
<Col xs={5}>
<Field name={'itemsIds'}>
{({
form: { setFieldValue },
field: { value },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'Specific items'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ItemsMultiSelect
items={items}
selectedItems={value}
onItemSelect={(itemsIds) => {
setFieldValue('itemsIds', itemsIds);
}}
/>
</FormGroup>
)}
</Field>
</Col>
</Row>
</div>
);
}

View File

@@ -1,6 +1,6 @@
import React from 'react';
import FinancialReportPage from '../FinancialReportPage';
import { useInventoryValuation } from 'hooks/query';
import { useInventoryValuation, useItems } from 'hooks/query';
import { transformFilterFormToQuery } from '../common';
const InventoryValuationContext = React.createContext();
@@ -20,11 +20,23 @@ function InventoryValuationProvider({ query, ...props }) {
},
);
// Handle fetching the items based on the given query.
const {
data: { items },
isLoading: isItemsLoading,
isFetching: isItemsFetching,
} = useItems({ page_size: 10000 });
// Provider data.
const provider = {
inventoryValuation,
isLoading,
isFetching,
refetchSheet: refetch,
items,
isItemsFetching,
isItemsLoading
};
return (

View File

@@ -66,7 +66,7 @@ function PurchasesByItems({
/>
<PurchasesByItemsLoadingBar />
<DashboardPageContent>
<div className="financial-statement">
<div className="financial-statement financial-statement--purchases-by-items">
<PurchasesByItemsHeader
pageFilter={filter}
onSubmitFilter={handleFilterSubmit}

View File

@@ -1,13 +1,47 @@
import React from 'react';
import { FormGroup, Classes } from '@blueprintjs/core';
import { Field } from 'formik';
import { Row, Col, FormattedMessage as T } from 'components';
import classNames from 'classnames';
import FinancialStatementDateRange from 'containers/FinancialStatements/FinancialStatementDateRange';
import { ItemsMultiSelect } from 'components';
import { usePurchaseByItemsContext } from './PurchasesByItemsProvider';
/**
* Purchases by items - Drawer header - General panel.
*/
export default function PurchasesByItemsGeneralPanel() {
const { items } = usePurchaseByItemsContext();
return (
<div>
<FinancialStatementDateRange />
<Row>
<Col xs={4}>
<Field name={'itemsIds'}>
{({
form: { setFieldValue },
field: { value },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'Specific items'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ItemsMultiSelect
items={items}
selectedItems={value}
onItemSelect={(itemsIds) => {
setFieldValue('itemsIds', itemsIds);
}}
/>
</FormGroup>
)}
</Field>
</Col>
</Row>
</div>
);
}

View File

@@ -12,7 +12,7 @@ import PurchasesByItemsGeneralPanel from './PurchasesByItemsGeneralPanel';
import withPurchasesByItems from './withPurchasesByItems';
import withPurchasesByItemsActions from './withPurchasesByItemsActions';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
/**
* Purchases by items header.
@@ -28,25 +28,31 @@ function PurchasesByItemsHeader({
// #withPurchasesByItems
togglePurchasesByItemsFilterDrawer,
}) {
// Form validation schema.
const validationSchema = Yup.object().shape({
fromDate: Yup.date()
.required()
.label(intl.get('from_date')),
fromDate: Yup.date().required().label(intl.get('from_date')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('to_date')),
});
// Initial values.
const initialValues = {
// Default form values.
const defaultValues = {
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
fromDate: moment().toDate(),
toDate: moment().toDate(),
itemsIds: [],
};
// Initial form values.
const initialValues = transformToForm(
{
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
},
defaultValues,
);
// Handle form submit.
const handleSubmit = (values, { setSubmitting }) => {

View File

@@ -1,12 +1,13 @@
import React, { createContext, useContext } from 'react';
import FinancialReportPage from '../FinancialReportPage';
import { usePurchasesByItems } from 'hooks/query';
import { usePurchasesByItems, useItems } from 'hooks/query';
import { transformFilterFormToQuery } from '../common';
const PurchasesByItemsContext = createContext();
function PurchasesByItemsProvider({ query, ...props }) {
// Handle fetching the purchases by items report based on the given query.
const {
data: purchaseByItems,
isFetching,
@@ -21,11 +22,23 @@ function PurchasesByItemsProvider({ query, ...props }) {
},
);
// Handle fetching the items based on the given query.
const {
data: { items },
isLoading: isItemsLoading,
isFetching: isItemsFetching,
} = useItems({ page_size: 10000 });
const provider = {
purchaseByItems,
isFetching,
isLoading,
refetchSheet: refetch,
items,
isItemsLoading,
isItemsFetching,
refetchSheet: refetch,
};
return (
<FinancialReportPage name={'purchase-by-items'}>

View File

@@ -1,6 +1,6 @@
import React, { createContext, useContext } from 'react';
import FinancialReportPage from '../FinancialReportPage';
import { useSalesByItems } from 'hooks/query';
import { useSalesByItems, useItems } from 'hooks/query';
import { transformFilterFormToQuery } from '../common';
const SalesByItemsContext = createContext();
@@ -20,10 +20,22 @@ function SalesByItemProvider({ query, ...props }) {
},
);
// Handle fetching the items based on the given query.
const {
data: { items },
isLoading: isItemsLoading,
isFetching: isItemsFetching,
} = useItems({ page_size: 10000 });
const provider = {
salesByItems,
isFetching,
isLoading,
items,
isItemsLoading,
isItemsFetching,
refetchSheet: refetch,
};
return (

View File

@@ -68,7 +68,7 @@ function SalesByItems({
/>
<SalesByItemsLoadingBar />
<DashboardPageContent>
<div class="financial-statement">
<div class="financial-statement financial-statement--sales-by-items">
<SalesByItemsHeader
pageFilter={filter}
onSubmitFilter={handleFilterSubmit}

View File

@@ -1,13 +1,45 @@
import React from 'react';
import { FormGroup, Classes } from '@blueprintjs/core';
import { Field } from 'formik';
import classNames from 'classnames';
import { Row, Col, ItemsMultiSelect, FormattedMessage as T } from 'components';
import FinancialStatementDateRange from 'containers/FinancialStatements/FinancialStatementDateRange';
import { useSalesByItemsContext } from './SalesByItemProvider';
/**
* sells by items - Drawer header - General panel.
*/
export default function SalesByItemsHeaderGeneralPanel() {
const { items } = useSalesByItemsContext();
return (
<div>
<FinancialStatementDateRange />
<Row>
<Col xs={4}>
<Field name={'itemsIds'}>
{({
form: { setFieldValue },
field: { value },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'Specific items'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ItemsMultiSelect
items={items}
selectedItems={value}
onItemSelect={(itemsIds) => {
setFieldValue('itemsIds', itemsIds);
}}
/>
</FormGroup>
)}
</Field>
</Col>
</Row>
</div>
);
}

View File

@@ -12,7 +12,7 @@ import TrialBalanceSheetHeaderGeneralPanel from './TrialBalanceSheetHeaderGenera
import withTrialBalance from './withTrialBalance';
import withTrialBalanceActions from './withTrialBalanceActions';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
/**
* Trial balance sheet header.
@@ -28,42 +28,41 @@ function TrialBalanceSheetHeader({
// #withTrialBalanceActions
toggleTrialBalanceFilterDrawer: toggleFilterDrawer,
}) {
// Form validation schema.
const validationSchema = Yup.object().shape({
fromDate: Yup.date()
.required()
.label(intl.get('from_date')),
fromDate: Yup.date().required().label(intl.get('from_date')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('to_date')),
});
// Initial values.
const initialValues = {
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
// Default values.
const defaultValues = {
fromDate: moment().toDate(),
toDate: moment().toDate(),
};
// Initial values.
const initialValues = transformToForm(
{
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
},
defaultValues,
);
// Handle form submit.
const handleSubmit = (values, { setSubmitting }) => {
onSubmitFilter(values);
setSubmitting(false);
toggleFilterDrawer(false);
};
// Handle drawer close action.
const handleDrawerClose = () => {
toggleFilterDrawer(false);
};
const handleDrawerClose = () => { toggleFilterDrawer(false); };
// Handle cancel button click.
const handleCancelClick = () => {
toggleFilterDrawer(false);
};
const handleCancelClick = () => { toggleFilterDrawer(false); };
return (
<FinancialStatementHeader

View File

@@ -10,7 +10,7 @@ import withVendorsBalanceSummary from './withVendorsBalanceSummary';
import withVendorsBalanceSummaryActions from './withVendorsBalanceSummaryActions';
import VendorsBalanceSummaryHeaderGeneral from './VendorsBalanceSummaryHeaderGeneral';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
/**
* Vendors balance summary drawer header.
@@ -32,10 +32,15 @@ function VendorsBalanceSummaryHeader({
});
// filter form initial values.
const initialValues = {
const defaultValues = {
asDate: moment().toDate(),
vendorsIds: [],
};
// Initial form values.
const initialValues = transformToForm({
...pageFilter,
asDate: moment(pageFilter.asDate).toDate(),
};
}, defaultValues);
// handle form submit.
const handleSubmit = (values, { setSubmitting }) => {

View File

@@ -1,8 +1,9 @@
import React from 'react';
import { FastField } from 'formik';
import { Field, FastField } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import classNames from 'classnames';
import { FormGroup, Position, Classes, Checkbox } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { ContactsMultiSelect, FormattedMessage as T } from 'components';
import { Row, Col, FieldHint } from 'components';
import {
momentFormatter,
@@ -10,11 +11,14 @@ import {
inputIntent,
handleDateChange,
} from 'utils';
import { useVendorsBalanceSummaryContext } from './VendorsBalanceSummaryProvider';
/**
* Vendors balance header -general panel.
*/
export default function VendorsBalanceSummaryHeaderGeneral() {
const { vendors } = useVendorsBalanceSummaryContext();
return (
<div>
<Row>
@@ -42,6 +46,7 @@ export default function VendorsBalanceSummaryHeaderGeneral() {
</FastField>
</Col>
</Row>
<Row>
<Col xs={5}>
<FastField name={'percentage'} type={'checkbox'}>
@@ -59,6 +64,31 @@ export default function VendorsBalanceSummaryHeaderGeneral() {
</FastField>
</Col>
</Row>
<Row>
<Col xs={4}>
<Field name={'vendorsIds'}>
{({
form: { setFieldValue },
field: { value },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'specific_vendors'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
onContactSelect={(contactsIds) => {
setFieldValue('vendorsIds', contactsIds);
}}
contacts={vendors}
contactsSelected={value}
/>
</FormGroup>
)}
</Field>
</Col>
</Row>
</div>
);
}

View File

@@ -1,6 +1,6 @@
import React from 'react';
import FinancialReportPage from '../FinancialReportPage';
import { useVendorsBalanceSummaryReport } from 'hooks/query';
import { useVendorsBalanceSummaryReport, useVendors } from 'hooks/query';
import { transformFilterFormToQuery } from '../common';
const VendorsBalanceSummaryContext = React.createContext();
@@ -13,6 +13,7 @@ function VendorsBalanceSummaryProvider({ filter, ...props }) {
filter,
]);
// Fetching vendors balance summary report based on the given query.
const {
data: VendorBalanceSummary,
isLoading: isVendorsBalanceLoading,
@@ -22,10 +23,23 @@ function VendorsBalanceSummaryProvider({ filter, ...props }) {
keepPreviousData: true,
});
// Fetch vendors list with pagination meta.
const {
data: { vendors },
isLoading: isVendorsLoading,
isFetching: isVendorsFetching,
} = useVendors({ page_size: 1000000 });
// Provider.
const provider = {
VendorBalanceSummary,
isVendorsBalanceLoading,
isVendorsBalanceFetching,
vendors,
isVendorsFetching,
isVendorsLoading,
refetch,
};

View File

@@ -12,7 +12,7 @@ import VendorsTransactionsHeaderGeneralPanel from './VendorsTransactionsHeaderGe
import withVendorsTransaction from './withVendorsTransaction';
import withVendorsTransactionsActions from './withVendorsTransactionsActions';
import { compose } from 'utils';
import { compose, transformToForm } from 'utils';
/**
* Vendors transactions header.
@@ -29,14 +29,19 @@ function VendorsTransactionsHeader({
//#withVendorsTransactionsActions
toggleVendorsTransactionsFilterDrawer: toggleFilterDrawer,
}) {
// Default form values.
const defaultValues = {
fromDate: moment().toDate(),
toDate: moment().toDate(),
vendorsIds: [],
};
// Filter form initial values.
const initialValues = {
// Initial form values.
const initialValues = transformToForm({
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
};
}, defaultValues);
// Validation schema.
const validationSchema = Yup.object().shape({
@@ -57,9 +62,7 @@ function VendorsTransactionsHeader({
};
// Handle drawer close action.
const handleDrawerClose = () => {
toggleFilterDrawer(false);
};
const handleDrawerClose = () => { toggleFilterDrawer(false); };
return (
<FinancialStatementHeader

View File

@@ -1,13 +1,42 @@
import React from 'react';
import { Field } from 'formik';
import classNames from 'classnames';
import { Classes, FormGroup } from '@blueprintjs/core';
import FinancialStatementDateRange from 'containers/FinancialStatements/FinancialStatementDateRange';
import { Row, Col } from 'components';
import { ContactsMultiSelect, FormattedMessage as T } from 'components';
import { useVendorsTransactionsContext } from './VendorsTransactionsProvider';
/**
* Vendors transactions header - General panel.
*/
export default function VendorsTransactionsHeaderGeneralPanel() {
const { vendors } = useVendorsTransactionsContext();
return (
<div>
<FinancialStatementDateRange />
<Row>
<Col xs={5}>
<Field name={'vendorsIds'}>
{({ form: { setFieldValue }, field: { value } }) => (
<FormGroup
label={<T id={'specific_vendors'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
onContactSelect={(contactsIds) => {
setFieldValue('vendorsIds', contactsIds);
}}
contacts={vendors}
contactsSelected={value}
/>
</FormGroup>
)}
</Field>
</Col>
</Row>
</div>
);
}

View File

@@ -1,6 +1,6 @@
import React, { createContext, useContext, useMemo } from 'react';
import FinancialReportPage from '../FinancialReportPage';
import { useVendorsTransactionsReport } from 'hooks/query';
import { useVendorsTransactionsReport, useVendors } from 'hooks/query';
import { transformFilterFormToQuery } from '../common';
const VendorsTransactionsContext = createContext();
@@ -11,6 +11,7 @@ const VendorsTransactionsContext = createContext();
function VendorsTransactionsProvider({ filter, ...props }) {
const query = useMemo(() => transformFilterFormToQuery(filter), [filter]);
// Fetch vendors transactions based on the given query.
const {
data: vendorsTransactions,
isFetching: isVendorsTransactionFetching,
@@ -18,10 +19,22 @@ function VendorsTransactionsProvider({ filter, ...props }) {
refetch,
} = useVendorsTransactionsReport(query, { keepPreviousData: true });
// Fetch vendors list based on the given query.
const {
data: { vendors },
isLoading: isVendorsLoading,
isFetching: isVendorsFetching,
} = useVendors({ page_size: 100000 });
const provider = {
vendorsTransactions,
isVendorsTransactionsLoading,
isVendorsTransactionFetching,
vendors,
isVendorsLoading,
isVendorsFetching,
refetch,
filter,
query,

View File

@@ -82,5 +82,5 @@ export const transformFilterFormToQuery = (form) => {
noneZero: form.accountsFilter === 'without-zero-balance',
noneTransactions: form.accountsFilter === 'with-transactions',
});
return flatObject(transformed);
return transformed;
};

View File

@@ -113,7 +113,8 @@ export const profitLossSheetReducer = (profitLoss) => {
}
if (profitLoss.other_income) {
results.push({
name: 'other_income',
name:<T id={'other_income'}/>,
total: profitLoss.other_income.total,
total_periods: profitLoss.other_income.total_periods,
children: [

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { FastField, Field, ErrorMessage } from 'formik';
import { useFormikContext, FastField, Field, ErrorMessage } from 'formik';
import {
FormGroup,
Classes,
@@ -23,12 +23,21 @@ import withSettings from 'containers/Settings/withSettings';
import { ACCOUNT_PARENT_TYPE } from 'common/accountTypes';
import { compose, inputIntent } from 'utils';
import {
sellDescriptionFieldShouldUpdate,
sellAccountFieldShouldUpdate,
sellPriceFieldShouldUpdate,
costPriceFieldShouldUpdate,
costAccountFieldShouldUpdate,
purchaseDescFieldShouldUpdate,
} from './utils';
/**
* Item form body.
*/
function ItemFormBody({ baseCurrency }) {
const { accounts } = useItemFormContext();
const { values } = useFormikContext();
return (
<div class="page-form__section page-form__section--selling-cost">
@@ -53,7 +62,11 @@ function ItemFormBody({ baseCurrency }) {
</FastField>
{/*------------- Selling price ------------- */}
<FastField name={'sell_price'}>
<FastField
name={'sell_price'}
sellable={values.sellable}
shouldUpdate={sellPriceFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'selling_price'} />}
@@ -78,7 +91,12 @@ function ItemFormBody({ baseCurrency }) {
</FastField>
{/*------------- Selling account ------------- */}
<FastField name={'sell_account_id'}>
<FastField
name={'sell_account_id'}
sellable={values.sellable}
accounts={accounts}
shouldUpdate={sellAccountFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'account'} />}
@@ -107,7 +125,11 @@ function ItemFormBody({ baseCurrency }) {
)}
</FastField>
<FastField name={'sell_description'}>
<FastField
name={'sell_description'}
sellable={values.sellable}
shouldUpdate={sellDescriptionFieldShouldUpdate}
>
{({ form: { values }, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'description'} />}
@@ -146,7 +168,11 @@ function ItemFormBody({ baseCurrency }) {
</FastField>
{/*------------- Cost price ------------- */}
<FastField name={'cost_price'}>
<FastField
name={'cost_price'}
purchasable={values.purchasable}
shouldUpdate={costPriceFieldShouldUpdate}
>
{({ field, form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'cost_price'} />}
@@ -171,7 +197,12 @@ function ItemFormBody({ baseCurrency }) {
</FastField>
{/*------------- Cost account ------------- */}
<FastField name={'cost_account_id'}>
<FastField
name={'cost_account_id'}
purchasable={values.purchasable}
accounts={accounts}
shouldUpdate={costAccountFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'account'} />}
@@ -200,7 +231,11 @@ function ItemFormBody({ baseCurrency }) {
)}
</FastField>
<FastField name={'purchase_description'}>
<FastField
name={'purchase_description'}
purchasable={values.purchasable}
shouldUpdate={purchaseDescFieldShouldUpdate}
>
{({ form: { values }, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'description'} />}

View File

@@ -8,6 +8,7 @@ import classNames from 'classnames';
import withSettings from 'containers/Settings/withSettings';
import { accountsFieldShouldUpdate } from './utils';
import { compose, inputIntent } from 'utils';
import { ACCOUNT_TYPE } from 'common/accountTypes';
import { useItemFormContext } from './ItemFormProvider';
@@ -27,7 +28,11 @@ function ItemFormInventorySection({ baseCurrency }) {
<Row>
<Col xs={6}>
{/*------------- Inventory account ------------- */}
<FastField name={'inventory_account_id'}>
<FastField
name={'inventory_account_id'}
accounts={accounts}
shouldUpdate={accountsFieldShouldUpdate}
>
{({ form, field: { value }, meta: { touched, error } }) => (
<FormGroup
label={<T id={'inventory_account'} />}

View File

@@ -21,6 +21,7 @@ import { CLASSES } from 'common/classes';
import { useItemFormContext } from './ItemFormProvider';
import { handleStringChange, inputIntent } from 'utils';
import { categoriesFieldShouldUpdate } from './utils';
/**
* Item form primary section.
@@ -130,7 +131,11 @@ export default function ItemFormPrimarySection() {
</FastField>
{/*----------- Item category ----------*/}
<FastField name={'category_id'}>
<FastField
name={'category_id'}
categories={itemsCategories}
shouldUpdate={categoriesFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'category'} />}

View File

@@ -1,6 +1,7 @@
import intl from 'react-intl-universal';
import { Intent } from '@blueprintjs/core';
import { AppToaster } from 'components';
import { defaultFastFieldShouldUpdate } from 'utils';
export const transitionItemTypeKeyToLabel = (itemTypeKey) => {
const table = {
@@ -28,7 +29,9 @@ export const handleDeleteErrors = (errors) => {
)
) {
AppToaster.show({
message: intl.get('you_could_not_delete_item_that_has_associated_inventory_adjustments_transacions'),
message: intl.get(
'you_could_not_delete_item_that_has_associated_inventory_adjustments_transacions',
),
intent: Intent.DANGER,
});
}
@@ -38,8 +41,83 @@ export const handleDeleteErrors = (errors) => {
)
) {
AppToaster.show({
message: intl.get('cannot_change_item_type_to_inventory_with_item_has_associated_transactions'),
message: intl.get(
'cannot_change_item_type_to_inventory_with_item_has_associated_transactions',
),
intent: Intent.DANGER,
});
}
};
/**
* Detarmines accounts fast field should update.
*/
export const accountsFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.accounts !== oldProps.accounts ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Detarmines categories fast field should update.
*/
export const categoriesFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.categories !== oldProps.categories ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Sell price fast field should update.
*/
export const sellPriceFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.sellable !== oldProps.sellable ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Sell account fast field should update.
*/
export const sellAccountFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.accounts !== oldProps.accounts ||
newProps.sellable !== oldProps.sellable ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Sell description fast field should update.
*/
export const sellDescriptionFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.sellable !== oldProps.sellable ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
export const costAccountFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.accounts !== oldProps.accounts ||
newProps.purchasable !== oldProps.purchasable ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
export const costPriceFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.purchasable !== oldProps.purchasable ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
export const purchaseDescFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.purchasable !== oldProps.purchasable ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};

View File

@@ -22,15 +22,20 @@ import {
handleDateChange,
} from 'utils';
import { CLASSES } from 'common/classes';
import countriesOptions from 'common/countries';
import currencies from 'common/currencies';
import { getFiscalYearOptions } from 'common/fiscalYearOptions';
import languages from 'common/languagesOptions';
import dateFormatsOptions from 'common/dateFormatsOptions';
import { getCountries } from 'common/countries';
import { getCurrencies } from 'common/currencies';
import { getFiscalYear } from 'common/fiscalYearOptions';
import { getLanguages } from 'common/languagesOptions';
import { getDateFormats } from 'common/dateFormatsOptions';
export default function PreferencesGeneralForm({}) {
const history = useHistory();
const fiscalYearOptions = getFiscalYearOptions();
const FiscalYear = getFiscalYear();
const Countries = getCountries();
const Languages = getLanguages();
const Currencies = getCurrencies();
const DataFormats = getDateFormats();
const handleCloseClick = () => {
history.go(-1);
@@ -38,6 +43,7 @@ export default function PreferencesGeneralForm({}) {
return (
<Form>
{/* ---------- Organization name ---------- */}
<FastField name={'name'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
@@ -53,6 +59,7 @@ export default function PreferencesGeneralForm({}) {
)}
</FastField>
{/* ---------- Financial starting date ---------- */}
<FastField name={'financial_date_start'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
@@ -89,6 +96,7 @@ export default function PreferencesGeneralForm({}) {
)}
</FastField>
{/* ---------- Location ---------- */}
<FastField name={'location'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
@@ -102,7 +110,7 @@ export default function PreferencesGeneralForm({}) {
intent={inputIntent({ error, touched })}
>
<ListSelect
items={countriesOptions}
items={Countries}
onItemSelect={({ value }) => {
form.setFieldValue('location', value);
}}
@@ -116,6 +124,7 @@ export default function PreferencesGeneralForm({}) {
)}
</FastField>
{/* ---------- Base currency ---------- */}
<FastField name={'base_currency'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
@@ -133,7 +142,7 @@ export default function PreferencesGeneralForm({}) {
}
>
<ListSelect
items={currencies}
items={Currencies}
onItemSelect={(currency) => {
form.setFieldValue('base_currency', currency.code);
}}
@@ -148,6 +157,7 @@ export default function PreferencesGeneralForm({}) {
)}
</FastField>
{/* --------- Fiscal Year ----------- */}
<FastField name={'fiscal_year'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
@@ -159,7 +169,7 @@ export default function PreferencesGeneralForm({}) {
intent={inputIntent({ error, touched })}
>
<ListSelect
items={fiscalYearOptions}
items={FiscalYear}
onItemSelect={({ value }) =>
form.setFieldValue('fiscal_year', value)
}
@@ -173,6 +183,7 @@ export default function PreferencesGeneralForm({}) {
)}
</FastField>
{/* ---------- Language ---------- */}
<FastField name={'language'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
@@ -184,7 +195,7 @@ export default function PreferencesGeneralForm({}) {
helperText={<ErrorMessage name="language" />}
>
<ListSelect
items={languages}
items={Languages}
selectedItemProp={'value'}
textProp={'name'}
defaultText={<T id={'select_language'} />}
@@ -198,6 +209,7 @@ export default function PreferencesGeneralForm({}) {
)}
</FastField>
{/* ---------- Time zone ---------- */}
<FastField name={'time_zone'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
@@ -224,6 +236,7 @@ export default function PreferencesGeneralForm({}) {
)}
</FastField>
{/* --------- Data format ----------- */}
<FastField name={'date_format'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
@@ -235,7 +248,7 @@ export default function PreferencesGeneralForm({}) {
helperText={<ErrorMessage name="date_format" />}
>
<ListSelect
items={dateFormatsOptions}
items={DataFormats}
onItemSelect={(dateFormat) => {
form.setFieldValue('date_format', dateFormat.value);
}}

View File

@@ -48,7 +48,7 @@ function BillForm({
currency_code: baseCurrency,
}),
}),
[bill],
[bill, baseCurrency],
);
// Transform response error to fields.

View File

@@ -7,6 +7,7 @@ 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';
@@ -28,7 +29,11 @@ function BillFormHeader() {
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
{/* ------- Vendor name ------ */}
<FastField name={'vendor_id'}>
<FastField
name={'vendor_id'}
vendors={vendors}
shouldUpdate={vendorsFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'vendor_name'} />}

View File

@@ -4,13 +4,23 @@ import { FastField } from 'formik';
import { CLASSES } from 'common/classes';
import { useBillFormContext } from './BillFormProvider';
import ItemsEntriesTable from 'containers/Entries/ItemsEntriesTable';
import {
entriesFieldShouldUpdate
} from './utils';
/**
* Bill form body.
*/
export default function BillFormBody({ defaultBill }) {
const { items } = useBillFormContext();
return (
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
<FastField name={'entries'}>
<FastField
name={'entries'}
items={items}
shouldUpdate={entriesFieldShouldUpdate}
>
{({
form: { values, setFieldValue },
field: { value },
@@ -25,6 +35,7 @@ export default function BillFormBody({ defaultBill }) {
errors={error}
linesNumber={4}
currencyCode={values.currency_code}
landedCost={true}
/>
)}
</FastField>

View File

@@ -2,7 +2,11 @@ import moment from 'moment';
import intl from 'react-intl-universal';
import { Intent } from '@blueprintjs/core';
import { AppToaster } from 'components';
import { transformToForm, repeatValue } from 'utils';
import {
defaultFastFieldShouldUpdate,
transformToForm,
repeatValue,
} from 'utils';
export const MIN_LINES_NUMBER = 4;
@@ -13,6 +17,7 @@ export const defaultBillEntry = {
discount: '',
quantity: '',
description: '',
landed_cost: false,
};
export const defaultBill = {
@@ -51,4 +56,34 @@ export const handleDeleteErrors = (errors) => {
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)
);
};

View File

@@ -14,6 +14,7 @@ import withBillActions from './withBillsActions';
import withSettings from 'containers/Settings/withSettings';
import withAlertsActions from 'containers/Alert/withAlertActions';
import withDialogActions from 'containers/Dialog/withDialogActions';
import withDrawerActions from 'containers/Drawer/withDrawerActions';
import { useBillsTableColumns, ActionsMenu } from './components';
import { useBillsListContext } from './BillsListProvider';
@@ -32,15 +33,13 @@ function BillsDataTable({
// #withDialogActions
openDialog,
// #withDrawerActions
openDrawer,
}) {
// Bills list context.
const {
bills,
pagination,
isBillsLoading,
isBillsFetching,
isEmptyStatus,
} = useBillsListContext();
const { bills, pagination, isBillsLoading, isBillsFetching, isEmptyStatus } =
useBillsListContext();
const history = useHistory();
@@ -78,6 +77,16 @@ function BillsDataTable({
openDialog('quick-payment-made', { billId: id });
};
// handle allocate landed cost.
const handleAllocateLandedCost = ({ id }) => {
openDialog('allocate-landed-cost', { billId: id });
};
// Handle view detail bill.
const handleViewDetailBill = ({ id }) => {
openDrawer('bill-drawer', { billId: id });
};
if (isEmptyStatus) {
return <BillsEmptyStatus />;
}
@@ -105,6 +114,8 @@ function BillsDataTable({
onEdit: handleEditBill,
onOpen: handleOpenBill,
onQuick: handleQuickPaymentMade,
onAllocateLandedCost: handleAllocateLandedCost,
onViewDetails: handleViewDetailBill,
}}
/>
);
@@ -114,6 +125,7 @@ export default compose(
withBills(({ billsTableState }) => ({ billsTableState })),
withBillActions,
withAlertsActions,
withDrawerActions,
withDialogActions,
withSettings(({ organizationSettings }) => ({
baseCurrency: organizationSettings?.baseCurrency,

View File

@@ -20,7 +20,14 @@ import moment from 'moment';
* Actions menu.
*/
export function ActionsMenu({
payload: { onEdit, onOpen, onDelete, onQuick },
payload: {
onEdit,
onOpen,
onDelete,
onQuick,
onViewDetails,
onAllocateLandedCost,
},
row: { original },
}) {
return (
@@ -28,6 +35,7 @@ export function ActionsMenu({
<MenuItem
icon={<Icon icon="reader-18" />}
text={intl.get('view_details')}
onClick={safeCallback(onViewDetails, original)}
/>
<MenuDivider />
<MenuItem
@@ -50,7 +58,11 @@ export function ActionsMenu({
onClick={safeCallback(onQuick, original)}
/>
</If>
<MenuItem
icon={<Icon icon="receipt-24" iconSize={16} />}
text={intl.get('allocate_landed_coast')}
onClick={safeCallback(onAllocateLandedCost, original)}
/>
<MenuItem
text={intl.get('delete_bill')}
intent={Intent.DANGER}

View File

@@ -36,6 +36,7 @@ import {
fullAmountPaymentEntries,
amountPaymentEntries,
} from 'utils';
import { accountsFieldShouldUpdate, vendorsFieldShouldUpdate } from './utils';
/**
* Payment made form header fields.
@@ -48,17 +49,14 @@ function PaymentMadeFormHeaderFields({ baseCurrency }) {
} = useFormikContext();
// Payment made form context.
const {
vendors,
accounts,
isNewMode,
setPaymentVendorId,
} = usePaymentMadeFormContext();
const { vendors, accounts, isNewMode, setPaymentVendorId } =
usePaymentMadeFormContext();
// Sumation of payable full-amount.
const payableFullAmount = useMemo(() => safeSumBy(entries, 'due_amount'), [
entries,
]);
const payableFullAmount = useMemo(
() => safeSumBy(entries, 'due_amount'),
[entries],
);
// Handle receive full-amount click.
const handleReceiveFullAmountClick = () => {
@@ -78,7 +76,11 @@ function PaymentMadeFormHeaderFields({ baseCurrency }) {
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
{/* ------------ Vendor name ------------ */}
<FastField name={'vendor_id'}>
<FastField
name={'vendor_id'}
vendors={vendors}
shouldUpdate={vendorsFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'vendor_name'} />}
@@ -157,7 +159,7 @@ function PaymentMadeFormHeaderFields({ baseCurrency }) {
small={true}
minimal={true}
>
<T id={'receive_full_amount'} /> (
<T id={'receive_full_amount'} /> (
<Money amount={payableFullAmount} currency={baseCurrency} />)
</Button>
</FormGroup>
@@ -184,7 +186,11 @@ function PaymentMadeFormHeaderFields({ baseCurrency }) {
</FastField>
{/* ------------ Payment account ------------ */}
<FastField name={'payment_account_id'}>
<FastField
name={'payment_account_id'}
accounts={accounts}
shouldUpdate={accountsFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'payment_account'} />}

View File

@@ -1,5 +1,9 @@
import moment from 'moment';
import { safeSumBy, transformToForm } from 'utils';
import {
defaultFastFieldShouldUpdate,
safeSumBy,
transformToForm,
} from 'utils';
export const ERRORS = {
PAYMENT_NUMBER_NOT_UNIQUE: 'PAYMENT.NUMBER.NOT.UNIQUE',
@@ -9,10 +13,10 @@ export const ERRORS = {
export const defaultPaymentMadeEntry = {
bill_id: '',
payment_amount: '',
currency_code:'',
currency_code: '',
id: null,
due_amount: null,
amount:''
amount: '',
};
// Default initial values of payment made.
@@ -48,7 +52,26 @@ export const transformToNewPageEntries = (entries) => {
return entries.map((entry) => ({
...transformToForm(entry, defaultPaymentMadeEntry),
payment_amount: '',
currency_code:entry.currency_code,
currency_code: entry.currency_code,
}));
}
};
/**
* Detarmines vendors fast field when update.
*/
export const vendorsFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.vendors !== oldProps.vendors ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Detarmines accounts fast field when update.
*/
export const accountsFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.accounts !== oldProps.accounts ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};

View File

@@ -27,6 +27,7 @@ function EstimateFormHeader({
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<EstimateFormHeaderFields />
<PageFormBigNumber
label={intl.get('amount')}
amount={totalDueAmount}

View File

@@ -15,6 +15,7 @@ import {
inputIntent,
handleDateChange,
} from 'utils';
import { customersFieldShouldUpdate } from './utils';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import {
@@ -67,7 +68,11 @@ function EstimateFormHeader({
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
{/* ----------- Customer name ----------- */}
<FastField name={'customer_id'}>
<FastField
name={'customer_id'}
customers={customers}
shouldUpdate={customersFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'customer_name'} />}
@@ -170,7 +175,9 @@ function EstimateFormHeader({
}}
tooltip={true}
tooltipProps={{
content: <T id={'setting_your_auto_generated_estimate_number'}/>,
content: (
<T id={'setting_your_auto_generated_estimate_number'} />
),
position: Position.BOTTOM_LEFT,
}}
/>

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