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

@@ -0,0 +1,6 @@
import intl from 'react-intl-universal';
export default [
{ name: intl.get('bills'), value: 'Bill' },
{ name: intl.get('expenses'), value: 'Expense' },
];

View File

@@ -1,3 +1,8 @@
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
export default [{ name: intl.get('libya'), value: 'libya' }]; export const getCountries = () => [
{
name: intl.get('libya'),
value: 'libya',
},
];

View File

@@ -1,6 +1,6 @@
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
export default [ export const getCurrencies = () => [
{ name: intl.get('us_dollar'), code: 'USD' }, { name: intl.get('us_dollar'), code: 'USD' },
{ name: intl.get('euro'), code: 'EUR' }, { name: intl.get('euro'), code: 'EUR' },
{ name: intl.get('libyan_diner'), code: 'LYD' }, { name: intl.get('libyan_diner'), code: 'LYD' },

View File

@@ -1,7 +1,7 @@
import moment from 'moment'; import moment from 'moment';
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
export default [ export const getDateFormats =()=> [
{ {
id: 1, id: 1,
name: intl.get('mm_dd_yy'), name: intl.get('mm_dd_yy'),

View File

@@ -1,6 +1,6 @@
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
export const getFiscalYearOptions = () => [ export const getFiscalYear = () => [
{ {
id: 0, id: 0,
name: `${intl.get('january')} - ${intl.get('december')}`, name: `${intl.get('january')} - ${intl.get('december')}`,

View File

@@ -1,6 +1,6 @@
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
export default [ export const getLanguages = () => [
{ name: intl.get('english'), value: 'en' }, { name: intl.get('english'), value: 'en' },
{ name: intl.get('arabic'), value: 'ar' }, { name: intl.get('arabic'), value: 'ar' },
]; ];

View File

@@ -4,6 +4,7 @@ import { setLocale } from 'yup';
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
import { find } from 'lodash'; import { find } from 'lodash';
import rtlDetect from 'rtl-detect'; import rtlDetect from 'rtl-detect';
import { AppIntlProvider } from './AppIntlProvider';
import DashboardLoadingIndicator from 'components/Dashboard/DashboardLoadingIndicator'; import DashboardLoadingIndicator from 'components/Dashboard/DashboardLoadingIndicator';
const SUPPORTED_LOCALES = [ const SUPPORTED_LOCALES = [
@@ -40,16 +41,14 @@ function loadYupLocales(currentLocale) {
/** /**
* Modifies the html document direction to RTl if it was rtl-language. * Modifies the html document direction to RTl if it was rtl-language.
*/ */
function useDocumentDirectionModifier(locale) { function useDocumentDirectionModifier(locale, isRTL) {
React.useEffect(() => { React.useEffect(() => {
const isRTL = rtlDetect.isRtlLang(locale);
if (isRTL) { if (isRTL) {
const htmlDocument = document.querySelector('html'); const htmlDocument = document.querySelector('html');
htmlDocument.setAttribute('dir', 'rtl'); htmlDocument.setAttribute('dir', 'rtl');
htmlDocument.setAttribute('lang', locale); htmlDocument.setAttribute('lang', locale);
} }
}, []); }, [isRTL, locale]);
} }
/** /**
@@ -59,8 +58,10 @@ export default function AppIntlLoader({ children }) {
const [isLoading, setIsLoading] = React.useState(true); const [isLoading, setIsLoading] = React.useState(true);
const currentLocale = getCurrentLocal(); const currentLocale = getCurrentLocal();
const isRTL = rtlDetect.isRtlLang(currentLocale);
// Modifies the html document direction // Modifies the html document direction
useDocumentDirectionModifier(currentLocale); useDocumentDirectionModifier(currentLocale, isRTL);
React.useEffect(() => { React.useEffect(() => {
// Lodas the locales data file. // Lodas the locales data file.
@@ -88,8 +89,10 @@ export default function AppIntlLoader({ children }) {
}, [currentLocale]); }, [currentLocale]);
return ( return (
<DashboardLoadingIndicator isLoading={isLoading}> <AppIntlProvider currentLocale={currentLocale} isRTL={isRTL}>
{children} <DashboardLoadingIndicator isLoading={isLoading}>
</DashboardLoadingIndicator> {children}
</DashboardLoadingIndicator>
</AppIntlProvider>
); );
} }

View File

@@ -0,0 +1,24 @@
import React, { createContext } from 'react';
const AppIntlContext = createContext();
/**
* Application intl provider.
*/
function AppIntlProvider({ currentLocale, isRTL, children }) {
const provider = {
currentLocale,
isRTL,
isLTR: !isRTL,
};
return (
<AppIntlContext.Provider value={provider}>
{children}
</AppIntlContext.Provider>
);
}
const useAppIntlContext = () => React.useContext(AppIntlContext);
export { AppIntlProvider, useAppIntlContext };

View File

@@ -0,0 +1,5 @@
import React from 'react';
export default function Card({ children }) {
return <div class="card">{children}</div>;
}

View File

@@ -1,58 +1,57 @@
import React, { useMemo, useCallback, useState } from 'react'; import React, { useCallback, useState } from 'react';
import { MenuItem, Button } from '@blueprintjs/core'; import { MenuItem, Button } from '@blueprintjs/core';
import { omit } from 'lodash'; import intl from 'react-intl-universal';
import MultiSelect from 'components/MultiSelect'; import MultiSelect from 'components/MultiSelect';
import { FormattedMessage as T } from 'components'; import { FormattedMessage as T } from 'components';
import intl from 'react-intl-universal'; import { safeInvoke } from 'utils';
/**
* Contacts multi-select component.
*/
export default function ContactsMultiSelect({ export default function ContactsMultiSelect({
contacts, contacts,
defaultText = <T id={'all_customers'} />, defaultText = <T id={'all_customers'} />,
buttonProps, buttonProps,
onCustomerSelected: onContactSelected, onContactSelect,
...selectProps contactsSelected = [],
...multiSelectProps
}) { }) {
const [selectedContacts, setSelectedContacts] = useState({}); const [localSelected, setLocalSelected] = useState([ ...contactsSelected]);
const isContactSelect = useCallback( // Detarmines the given id is selected.
(id) => typeof selectedContacts[id] !== 'undefined', const isItemSelected = useCallback(
[selectedContacts], (id) => localSelected.some(s => s === id),
[localSelected],
); );
// Contact item renderer.
const contactRenderer = useCallback( const contactRenderer = useCallback(
(contact, { handleClick }) => ( (contact, { handleClick }) => (
<MenuItem <MenuItem
icon={isContactSelect(contact.id) ? 'tick' : 'blank'} icon={isItemSelected(contact.id) ? 'tick' : 'blank'}
text={contact.display_name} text={contact.display_name}
key={contact.id} key={contact.id}
onClick={handleClick} onClick={handleClick}
/> />
), ),
[isContactSelect], [isItemSelected],
); );
const countSelected = useMemo( // Count selected items.
() => Object.values(selectedContacts).length, const countSelected = localSelected.length;
[selectedContacts],
);
const onContactSelect = useCallback( // Handle item selected.
const handleItemSelect = useCallback(
({ id }) => { ({ id }) => {
const selected = { const selected = isItemSelected(id)
...(isContactSelect(id) ? localSelected.filter(s => s !== id)
? { : [...localSelected, id];
...omit(selectedContacts, [id]),
} setLocalSelected([ ...selected ]);
: { safeInvoke(onContactSelect, selected);
...selectedContacts,
[id]: true,
}),
};
setSelectedContacts({ ...selected });
onContactSelected && onContactSelected(selected);
}, },
[setSelectedContacts, selectedContacts, isContactSelect, onContactSelected], [setLocalSelected, localSelected, isItemSelected, onContactSelect],
); );
return ( return (
@@ -62,7 +61,8 @@ export default function ContactsMultiSelect({
itemRenderer={contactRenderer} itemRenderer={contactRenderer}
popoverProps={{ minimal: true }} popoverProps={{ minimal: true }}
filterable={true} filterable={true}
onItemSelect={onContactSelect} onItemSelect={handleItemSelect}
{...multiSelectProps}
> >
<Button <Button
text={ text={

View File

@@ -0,0 +1,41 @@
import React from 'react';
import classNames from 'classnames';
import { Classes, Checkbox, FormGroup, Intent } from '@blueprintjs/core';
const CheckboxEditableCell = ({
row: { index },
column: { id },
cell: { value: initialValue },
payload,
}) => {
const [value, setValue] = React.useState(initialValue);
const onChange = (e) => {
setValue(e.target.value);
};
const onBlur = () => {
payload.updateData(index, id, value);
};
React.useEffect(() => {
setValue(initialValue);
}, [initialValue]);
const error = payload.errors?.[index]?.[id];
return (
<FormGroup
// intent={error ? Intent.DANGER : null}
className={classNames(Classes.FILL)}
>
<Checkbox
value={value}
onChange={onChange}
onBlur={onBlur}
minimal={true}
className="ml2"
/>
</FormGroup>
);
};
export default CheckboxEditableCell;

View File

@@ -6,6 +6,7 @@ import ItemsListCell from './ItemsListCell';
import PercentFieldCell from './PercentFieldCell'; import PercentFieldCell from './PercentFieldCell';
import { DivFieldCell, EmptyDiv } from './DivFieldCell'; import { DivFieldCell, EmptyDiv } from './DivFieldCell';
import NumericInputCell from './NumericInputCell'; import NumericInputCell from './NumericInputCell';
import CheckBoxFieldCell from './CheckBoxFieldCell'
export { export {
AccountsListFieldCell, AccountsListFieldCell,
@@ -16,5 +17,6 @@ export {
PercentFieldCell, PercentFieldCell,
DivFieldCell, DivFieldCell,
EmptyDiv, EmptyDiv,
NumericInputCell NumericInputCell,
CheckBoxFieldCell
}; };

View File

@@ -4,14 +4,26 @@ import { CLASSES } from 'common/classes';
import { DataTable, If } from 'components'; import { DataTable, If } from 'components';
import 'style/components/DataTable/DataTableEditable.scss'; import 'style/components/DataTable/DataTableEditable.scss';
/**
* Editable datatable.
*/
export default function DatatableEditable({ export default function DatatableEditable({
totalRow = false, totalRow = false,
actions, actions,
name,
className, className,
...tableProps ...tableProps
}) { }) {
return ( return (
<div className={classNames(CLASSES.DATATABLE_EDITOR, className)}> <div
className={classNames(
CLASSES.DATATABLE_EDITOR,
{
[`${CLASSES.DATATABLE_EDITOR}--${name}`]: name,
},
className,
)}
>
<DataTable {...tableProps} /> <DataTable {...tableProps} />
<If condition={actions}> <If condition={actions}>

View File

@@ -2,6 +2,7 @@ import React, { useContext } from 'react';
import classNames from 'classnames'; import classNames from 'classnames';
import { If } from 'components'; import { If } from 'components';
import { Skeleton } from 'components'; import { Skeleton } from 'components';
import { useAppIntlContext } from 'components/AppIntlProvider';
import TableContext from './TableContext'; import TableContext from './TableContext';
import { isCellLoading } from './utils'; import { isCellLoading } from './utils';
@@ -26,6 +27,9 @@ export default function TableCell({
const isExpandColumn = expandToggleColumn === index; const isExpandColumn = expandToggleColumn === index;
const { skeletonWidthMax = 100, skeletonWidthMin = 40 } = {}; const { skeletonWidthMax = 100, skeletonWidthMin = 40 } = {};
// Application intl context.
const { isRTL } = useAppIntlContext();
// Detarmines whether the current cell is loading. // Detarmines whether the current cell is loading.
const cellLoading = isCellLoading( const cellLoading = isCellLoading(
cellsLoading, cellsLoading,
@@ -46,8 +50,6 @@ export default function TableCell({
); );
} }
const isRTL = true;
return ( return (
<div <div
{...cell.getCellProps({ {...cell.getCellProps({

View File

@@ -0,0 +1,29 @@
import React from 'react';
import className from 'classname';
/**
* Details menu.
*/
export function DetailsMenu({ children, vertical = false }) {
return (
<div
className={className('details-menu', {
'is-vertical': vertical,
})}
>
{children}
</div>
);
}
/**
* Detail item.
*/
export function DetailItem({ label, children }) {
return (
<div class="detail-item">
<div class="detail-item__label">{label}</div>
<div class="detail-item__content">{children}</div>
</div>
);
}

View File

@@ -13,6 +13,7 @@ import KeyboardShortcutsDialog from 'containers/Dialogs/keyboardShortcutsDialog'
import ContactDuplicateDialog from 'containers/Dialogs/ContactDuplicateDialog'; import ContactDuplicateDialog from 'containers/Dialogs/ContactDuplicateDialog';
import QuickPaymentReceiveFormDialog from 'containers/Dialogs/QuickPaymentReceiveFormDialog'; import QuickPaymentReceiveFormDialog from 'containers/Dialogs/QuickPaymentReceiveFormDialog';
import QuickPaymentMadeFormDialog from 'containers/Dialogs/QuickPaymentMadeFormDialog'; import QuickPaymentMadeFormDialog from 'containers/Dialogs/QuickPaymentMadeFormDialog';
import AllocateLandedCostDialog from 'containers/Dialogs/AllocateLandedCostDialog';
/** /**
* Dialogs container. * Dialogs container.
@@ -32,6 +33,7 @@ export default function DialogsContainer() {
<ContactDuplicateDialog dialogName={'contact-duplicate'} /> <ContactDuplicateDialog dialogName={'contact-duplicate'} />
<QuickPaymentReceiveFormDialog dialogName={'quick-payment-receive'} /> <QuickPaymentReceiveFormDialog dialogName={'quick-payment-receive'} />
<QuickPaymentMadeFormDialog dialogName={'quick-payment-made'} /> <QuickPaymentMadeFormDialog dialogName={'quick-payment-made'} />
<AllocateLandedCostDialog dialogName={'allocate-landed-cost'} />
</div> </div>
); );
} }

View File

@@ -1,9 +1,14 @@
import React from 'react'; import React from 'react';
import { Position, Drawer } from '@blueprintjs/core'; import { Position, Drawer } from '@blueprintjs/core';
import withDrawerActions from 'containers/Drawer/withDrawerActions';
import 'style/components/Drawer.scss';
import withDrawerActions from 'containers/Drawer/withDrawerActions';
import { compose } from 'utils'; import { compose } from 'utils';
/**
* Drawer component.
*/
function DrawerComponent(props) { function DrawerComponent(props) {
const { name, children, onClose, closeDrawer } = props; const { name, children, onClose, closeDrawer } = props;

View File

@@ -6,6 +6,7 @@ import PaymentReceiveDrawer from 'containers/Sales/PaymentReceives/PaymentDetail
import AccountDrawer from 'containers/Drawers/AccountDrawer'; import AccountDrawer from 'containers/Drawers/AccountDrawer';
import ManualJournalDrawer from 'containers/Drawers/ManualJournalDrawer'; import ManualJournalDrawer from 'containers/Drawers/ManualJournalDrawer';
import ExpenseDrawer from 'containers/Drawers/ExpenseDrawer'; import ExpenseDrawer from 'containers/Drawers/ExpenseDrawer';
import BillDrawer from 'containers/Drawers/BillDrawer';
export default function DrawersContainer() { export default function DrawersContainer() {
return ( return (
@@ -17,6 +18,7 @@ export default function DrawersContainer() {
<AccountDrawer name={'account-drawer'} /> <AccountDrawer name={'account-drawer'} />
<ManualJournalDrawer name={'journal-drawer'} /> <ManualJournalDrawer name={'journal-drawer'} />
<ExpenseDrawer name={'expense-drawer'} /> <ExpenseDrawer name={'expense-drawer'} />
<BillDrawer name={'bill-drawer'} />
</div> </div>
); );
} }

View File

@@ -1,6 +1,15 @@
import React from 'react'; import React from 'react';
import className from 'classnames';
import 'style/containers/FinancialStatements/FinancialSheet.scss'; import 'style/containers/FinancialStatements/FinancialSheet.scss';
export default function FinancialStatements({ children }) { export default function FinancialStatements({ name, children }) {
return <div class="financial-statement">{children}</div>; return (
<div
className={className('financial-statement', {
[`financial-statement--${name}`]: name,
})}
>
{children}
</div>
);
} }

View File

@@ -0,0 +1,77 @@
import React, { useCallback, useState } from 'react';
import { MenuItem, Button } from '@blueprintjs/core';
import intl from 'react-intl-universal';
import MultiSelect from 'components/MultiSelect';
import { FormattedMessage as T } from 'components';
import { safeInvoke } from 'utils';
/**
* Items multi-select.
*/
export function ItemsMultiSelect({
items,
defaultText = <T id={'All items'} />,
buttonProps,
selectedItems = [],
onItemSelect,
...multiSelectProps
}) {
const [localSelected, setLocalSelected] = useState([...selectedItems]);
// Detarmines the given id is selected.
const isItemSelected = useCallback(
(id) => localSelected.some((s) => s === id),
[localSelected],
);
// Contact item renderer.
const itemRenderer = useCallback(
(item, { handleClick }) => (
<MenuItem
icon={isItemSelected(item.id) ? 'tick' : 'blank'}
text={item.name}
key={item.id}
onClick={handleClick}
/>
),
[isItemSelected],
);
// Count selected items.
const countSelected = localSelected.length;
// Handle item selected.
const handleItemSelect = useCallback(
({ id }) => {
const selected = isItemSelected(id)
? localSelected.filter((s) => s !== id)
: [...localSelected, id];
setLocalSelected([...selected]);
safeInvoke(onItemSelect, selected);
},
[setLocalSelected, localSelected, isItemSelected, onItemSelect],
);
return (
<MultiSelect
items={items}
noResults={<MenuItem disabled={true} text={<T id={'No items'} />} />}
itemRenderer={itemRenderer}
popoverProps={{ minimal: true }}
filterable={true}
onItemSelect={handleItemSelect}
{...multiSelectProps}
>
<Button
text={
countSelected === 0
? defaultText
: intl.get('Selected items ({count})', { count: countSelected })
}
{...buttonProps}
/>
</MultiSelect>
);
}

View File

@@ -0,0 +1 @@
export * from './ItemsMultiSelect';

View File

@@ -13,18 +13,16 @@
* limitations under the License. * limitations under the License.
*/ */
import classNames from "classnames"; import classNames from 'classnames';
import * as React from "react"; import * as React from 'react';
import { import {
Classes, Classes,
DISPLAYNAME_PREFIX, DISPLAYNAME_PREFIX,
Popover, Popover,
Position, Position,
Utils, Utils,
} from "@blueprintjs/core"; } from '@blueprintjs/core';
import { import { QueryList } from '@blueprintjs/select';
QueryList,
} from '@blueprintjs/select';
// export interface IMultiSelectProps<T> extends IListItemsProps<T> { // export interface IMultiSelectProps<T> extends IListItemsProps<T> {
// /** // /**
@@ -63,114 +61,124 @@ import {
// } // }
export default class MultiSelect extends React.Component { export default class MultiSelect extends React.Component {
static get displayName() { static get displayName() {
return `${DISPLAYNAME_PREFIX}.MultiSelect`; return `${DISPLAYNAME_PREFIX}.MultiSelect`;
} }
static get defaultProps() { static get defaultProps() {
return { return {
fill: false, fill: false,
placeholder: "Search...", placeholder: 'Search...',
};
}; };
}
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { isOpen: (this.props.popoverProps && this.props.popoverProps.isOpen) || false }; this.state = {
this.input = null; isOpen:
this.queryList = null; (this.props.popoverProps && this.props.popoverProps.isOpen) || false,
this.listRef = React.createRef(); };
this.input = null;
this.queryList = null;
this.listRef = React.createRef();
this.refHandlers = { this.refHandlers = {
queryList: (ref) => { queryList: (ref) => {
this.queryList = ref; this.queryList = ref;
}, },
}; };
}
render() {
// omit props specific to this component, spread the rest.
const { openOnKeyDown, popoverProps, tagInputProps, ...restProps } =
this.props;
return (
<QueryList
{...restProps}
onItemSelect={this.handleItemSelect.bind(this)}
onQueryChange={this.handleQueryChange.bind(this)}
ref={this.refHandlers.queryList}
renderer={this.renderQueryList.bind(this)}
/>
);
}
renderQueryList(listProps) {
const { fill, tagInputProps = {}, popoverProps = {} } = this.props;
const { handleKeyDown, handleKeyUp } = listProps;
if (fill) {
popoverProps.fill = true;
tagInputProps.fill = true;
} }
render() { // add our own inputProps.className so that we can reference it in event handlers
// omit props specific to this component, spread the rest. const { inputProps = {} } = tagInputProps;
const { openOnKeyDown, popoverProps, tagInputProps, ...restProps } = this.props; inputProps.className = classNames(
inputProps.className,
Classes.MULTISELECT_TAG_INPUT_INPUT,
);
return ( return (
<QueryList <Popover
{...restProps} autoFocus={false}
onItemSelect={this.handleItemSelect.bind(this)} canEscapeKeyClose={true}
onQueryChange={this.handleQueryChange.bind(this)} enforceFocus={false}
ref={this.refHandlers.queryList} isOpen={this.state.isOpen}
renderer={this.renderQueryList.bind(this)} position={Position.BOTTOM_LEFT}
/> {...popoverProps}
); className={classNames(listProps.className, popoverProps.className)}
} onInteraction={this.handlePopoverInteraction.bind(this)}
popoverClassName={classNames(
renderQueryList(listProps) { Classes.MULTISELECT_POPOVER,
const { fill, tagInputProps = {}, popoverProps = {} } = this.props; popoverProps.popoverClassName,
const { handleKeyDown, handleKeyUp } = listProps; )}
onOpened={this.handlePopoverOpened.bind(this)}
if (fill) { >
popoverProps.fill = true; <div
tagInputProps.fill = true; onKeyDown={
} this.state.isOpen ? handleKeyDown : this.handleTargetKeyDown
}
// add our own inputProps.className so that we can reference it in event handlers onKeyUp={this.state.isOpen ? handleKeyUp : undefined}
const { inputProps = {} } = tagInputProps;
inputProps.className = classNames(inputProps.className, Classes.MULTISELECT_TAG_INPUT_INPUT);
return (
<Popover
autoFocus={false}
canEscapeKeyClose={true}
enforceFocus={false}
isOpen={this.state.isOpen}
position={Position.BOTTOM_LEFT}
{...popoverProps}
className={classNames(listProps.className, popoverProps.className)}
onInteraction={this.handlePopoverInteraction.bind(this)}
popoverClassName={classNames(Classes.MULTISELECT_POPOVER, popoverProps.popoverClassName)}
onOpened={this.handlePopoverOpened.bind(this)}
> >
<div {this.props.children}
onKeyDown={this.state.isOpen ? handleKeyDown : this.handleTargetKeyDown} </div>
onKeyUp={this.state.isOpen ? handleKeyUp : undefined} <div onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} ref={this.listRef}>
> {listProps.itemList}
{this.props.children} </div>
</div> </Popover>
<div onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} ref={this.listRef}> );
{listProps.itemList} }
</div>
</Popover>
);
};
handleItemSelect(item, evt) { handleItemSelect(item, evt) {
if (this.input != null) { if (this.input != null) {
this.input.focus(); this.input.focus();
}
Utils.safeInvoke(this.props.onItemSelect, item, evt);
};
handleQueryChange(query, evt) {
this.setState({ isOpen: query.length > 0 || !this.props.openOnKeyDown });
Utils.safeInvoke(this.props.onQueryChange, query, evt);
};
handlePopoverInteraction = (isOpen, e) => {
if (e && this.listRef.current && this.listRef.current.contains(e.target)) {
this.setState({ isOpen: true })
} else {
this.setState({ isOpen });
}
Utils.safeInvokeMember(this.props.popoverProps, "onInteraction", isOpen);
} }
Utils.safeInvoke(this.props.onItemSelect, item, evt);
}
handleQueryChange(query, evt) {
this.setState({ isOpen: query.length > 0 || !this.props.openOnKeyDown });
Utils.safeInvoke(this.props.onQueryChange, query, evt);
}
handlePopoverOpened(node) { handlePopoverInteraction = (isOpen, e) => {
if (this.queryList != null) { if (e && this.listRef.current && this.listRef.current.contains(e.target)) {
// scroll active item into view after popover transition completes and all dimensions are stable. this.setState({ isOpen: true });
this.queryList.scrollActiveItemIntoView(); } else {
} this.setState({ isOpen });
Utils.safeInvokeMember(this.props.popoverProps, "onOpened", node); }
}; Utils.safeInvokeMember(this.props.popoverProps, 'onInteraction', isOpen);
};
handlePopoverOpened(node) {
if (this.queryList != null) {
// scroll active item into view after popover transition completes and all dimensions are stable.
this.queryList.scrollActiveItemIntoView();
}
Utils.safeInvokeMember(this.props.popoverProps, 'onOpened', node);
}
} }

View File

@@ -56,6 +56,10 @@ import DrawerHeaderContent from './Drawer/DrawerHeaderContent';
import Postbox from './Postbox'; import Postbox from './Postbox';
import AccountsSuggestField from './AccountsSuggestField'; import AccountsSuggestField from './AccountsSuggestField';
import MaterialProgressBar from './MaterialProgressBar'; import MaterialProgressBar from './MaterialProgressBar';
import { MoneyFieldCell } from './DataTableCells';
import Card from './Card';
import { ItemsMultiSelect } from './Items';
const Hint = FieldHint; const Hint = FieldHint;
@@ -123,4 +127,7 @@ export {
Postbox, Postbox,
AccountsSuggestField, AccountsSuggestField,
MaterialProgressBar, MaterialProgressBar,
MoneyFieldCell,
ItemsMultiSelect,
Card
}; };

View File

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

View File

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

View File

@@ -1,13 +1,13 @@
import React from 'react'; import React from 'react';
import { Intent } from '@blueprintjs/core'; 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 moment from 'moment';
import { import {
transactionNumber, transactionNumber,
updateTableRow, updateTableRow,
repeatValue, repeatValue,
transformToForm, transformToForm,
defaultFastFieldShouldUpdate,
} from 'utils'; } from 'utils';
import { AppToaster } from 'components'; import { AppToaster } from 'components';
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
@@ -123,17 +123,17 @@ export const transformErrors = (resErrors, { setErrors, errors }) => {
setEntriesErrors(error.indexes, 'contact_id', 'error'); setEntriesErrors(error.indexes, 'contact_id', 'error');
} }
if ((error = getError(ERROR.ENTRIES_SHOULD_ASSIGN_WITH_CONTACT))) { 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( toastMessages.push(
intl.get('receivable_accounts_should_assign_with_customers'), 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( toastMessages.push(
intl.get('payable_accounts_should_assign_with_vendors'), 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'); setEntriesErrors(indexes, 'contact_id', 'error');
} }
if ((error = getError(ERROR.JOURNAL_NUMBER_ALREADY_EXISTS))) { if ((error = getError(ERROR.JOURNAL_NUMBER_ALREADY_EXISTS))) {
@@ -163,3 +163,24 @@ export const useObserveJournalNoSettings = (prefix, nextNumber) => {
setFieldValue('journal_number', journalNo); setFieldValue('journal_number', journalNo);
}, [setFieldValue, prefix, nextNumber]); }, [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, isOpen,
payload: { expenseId }, payload: { expenseId },
}) { }) {
const { mutateAsync: deleteExpenseMutate, isLoading } = useDeleteExpense();
const {
mutateAsync: deleteExpenseMutate,
isLoading,
} = useDeleteExpense();
// Handle cancel expense journal. // Handle cancel expense journal.
const handleCancelExpenseDelete = () => { const handleCancelExpenseDelete = () => {
@@ -34,17 +30,34 @@ function ExpenseDeleteAlert({
// Handle confirm delete expense. // Handle confirm delete expense.
const handleConfirmExpenseDelete = () => { const handleConfirmExpenseDelete = () => {
deleteExpenseMutate(expenseId).then(() => { deleteExpenseMutate(expenseId)
AppToaster.show({ .then(() => {
message: intl.get( AppToaster.show({
'the_expense_has_been_deleted_successfully', message: intl.get('the_expense_has_been_deleted_successfully', {
{ number: expenseId }, number: expenseId,
), }),
intent: Intent.SUCCESS, intent: Intent.SUCCESS,
}); });
}).finally(() => { closeAlert('expense-delete');
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 ( return (

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

View File

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

View File

@@ -5,8 +5,6 @@ import AccountDrawerHeader from './AccountDrawerHeader';
import AccountDrawerTable from './AccountDrawerTable'; import AccountDrawerTable from './AccountDrawerTable';
import { useAccountDrawerContext } from './AccountDrawerProvider'; import { useAccountDrawerContext } from './AccountDrawerProvider';
import 'style/components/Drawer/AccountDrawer.scss';
/** /**
* Account view details. * 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 React from 'react';
import 'style/components/Drawers/ViewDetails.scss';
import { ExpenseDrawerProvider } from './ExpenseDrawerProvider'; import { ExpenseDrawerProvider } from './ExpenseDrawerProvider';
import ExpenseDrawerDetails from './ExpenseDrawerDetails'; import ExpenseDrawerDetails from './ExpenseDrawerDetails';

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { FormattedMessage as T } from 'components'; import { FormattedMessage as T } from 'components';
import intl from 'react-intl-universal'; 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 { Hint, Icon } from 'components';
import { formattedAmount, safeSumBy } from 'utils'; import { formattedAmount, safeSumBy } from 'utils';
import { import {
@@ -10,6 +10,7 @@ import {
ItemsListCell, ItemsListCell,
PercentFieldCell, PercentFieldCell,
NumericInputCell, NumericInputCell,
CheckBoxFieldCell,
} from 'components/DataTableCells'; } from 'components/DataTableCells';
/** /**
@@ -28,7 +29,11 @@ export function ItemHeaderCell() {
* Item column footer cell. * Item column footer cell.
*/ */
export function ItemFooterCell() { 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>; 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. * Retrieve editable items entries columns.
*/ */
export function useEditableItemsEntriesColumns() { export function useEditableItemsEntriesColumns({ landedCost }) {
return React.useMemo( return React.useMemo(
() => [ () => [
{ {
@@ -155,6 +174,19 @@ export function useEditableItemsEntriesColumns() {
width: 100, width: 100,
className: 'total', className: 'total',
}, },
...(landedCost
? [
{
Header: LandedCostHeaderCell,
accessor: 'landed_cost',
Cell: CheckBoxFieldCell,
width: 100,
disableSortBy: true,
disableResizing: true,
className: 'landed-cost',
},
]
: []),
{ {
Header: '', Header: '',
accessor: 'action', accessor: 'action',

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,5 @@
import React from 'react'; 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 { FormattedMessage as T } from 'components';
import { Icon, Hint } from 'components'; import { Icon, Hint } from 'components';
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
@@ -7,6 +7,7 @@ import {
InputGroupCell, InputGroupCell,
MoneyFieldCell, MoneyFieldCell,
AccountsListFieldCell, AccountsListFieldCell,
CheckBoxFieldCell,
} from 'components/DataTableCells'; } from 'components/DataTableCells';
import { formattedAmount, safeSumBy } from 'utils'; 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. * Amount footer cell.
*/ */
@@ -74,7 +91,7 @@ function ExpenseAccountFooterCell() {
/** /**
* Retrieve expense form table entries columns. * Retrieve expense form table entries columns.
*/ */
export function useExpenseFormTableColumns() { export function useExpenseFormTableColumns({ landedCost }) {
return React.useMemo( return React.useMemo(
() => [ () => [
{ {
@@ -114,6 +131,19 @@ export function useExpenseFormTableColumns() {
className: 'description', className: 'description',
width: 100, width: 100,
}, },
...(landedCost
? [
{
Header: LandedCostHeaderCell,
accessor: 'landed_cost',
Cell: CheckBoxFieldCell,
disableSortBy: true,
disableResizing: true,
width: 100,
className: 'landed-cost',
},
]
: []),
{ {
Header: '', Header: '',
accessor: 'action', accessor: 'action',

View File

@@ -1,7 +1,11 @@
import { AppToaster } from 'components'; import { AppToaster } from 'components';
import moment from 'moment'; import moment from 'moment';
import intl from 'react-intl-universal'; import intl from 'react-intl-universal';
import { transformToForm, repeatValue } from 'utils'; import {
defaultFastFieldShouldUpdate,
transformToForm,
repeatValue,
} from 'utils';
const ERROR = { const ERROR = {
EXPENSE_ALREADY_PUBLISHED: 'EXPENSE.ALREADY.PUBLISHED', EXPENSE_ALREADY_PUBLISHED: 'EXPENSE.ALREADY.PUBLISHED',
@@ -27,6 +31,7 @@ export const defaultExpenseEntry = {
amount: '', amount: '',
expense_account_id: '', expense_account_id: '',
description: '', description: '',
landed_cost: false,
}; };
export const defaultExpense = { 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'), asDate: moment().endOf('day').format('YYYY-MM-DD'),
agingBeforeDays: 30, agingBeforeDays: 30,
agingPeriods: 3, agingPeriods: 3,
vendorsIds: [],
}); });
// Handle filter submit. // Handle filter submit.
@@ -63,7 +64,7 @@ function APAgingSummary({
<APAgingSummarySheetLoadingBar /> <APAgingSummarySheetLoadingBar />
<DashboardPageContent> <DashboardPageContent>
<FinancialStatement> <FinancialStatement name={'AP-aging-summary'}>
<APAgingSummaryHeader <APAgingSummaryHeader
pageFilter={filter} pageFilter={filter}
onSubmitFilter={handleFilterSubmit} onSubmitFilter={handleFilterSubmit}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,14 +1,9 @@
import React from 'react'; import React from 'react';
import { FastField } from 'formik'; import { FastField, Field } from 'formik';
import { DateInput } from '@blueprintjs/datetime'; import { DateInput } from '@blueprintjs/datetime';
import { import { Classes, FormGroup, Position, Checkbox } from '@blueprintjs/core';
FormGroup, import { ContactsMultiSelect, FormattedMessage as T } from 'components';
Position, import classNames from 'classnames';
Classes,
Checkbox,
} from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { Row, Col, FieldHint } from 'components'; import { Row, Col, FieldHint } from 'components';
import { import {
momentFormatter, momentFormatter,
@@ -16,11 +11,14 @@ import {
inputIntent, inputIntent,
handleDateChange, handleDateChange,
} from 'utils'; } from 'utils';
import { useCustomersBalanceSummaryContext } from './CustomersBalanceSummaryProvider';
/** /**
* Customers balance header - general panel. * Customers balance header - general panel.
*/ */
export default function CustomersBalanceSummaryGeneralPanel() { export default function CustomersBalanceSummaryGeneralPanel() {
const { customers } = useCustomersBalanceSummaryContext();
return ( return (
<div> <div>
<Row> <Row>
@@ -48,6 +46,7 @@ export default function CustomersBalanceSummaryGeneralPanel() {
</FastField> </FastField>
</Col> </Col>
</Row> </Row>
<Row> <Row>
<Col xs={5}> <Col xs={5}>
<FastField name={'percentage'} type={'checkbox'}> <FastField name={'percentage'} type={'checkbox'}>
@@ -57,7 +56,7 @@ export default function CustomersBalanceSummaryGeneralPanel() {
inline={true} inline={true}
name={'percentage'} name={'percentage'}
small={true} small={true}
label={<T id={'percentage_of_column'}/>} label={<T id={'percentage_of_column'} />}
{...field} {...field}
/> />
</FormGroup> </FormGroup>
@@ -65,6 +64,31 @@ export default function CustomersBalanceSummaryGeneralPanel() {
</FastField> </FastField>
</Col> </Col>
</Row> </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> </div>
); );
} }

View File

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

View File

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

View File

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

View File

@@ -1,13 +1,45 @@
import React from 'react'; 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 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. * Customers transactions header - General panel.
*/ */
export default function CustomersTransactionsHeaderGeneralPanel() { export default function CustomersTransactionsHeaderGeneralPanel() {
const { customers } = useCustomersTransactionsContext();
return ( return (
<div> <div>
<FinancialStatementDateRange /> <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> </div>
); );
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,13 +1,46 @@
import React from 'react'; 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 FinancialStatementDateRange from 'containers/FinancialStatements/FinancialStatementDateRange';
import { useInventoryItemDetailsContext } from './InventoryItemDetailsProvider';
/** /**
* Inventory item details header - General panel. * Inventory item details header - General panel.
*/ */
export default function InventoryItemDetailsHeaderGeneralPanel() { export default function InventoryItemDetailsHeaderGeneralPanel() {
const { items } = useInventoryItemDetailsContext();
return ( return (
<div> <div>
<FinancialStatementDateRange /> <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> </div>
); );
} }

View File

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

View File

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

View File

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

View File

@@ -1,20 +1,24 @@
import React from 'react'; import React from 'react';
import { FastField } from 'formik'; import { FastField, Field } from 'formik';
import { DateInput } from '@blueprintjs/datetime'; 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 { FormattedMessage as T } from 'components';
import { Row, Col, FieldHint } from 'components'; import { ItemsMultiSelect, Row, Col, FieldHint } from 'components';
import { import {
momentFormatter, momentFormatter,
tansformDateValue, tansformDateValue,
inputIntent, inputIntent,
handleDateChange, handleDateChange,
} from 'utils'; } from 'utils';
import { useInventoryValuationContext } from './InventoryValuationProvider';
/** /**
* inventory valuation - Drawer Header - General panel. * Inventory valuation - Drawer Header - General panel.
*/ */
export default function InventoryValuationHeaderGeneralPanel() { export default function InventoryValuationHeaderGeneralPanel() {
const { items } = useInventoryValuationContext();
return ( return (
<div> <div>
<Row> <Row>
@@ -42,6 +46,31 @@ export default function InventoryValuationHeaderGeneralPanel() {
</FastField> </FastField>
</Col> </Col>
</Row> </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> </div>
); );
} }

View File

@@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import FinancialReportPage from '../FinancialReportPage'; import FinancialReportPage from '../FinancialReportPage';
import { useInventoryValuation } from 'hooks/query'; import { useInventoryValuation, useItems } from 'hooks/query';
import { transformFilterFormToQuery } from '../common'; import { transformFilterFormToQuery } from '../common';
const InventoryValuationContext = React.createContext(); 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 = { const provider = {
inventoryValuation, inventoryValuation,
isLoading, isLoading,
isFetching, isFetching,
refetchSheet: refetch, refetchSheet: refetch,
items,
isItemsFetching,
isItemsLoading
}; };
return ( return (

View File

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

View File

@@ -1,13 +1,47 @@
import React from 'react'; 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 FinancialStatementDateRange from 'containers/FinancialStatements/FinancialStatementDateRange';
import { ItemsMultiSelect } from 'components';
import { usePurchaseByItemsContext } from './PurchasesByItemsProvider';
/** /**
* Purchases by items - Drawer header - General panel. * Purchases by items - Drawer header - General panel.
*/ */
export default function PurchasesByItemsGeneralPanel() { export default function PurchasesByItemsGeneralPanel() {
const { items } = usePurchaseByItemsContext();
return ( return (
<div> <div>
<FinancialStatementDateRange /> <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> </div>
); );
} }

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
import React, { createContext, useContext } from 'react'; import React, { createContext, useContext } from 'react';
import FinancialReportPage from '../FinancialReportPage'; import FinancialReportPage from '../FinancialReportPage';
import { useSalesByItems } from 'hooks/query'; import { useSalesByItems, useItems } from 'hooks/query';
import { transformFilterFormToQuery } from '../common'; import { transformFilterFormToQuery } from '../common';
const SalesByItemsContext = createContext(); 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 = { const provider = {
salesByItems, salesByItems,
isFetching, isFetching,
isLoading, isLoading,
items,
isItemsLoading,
isItemsFetching,
refetchSheet: refetch, refetchSheet: refetch,
}; };
return ( return (

View File

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

View File

@@ -1,13 +1,45 @@
import React from 'react'; 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 FinancialStatementDateRange from 'containers/FinancialStatements/FinancialStatementDateRange';
import { useSalesByItemsContext } from './SalesByItemProvider';
/** /**
* sells by items - Drawer header - General panel. * sells by items - Drawer header - General panel.
*/ */
export default function SalesByItemsHeaderGeneralPanel() { export default function SalesByItemsHeaderGeneralPanel() {
const { items } = useSalesByItemsContext();
return ( return (
<div> <div>
<FinancialStatementDateRange /> <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> </div>
); );
} }

View File

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

View File

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

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