feat: fix item form in edit mode.

This commit is contained in:
Ahmed Bouhuolia
2020-11-10 17:41:53 +02:00
parent b2fd2e7cdb
commit 93fbe1fc98
6 changed files with 159 additions and 116 deletions

View File

@@ -6,7 +6,7 @@ import {
} from '@blueprintjs/core'; } from '@blueprintjs/core';
import { queryCache } from 'react-query'; import { queryCache } from 'react-query';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { pick } from 'lodash'; import { pick, pickBy } from 'lodash';
import { useIntl } from 'react-intl'; import { useIntl } from 'react-intl';
import classNames from 'classnames'; import classNames from 'classnames';
@@ -23,7 +23,23 @@ import useMedia from 'hooks/useMedia';
import withItemDetail from 'containers/Items/withItemDetail'; import withItemDetail from 'containers/Items/withItemDetail';
import withDashboardActions from 'containers/Dashboard/withDashboardActions'; import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import { compose } from 'utils'; import { compose, transformToForm } from 'utils';
const defaultInitialValues = {
active: true,
name: '',
type: 'service',
sku: '',
cost_price: '',
sell_price: '',
cost_account_id: '',
sell_account_id: '',
inventory_account_id: '',
category_id: '',
note: '',
sellable: true,
purchasable: true,
};
/** /**
* Item form. * Item form.
@@ -71,54 +87,61 @@ function ItemForm({
.required() .required()
.label(formatMessage({ id: 'item_type_' })), .label(formatMessage({ id: 'item_type_' })),
sku: Yup.string().trim(), sku: Yup.string().trim(),
cost_price: Yup.number(), cost_price: Yup.number()
sell_price: Yup.number(), .when(['purchasable'], {
is: true,
then: Yup.number().required(),
otherwise: Yup.number().nullable(true),
}),
sell_price: Yup.number()
.when(['sellable'], {
is: true,
then: Yup.number().required(),
otherwise: Yup.number().nullable(true),
}),
cost_account_id: Yup.number() cost_account_id: Yup.number()
.required() .when(['purchasable'], {
is: true,
then: Yup.number().required(),
otherwise: Yup.number().nullable(true),
})
.label(formatMessage({ id: 'cost_account_id' })), .label(formatMessage({ id: 'cost_account_id' })),
sell_account_id: Yup.number() sell_account_id: Yup.number()
.required() .when(['sellable'], {
is: true,
then: Yup.number().required(),
otherwise: Yup.number().nullable(),
})
.label(formatMessage({ id: 'sell_account_id' })), .label(formatMessage({ id: 'sell_account_id' })),
inventory_account_id: Yup.number().when('type', { inventory_account_id: Yup.number()
.when(['type'], {
is: (value) => value === 'inventory', is: (value) => value === 'inventory',
then: Yup.number().required(), then: Yup.number().required(),
otherwise: Yup.number().nullable(), otherwise: Yup.number().nullable(),
}), })
category_id: Yup.number().nullable(), .label(formatMessage({ id: 'Inventory account' })),
category_id: Yup.number().positive().nullable(),
stock: Yup.string() || Yup.boolean(), stock: Yup.string() || Yup.boolean(),
sellable: Yup.boolean().required(), sellable: Yup.boolean().required(),
purchasable: Yup.boolean().required(), purchasable: Yup.boolean().required(),
}); });
const defaultInitialValues = useMemo(
() => ({ /**
active: true, * Initial values in create and edit mode.
name: '', */
type: 'service',
sku: '',
cost_price: 0,
sell_price: 0,
cost_account_id: null,
sell_account_id: null,
inventory_account_id: null,
category_id: null,
note: '',
sellable: true,
purchasable: true,
}),
[],
);
const initialValues = useMemo( const initialValues = useMemo(
() => ({ () => ({
...(itemDetail
? {
...pick(itemDetail, Object.keys(defaultInitialValues)),
}
: {
...defaultInitialValues, ...defaultInitialValues,
/**
* We only care about the fields in the form. Previously unfilled optional
* values such as `notes` come back from the API as null, so remove those
* as well.
*/
...transformToForm(itemDetail, defaultInitialValues),
}), }),
}), [],
[itemDetail, defaultInitialValues],
); );
useEffect(() => { useEffect(() => {
@@ -141,7 +164,7 @@ function ItemForm({
'the_item_has_been_successfully_edited', 'the_item_has_been_successfully_edited',
}, },
{ {
number: itemDetail.id, number: itemId,
}, },
), ),
intent: Intent.SUCCESS, intent: Intent.SUCCESS,
@@ -156,7 +179,7 @@ function ItemForm({
if (isNewMode) { if (isNewMode) {
requestSubmitItem(form).then(onSuccess).catch(onError); requestSubmitItem(form).then(onSuccess).catch(onError);
} else { } else {
requestEditItem(form).then(onSuccess).catch(onError); requestEditItem(itemId, form).then(onSuccess).catch(onError);
} }
}; };

View File

@@ -36,15 +36,15 @@ function ItemFormBody({
<div class="page-form__section page-form__section--selling-cost"> <div class="page-form__section page-form__section--selling-cost">
<Row> <Row>
<Col xs={6}> <Col xs={6}>
{/*------------- Sellable checkbox ------------- */} {/*------------- Sellable checkbox ------------- */}
<FormGroup <FormGroup inline={true} className={'form-group--sellable'}>
inline={true}
className={'form-group--sellable'}
>
<Checkbox <Checkbox
inline={true} inline={true}
label={<h3><T id={'i_purchase_this_item'} /></h3>} label={
<h3>
<T id={'i_purchase_this_item'} />
</h3>
}
checked={values.sellable} checked={values.sellable}
{...getFieldProps('sellable')} {...getFieldProps('sellable')}
/> />
@@ -54,26 +54,22 @@ function ItemFormBody({
<FormGroup <FormGroup
label={<T id={'selling_price'} />} label={<T id={'selling_price'} />}
className={'form-group--item-selling-price'} className={'form-group--item-selling-price'}
intent={ intent={errors.sell_price && touched.sell_price && Intent.DANGER}
errors.selling_price && touched.selling_price && Intent.DANGER
}
helperText={ helperText={
<ErrorMessage {...{ errors, touched }} name="selling_price" /> <ErrorMessage {...{ errors, touched }} name="sell_price" />
} }
inline={true} inline={true}
> >
<MoneyInputGroup <MoneyInputGroup
value={values.selling_price} value={values.sell_price}
prefix={'$'} prefix={'$'}
onChange={(e, value) => { onChange={(e, value) => {
setFieldValue('selling_price', value); setFieldValue('sell_price', value);
}} }}
inputGroupProps={{ inputGroupProps={{
medium: true, medium: true,
intent: intent:
errors.selling_price && errors.sell_price && touched.sell_price && Intent.DANGER,
touched.selling_price &&
Intent.DANGER,
}} }}
disabled={!values.sellable} disabled={!values.sellable}
/> />
@@ -107,18 +103,18 @@ function ItemFormBody({
filterByTypes={['income']} filterByTypes={['income']}
/> />
</FormGroup> </FormGroup>
</Col> </Col>
<Col xs={6}> <Col xs={6}>
{/*------------- Purchasable checbox ------------- */} {/*------------- Purchasable checbox ------------- */}
<FormGroup <FormGroup inline={true} className={'form-group--purchasable'}>
inline={true}
className={'form-group--purchasable'}
>
<Checkbox <Checkbox
inline={true} inline={true}
label={<h3><T id={'i_sell_this_item'} /></h3>} label={
<h3>
<T id={'i_sell_this_item'} />
</h3>
}
defaultChecked={values.purchasable} defaultChecked={values.purchasable}
{...getFieldProps('purchasable')} {...getFieldProps('purchasable')}
/> />
@@ -169,7 +165,7 @@ function ItemFormBody({
<AccountsSelectList <AccountsSelectList
accounts={accountsList} accounts={accountsList}
onAccountSelected={(account) => { onAccountSelected={(account) => {
setFieldValue('cost_account_id', account.id) setFieldValue('cost_account_id', account.id);
}} }}
defaultSelectText={<T id={'select_account'} />} defaultSelectText={<T id={'select_account'} />}
selectedAccountId={values.cost_account_id} selectedAccountId={values.cost_account_id}

View File

@@ -1,11 +1,17 @@
import React from 'react'; import React from 'react';
import { FormGroup, Intent, InputGroup, Classes } from '@blueprintjs/core'; import {
import { AccountsSelectList, ErrorMessage, Col, Row } from 'components'; FormGroup,
Intent,
InputGroup,
Position,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { AccountsSelectList, ErrorMessage, Col, Row, Hint } from 'components';
import { CLASSES } from 'common/classes';
import { FormattedMessage as T } from 'react-intl'; import { FormattedMessage as T } from 'react-intl';
import classNames from 'classnames'; import classNames from 'classnames';
import withAccounts from 'containers/Accounts/withAccounts'; import withAccounts from 'containers/Accounts/withAccounts';
import { compose, tansformDateValue, momentFormatter } from 'utils';
import { compose } from 'utils';
/** /**
* Item form inventory sections. * Item form inventory sections.
@@ -21,12 +27,12 @@ function ItemFormInventorySection({
}) { }) {
return ( return (
<div class="page-form__section page-form__section--inventory"> <div class="page-form__section page-form__section--inventory">
<Row>
<Col xs={6}>
<h3> <h3>
<T id={'inventory_information'} /> <T id={'inventory_information'} />
</h3> </h3>
<Row>
<Col xs={6}>
{/*------------- Inventory account ------------- */} {/*------------- Inventory account ------------- */}
<FormGroup <FormGroup
label={<T id={'inventory_account'} />} label={<T id={'inventory_account'} />}
@@ -45,7 +51,7 @@ function ItemFormInventorySection({
className={classNames( className={classNames(
'form-group--item-inventory_account', 'form-group--item-inventory_account',
'form-group--select-list', 'form-group--select-list',
Classes.FILL, CLASSES.FILL,
)} )}
> >
<AccountsSelectList <AccountsSelectList
@@ -59,26 +65,50 @@ function ItemFormInventorySection({
</FormGroup> </FormGroup>
<FormGroup <FormGroup
label={<T id={'opening_stock'} />} label={<T id={'opening_quantity'} />}
className={'form-group--item-stock'} labelInfo={<Hint />}
className={'form-group--opening_quantity'}
inline={true} inline={true}
> >
<InputGroup <InputGroup
medium={true} medium={true}
intent={errors.stock && Intent.DANGER} intent={errors.opening_quantity && Intent.DANGER}
{...getFieldProps('stock')} {...getFieldProps('opening_quantity')}
/> />
</FormGroup> </FormGroup>
<FormGroup <FormGroup
label={'Opening average cost'} label={<T id={'opening_date'} />}
className={'form-group--item-stock'} labelInfo={<Hint />}
className={classNames(
'form-group--select-list',
'form-group--opening_date',
CLASSES.FILL,
)}
inline={true}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(values.payment_date)}
onChange={(value) => {
setFieldValue('opening_date', value);
}}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
/>
</FormGroup>
</Col>
<Col xs={6}>
<FormGroup
label={'Opening average rate'}
labelInfo={<Hint />}
className={'form-group--opening_average_rate'}
inline={true} inline={true}
> >
<InputGroup <InputGroup
medium={true} medium={true}
intent={errors.stock && Intent.DANGER} intent={errors.opening_average_rate && Intent.DANGER}
{...getFieldProps('stock')} {...getFieldProps('opening_average_rate')}
/> />
</FormGroup> </FormGroup>
</Col> </Col>

View File

@@ -39,6 +39,14 @@ function ItemFormPrimarySection({
// #withItemCategories // #withItemCategories
categoriesList, categoriesList,
}) { }) {
const itemTypeHintContent = (
<>
<div class="mb1"><strong>{'Service: '}</strong>{'Services that you provide to customers. '}</div>
<div class="mb1"><strong>{'Inventory: '}</strong>{'Products you buy and/or sell and that you track quantities of.'}</div>
<div class="mb1"><strong>{'Non-Inventory: '}</strong>{'Products you buy and/or sell but dont need to (or cant) track quantities of, for example, nuts and bolts used in an installation.'}</div>
</>);
return ( return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}> <div className={classNames(CLASSES.PAGE_FORM_HEADER_PRIMARY)}>
<Row> <Row>
@@ -47,7 +55,12 @@ function ItemFormPrimarySection({
<FormGroup <FormGroup
medium={true} medium={true}
label={<T id={'item_type'} />} label={<T id={'item_type'} />}
labelInfo={<FieldRequiredHint />} labelInfo={
<span>
<FieldRequiredHint />
<Hint content={itemTypeHintContent} position={Position.BOTTOM_LEFT} />
</span>
}
className={'form-group--item-type'} className={'form-group--item-type'}
intent={errors.type && touched.type && Intent.DANGER} intent={errors.type && touched.type && Intent.DANGER}
helperText={<ErrorMessage {...{ errors, touched }} name="type" />} helperText={<ErrorMessage {...{ errors, touched }} name="type" />}
@@ -56,48 +69,20 @@ function ItemFormPrimarySection({
<RadioGroup <RadioGroup
inline={true} inline={true}
onChange={handleStringChange((value) => { onChange={handleStringChange((value) => {
setFieldValue('item_type', value); setFieldValue('type', value);
})} })}
selectedValue={values.item_type} selectedValue={values.type}
> >
<Radio <Radio
label={ label={<T id={'service'} />}
<Tooltip
className={Classes.TOOLTIP_INDICATOR}
content={'Services that you provide to customers.'}
position={Position.BOTTOM_LEFT}
>
<T id={'service'} />
</Tooltip>
}
value="service" value="service"
/> />
<Radio <Radio
label={ label={<T id={'inventory'} />}
<Tooltip
className={Classes.TOOLTIP_INDICATOR}
content={
'Products you buy and/or sell and that you track quantities of.'
}
position={Position.BOTTOM_LEFT}
>
<T id={'inventory'} />
</Tooltip>
}
value="inventory" value="inventory"
/> />
<Radio <Radio
label={ label={<T id={'non_inventory'} />}
<Tooltip
className={Classes.TOOLTIP_INDICATOR}
content={
'Products you buy and/or sell but dont need to (or cant) track quantities of, for example, nuts and bolts used in an installation.'
}
position={Position.BOTTOM_LEFT}
>
<T id={'non_inventory'} />
</Tooltip>
}
value="non_inventory" value="non_inventory"
/> />
</RadioGroup> </RadioGroup>
@@ -121,7 +106,7 @@ function ItemFormPrimarySection({
{/*----------- SKU ----------*/} {/*----------- SKU ----------*/}
<FormGroup <FormGroup
label={<T id={'sku'} />} label={<T id={'item_code'} />}
labelInfo={<Hint />} labelInfo={<Hint />}
className={'form-group--item-sku'} className={'form-group--item-sku'}
intent={errors.sku && touched.sku && Intent.DANGER} intent={errors.sku && touched.sku && Intent.DANGER}

View File

@@ -100,7 +100,7 @@ export default {
cost_price: 'Cost Price', cost_price: 'Cost Price',
inventory_information: 'Inventory Information', inventory_information: 'Inventory Information',
inventory_account: 'Inventory Account', inventory_account: 'Inventory Account',
opening_stock: 'Opening Stock', opening_quantity: 'Opening quantity',
save: 'Save', save: 'Save',
save_as_draft: 'Save as Draft', save_as_draft: 'Save as Draft',
active: 'Active', active: 'Active',
@@ -810,4 +810,6 @@ export default {
i_purchase_this_item: 'I purchase this item from a vendor.', i_purchase_this_item: 'I purchase this item from a vendor.',
i_sell_this_item: 'I sell this item to a customer.', i_sell_this_item: 'I sell this item to a customer.',
select_display_name_as:'Select display name as', select_display_name_as:'Select display name as',
opening_date: 'Opening date',
item_code: 'Item code',
}; };

View File

@@ -278,3 +278,10 @@ export const itemsStartWith = (items, char) => {
export const saveInvoke = (func, ...rest) => { export const saveInvoke = (func, ...rest) => {
return func && func(...rest); return func && func(...rest);
} }
export const transformToForm = (obj, emptyInitialValues) => {
return _.pickBy(
obj,
(val, key) => val !== null && Object.keys(emptyInitialValues).includes(key),
)
}