Compare commits

..

1 Commits

Author SHA1 Message Date
a.bouhuolia
bceb76ef1d feat: WIP Item entries select warehouse. 2022-02-20 15:23:34 +02:00
491 changed files with 2895 additions and 10638 deletions

View File

@@ -2,73 +2,6 @@
All notable changes to Bigcapital server-side will be in this file.
## [1.7.2-rc.2] - 04-04-2022
### Fixed
- Add the missing Arabic localization.
- Subscription plans modifications.
## [1.7.1-rc.2] - 30-03-2022
## Added
- `BIG-141` Add inactive status to item drawer details.
- `BIG-278` Add created at date on expense details.
- `BIG-350` Add empty status content of warehouse transfers service.
- `BIG-344` Add branch details to manual journal and expense details.
## Fixed
- `BIG-221` Remove Non-inventory radio choice on item form.
- `BIG-236` Validate estimate expiration date should be equal or bigger than estimate date.
- `BIG-237` Validate invoice due date should be equal or bigger than invoice date.
- `BIG-238` Validate bill due date should be equal or bigger than bill date.
- `BIG-280` Optimize style of multi-select accounts menu.
- `BIG-284` Cashflow statement loading bar.
- `BIG-296` Creating a new child account from accounts list.
- `BIG-301` Navigation bar divider on actions bar hide with permissions control.
- `BIG-304` Adding cash or bank account from cash flow service.
- `BIG-351` Invalid date in the inventory adjustment detail.
- `BIG-352` Fix terms and notes fields on footer of all services.
- `BIG-354` Validate the warehouse transfer quantity should be above zero.
## [1.7.0-rc.1] - 24-03-2022
## Added
- Multiply currencies with foreign currencies.
- Multiply warehouses to track inventory items.
- Multiply branches to track organization transactions.
- Transfer orders between warehouses.
- Integrate financial reports with multiply branches.
- Integrate inventory reports with multiply warehouses.
## Changes
- Optimize style of sale invoice form.
- Optimize style of sale receipt form.
- Optimize style of credit note form.
- Optimize style of payment receive form.
- Optimize style of bill form.
- Optimize style of payment made form.
- Optimize style of manual journal form.
- Optimize style of expense form.
## [1.6.3] - 21-02-2022
### Fixed
- `BIG-337` Display billing page once the organization subscription is inactive.
## [1.6.2] - 19-02-2022
### Fixed
- fix syled components dependency with imported as default components.
## [1.6.0] - 18-02-2022
### Added
- Balance sheet comparison of previous period (PP).
- Balance sheet comparison of previous year (PY).
- Balance sheet percentage analysis columns and rows basis.
- Profit & loss sheet comparison of preivous period (PP).
- Profit & loss sheet comparison of previous year (PY).
- Profit & loss sheet percentage analysis columns, rows, income and expenses basis.
## [1.5.8] - 13-01-2022
### Added

View File

@@ -1,10 +1,10 @@
{
"name": "bigcapital-client",
"version": "1.7.1",
"version": "1.5.8",
"private": true,
"dependencies": {
"@babel/core": "7.8.4",
"@blueprintjs-formik/core": "^0.2.1",
"@blueprintjs-formik/core": "^0.1.5",
"@blueprintjs-formik/select": "^0.1.4",
"@blueprintjs/core": "^3.50.2",
"@blueprintjs/datetime": "^3.23.12",

View File

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@@ -221,5 +221,3 @@ export const ACCOUNT_TYPES = [
incomeSheet: true,
},
];
export const FOREIGN_CURRENCY_ACCOUNTS = ['cash', 'bank'];

View File

@@ -1,7 +0,0 @@
export const CellType = {
Text: 'text',
Field: 'field',
Button: 'button'
}

View File

@@ -2,6 +2,5 @@
export const Features = {
Warehouses: 'warehouses',
Branches: 'branches',
ManualJournal: 'manualJournal',
Branches: 'branches'
}

View File

@@ -1,6 +1,4 @@
export * from './accountTypes';
export * from './TableStyle';
export * from './features';
export * from './cellTypes';
export const Align = { Left: 'left', Right: 'right', Center: 'center' };

View File

@@ -1,73 +0,0 @@
import React from 'react';
import styled from 'styled-components';
import { MenuItem } from '@blueprintjs/core';
import { FMultiSelect } from '../Forms';
import classNames from 'classnames';
import { Classes } from '@blueprintjs/popover2';
/**
*
* @param {*} query
* @param {*} account
* @param {*} _index
* @param {*} exactMatch
* @returns
*/
const accountItemPredicate = (query, account, _index, exactMatch) => {
const normalizedTitle = account.name.toLowerCase();
const normalizedQuery = query.toLowerCase();
if (exactMatch) {
return normalizedTitle === normalizedQuery;
} else {
return `${account.code}. ${normalizedTitle}`.indexOf(normalizedQuery) >= 0;
}
};
/**
*
* @param {*} account
* @param {*} param1
* @returns
*/
const accountItemRenderer = (
account,
{ handleClick, modifiers, query },
{ isSelected },
) => {
return (
<MenuItem
icon={isSelected ? 'tick' : 'blank'}
text={account.name}
label={account.code}
key={account.id}
onClick={handleClick}
/>
);
};
const accountSelectProps = {
itemPredicate: accountItemPredicate,
itemRenderer: accountItemRenderer,
valueAccessor: (item) => item.id,
labelAccessor: (item) => item.code,
tagRenderer: (item) => item.name,
};
/**
* branches mulit select.
* @param {*} param0
* @returns {JSX.Element}
*/
export function AccountMultiSelect({ accounts, ...rest }) {
return (
<FMultiSelect
items={accounts}
popoverProps={{
minimal: true,
}}
{...accountSelectProps}
{...rest}
/>
);
}

View File

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

View File

@@ -1,124 +0,0 @@
import React from 'react';
import intl from 'react-intl-universal';
import { MenuItem } from '@blueprintjs/core';
import { Suggest } from '@blueprintjs/select';
import { FormattedMessage as T } from 'components';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
/**
* branch suggest field.
* @returns
*/
export default function BranchSuggestField({
branches,
initialBranchId,
selectedBranchId,
defaultSelectText = intl.get('select_branch'),
popoverFill = false,
onBranchSelected,
...suggestProps
}) {
const initialBranch = React.useMemo(
() => branches.find((b) => b.id === initialBranchId),
[initialBranchId, branches],
);
const [selectedBranch, setSelectedBranch] = React.useState(
initialBranch || null,
);
React.useEffect(() => {
if (typeof selectedBranchId !== 'undefined') {
const branch = selectedBranchId
? branches.find((a) => a.id === selectedBranchId)
: null;
setSelectedBranch(branch);
}
}, [selectedBranchId, branches, setSelectedBranch]);
/**
*
* @param {*} branch
* @returns
*/
const branchItemRenderer = (branch, { handleClick, modifiers, query }) => {
return (
<MenuItem
// active={modifiers.active}
disabled={modifiers.disabled}
label={branch.code}
key={branch.id}
onClick={handleClick}
text={branch.name}
/>
);
};
/**
*
* @param {*} query
* @param {*} branch
* @param {*} _index
* @param {*} exactMatch
* @returns
*/
const branchItemPredicate = (query, branch, _index, exactMatch) => {
const normalizedTitle = branch.name.toLowerCase();
const normalizedQuery = query.toLowerCase();
if (exactMatch) {
return normalizedTitle === normalizedQuery;
} else {
return `${branch.code}. ${normalizedTitle}`.indexOf(normalizedQuery) >= 0;
}
};
/**
*
* @param {*} branch
* @returns
*/
const brnachItemSelect = React.useCallback(
(branch) => {
if (branch.id) {
setSelectedBranch({ ...branch });
onBranchSelected && onBranchSelected(branch);
}
},
[setSelectedBranch, onBranchSelected],
);
/**
*
* @param {*} inputVaue
* @returns
*/
const branchInputValueRenderer = (inputValue) => {
if (inputValue) {
return inputValue.name.toString();
}
return '';
};
return (
<Suggest
items={branches}
noResults={<MenuItem disabled={true} text={<T id={'no_accounts'} />} />}
itemRenderer={branchItemRenderer}
itemPredicate={branchItemPredicate}
onItemSelect={brnachItemSelect}
selectedItem={selectedBranch}
inputProps={{ placeholder: defaultSelectText }}
resetOnClose={true}
fill={true}
popoverProps={{ minimal: true, boundary: 'window' }}
inputValueRenderer={branchInputValueRenderer}
className={classNames(CLASSES.FORM_GROUP_LIST_SELECT, {
[CLASSES.SELECT_LIST_FILL_POPOVER]: popoverFill,
})}
{...suggestProps}
/>
);
}

View File

@@ -38,8 +38,8 @@ const branchItemRenderer = (
active={modifiers.active}
disabled={modifiers.disabled}
icon={isSelected ? 'tick' : 'blank'}
text={branch.name}
label={branch.code}
text={branch.name.toString()}
label={branch.code.toString()}
key={branch.id}
onClick={handleClick}
/>
@@ -50,14 +50,14 @@ const branchSelectProps = {
itemPredicate: branchItemPredicate,
itemRenderer: branchItemRenderer,
valueAccessor: (item) => item.id,
labelAccessor: (item) => item.code,
labelAccessor: (item) => item.label,
tagRenderer: (item) => item.name,
};
/**
* branches mulit select.
* @param {*} param0
* @returns {JSX.Element}
* @returns
*/
export function BranchMultiSelect({ branches, ...rest }) {
return (

View File

@@ -35,7 +35,7 @@ const branchItemRenderer = (branch, { handleClick, modifiers, query }) => {
<MenuItem
active={modifiers.active}
disabled={modifiers.disabled}
label={branch.code}
label={branch.name.toString()}
key={branch.id}
onClick={handleClick}
text={text}

View File

@@ -1 +1,3 @@
export * from './ButtonLink';

View File

@@ -1,10 +0,0 @@
import React from 'react';
import { CurrencyTag } from 'components';
/**
* base currecncy.
* @returns
*/
export function BaseCurrency({ currency }) {
return <CurrencyTag>{currency}</CurrencyTag>;
}

View File

@@ -1,2 +1 @@
export * from './CurrencySelect';
export * from './BaseCurrency';
export * from './CurrencySelect'

View File

@@ -1,29 +1,23 @@
import React from 'react';
import * as R from 'ramda';
import { ButtonLink } from '../Button';
import { ButtonLink } from 'components';
import withDrawerActions from 'containers/Drawer/withDrawerActions';
function CustomerDrawerLinkComponent({
// #ownProps
children,
customerId,
className,
// #withDrawerActions
openDrawer,
}) {
// Handle view customer drawer.
const handleCustomerDrawer = (event) => {
const handleCustomerDrawer = () => {
openDrawer('customer-details-drawer', { customerId });
event.preventDefault();
};
return (
<ButtonLink className={className} onClick={handleCustomerDrawer}>
{children}
</ButtonLink>
);
return <ButtonLink onClick={handleCustomerDrawer}>{children}</ButtonLink>;
}
export const CustomerDrawerLink = R.compose(withDrawerActions)(

View File

@@ -1,8 +1,7 @@
import React from 'react';
import { Ability } from '@casl/ability';
import { createContextualCan } from '@casl/react';
import { useDashboardMetaBoot } from './DashboardBoot';
import { useDashboardMeta } from '../../hooks/query';
export const AbilityContext = React.createContext();
export const Can = createContextualCan(AbilityContext.Consumer);
@@ -12,8 +11,8 @@ export const Can = createContextualCan(AbilityContext.Consumer);
*/
export function DashboardAbilityProvider({ children }) {
const {
meta: { abilities },
} = useDashboardMetaBoot();
data: { abilities },
} = useDashboardMeta();
// Ability instance.
const ability = new Ability(abilities);

View File

@@ -6,26 +6,18 @@ import {
} from '../../hooks/query';
import { useSplashLoading } from '../../hooks/state';
import { useWatch, useWatchImmediate, useWhen } from '../../hooks';
import { useSubscription } from '../../hooks/state';
import { setCookie, getCookie } from '../../utils';
/**
* Dashboard meta async booting.
* - Fetches the dashboard meta only if the organization subscribe is active.
* - Once the dashboard meta query is loading display dashboard splash screen.
*/
export function useDashboardMetaBoot() {
const { isSubscriptionActive } = useSubscription();
const {
data: dashboardMeta,
isLoading: isDashboardMetaLoading,
isSuccess: isDashboardMetaSuccess,
} = useDashboardMeta({
keepPreviousData: true,
// Avoid run the query if the organization subscription is not active.
enabled: isSubscriptionActive,
});
const [startLoading, stopLoading] = useSplashLoading();
@@ -38,12 +30,20 @@ export function useDashboardMetaBoot() {
}, isDashboardMetaSuccess);
return {
meta: dashboardMeta,
isLoading: isDashboardMetaLoading,
isSuccess: isDashboardMetaSuccess
};
}
/**
* Dashboard async booting.
* @returns {{ isLoading: boolean }}
*/
export function useDashboardBoot() {
const { isLoading } = useDashboardMetaBoot();
return { isLoading };
}
/**
* Application async booting.
*/

View File

@@ -1,12 +1,12 @@
import React from 'react';
import { DashboardAbilityProvider } from '../../components';
import { useDashboardMetaBoot } from './DashboardBoot';
import { useDashboardBoot } from './DashboardBoot';
/**
* Dashboard provider.
*/
export default function DashboardProvider({ children }) {
const { isLoading } = useDashboardMetaBoot();
const { isLoading } = useDashboardBoot();
// Avoid display any dashboard component before complete booting.
if (isLoading) {

View File

@@ -1,12 +1,13 @@
import React, { useRef, useCallback, useMemo } from 'react';
import classNames from 'classnames';
import { FormGroup, Classes, Intent } from '@blueprintjs/core';
import { useCellAutoFocus } from 'hooks';
import intl from 'react-intl-universal';
import { CellType } from 'common';
import { useCellAutoFocus } from 'hooks';
import AccountsSuggestField from 'components/AccountsSuggestField';
// import AccountsSelectList from 'components/AccountsSelectList';
import { FormGroup, Classes, Intent } from '@blueprintjs/core';
/**
* Account cell renderer.
*/
@@ -73,4 +74,3 @@ export default function AccountCellRenderer({
</FormGroup>
);
}
AccountCellRenderer.cellType = CellType.Field;

View File

@@ -1,44 +0,0 @@
import React from 'react';
import { FormGroup, Intent, Classes } from '@blueprintjs/core';
import classNames from 'classnames';
import { CellType } from 'common';
import BranchSuggestField from '../BranchSuggestField';
/**
* Branches list field cell.
* @returns
*/
export default function BranchesListFieldCell({
column: { id },
row: { index, original },
payload: { branches, updateData, errors },
}) {
const handleBranchSelected = React.useCallback(
(branch) => {
updateData(index, 'branch_id', branch.id);
},
[updateData, index],
);
const error = errors?.[index]?.[id];
return (
<FormGroup
intent={error ? Intent.DANGER : null}
className={classNames(
'form-group--select-list',
'form-group--contacts-list',
Classes.FILL,
)}
>
<BranchSuggestField
branches={branches}
onBranchSelected={handleBranchSelected}
selectedBranchId={original?.branch_id}
/>
</FormGroup>
);
}
BranchesListFieldCell.cellType = CellType.Field;

View File

@@ -2,7 +2,6 @@ import React from 'react';
import classNames from 'classnames';
import { get } from 'lodash';
import { Classes, Checkbox, FormGroup, Intent } from '@blueprintjs/core';
import { CellType } from 'common';
const CheckboxEditableCell = ({
row: { index, original },
@@ -46,6 +45,4 @@ const CheckboxEditableCell = ({
);
};
CheckboxEditableCell.cellType = CellType.Field;
export default CheckboxEditableCell;

View File

@@ -1,9 +1,9 @@
import React, { useCallback } from 'react';
import { FormGroup, Intent, Classes } from '@blueprintjs/core';
import classNames from 'classnames';
import { CellType } from 'common';
import { ContactSelecetList } from 'components';
import ContactsSuggestField from 'components/ContactsSuggestField';
export default function ContactsListCellRenderer({
column: { id },
row: { index, original },
@@ -37,5 +37,3 @@ export default function ContactsListCellRenderer({
</FormGroup>
);
}
ContactsListCellRenderer.cellType = CellType.Field;

View File

@@ -1,7 +1,6 @@
import React, { useState, useEffect } from 'react';
import classNames from 'classnames';
import { Classes, InputGroup, FormGroup, Intent } from '@blueprintjs/core';
import { CellType } from 'common';
const InputEditableCell = ({
row: { index },
@@ -38,6 +37,4 @@ const InputEditableCell = ({
);
};
InputEditableCell.cellType = CellType.Field;
export default InputEditableCell;

View File

@@ -3,7 +3,6 @@ import classNames from 'classnames';
import { FormGroup, Classes, Intent } from '@blueprintjs/core';
import intl from 'react-intl-universal';
import { CellType } from 'common';
import ItemsSuggestField from 'components/ItemsSuggestField';
import { useCellAutoFocus } from 'hooks';
@@ -55,5 +54,3 @@ export default function ItemsListCell({
</FormGroup>
);
}
ItemsListCell.cellType = CellType.Field;

View File

@@ -1,9 +1,7 @@
import React, { useCallback, useState, useEffect } from 'react';
import { FormGroup, Intent } from '@blueprintjs/core';
import { MoneyInputGroup } from 'components';
import { CLASSES } from 'common/classes';
import { CellType } from 'common';
// Input form cell renderer.
const MoneyFieldCellRenderer = ({
@@ -50,6 +48,4 @@ const MoneyFieldCellRenderer = ({
);
};
MoneyFieldCellRenderer.cellType = CellType.Field;
export default MoneyFieldCellRenderer;

View File

@@ -1,8 +1,6 @@
import React, { useState, useEffect } from 'react';
import { FormGroup, NumericInput, Intent } from '@blueprintjs/core';
import classNames from 'classnames';
import { CellType } from 'common';
import { CLASSES } from 'common/classes';
/**
@@ -38,10 +36,8 @@ export default function NumericInputCell({
onValueChange={handleValueChange}
onBlur={onBlur}
fill={true}
buttonPosition={'none'}
buttonPosition={"none"}
/>
</FormGroup>
);
}
NumericInputCell.cellType = CellType.Field;

View File

@@ -1,9 +1,8 @@
import React, { useCallback } from 'react';
import PaymentReceiveListField from 'components/PaymentReceiveListField';
import classNames from 'classnames';
import { FormGroup, Classes, Intent } from '@blueprintjs/core';
import PaymentReceiveListField from 'components/PaymentReceiveListField';
import { CellType } from 'common';
function PaymentReceiveListFieldCell({
column: { id },
row: { index },
@@ -33,6 +32,4 @@ function PaymentReceiveListFieldCell({
);
}
PaymentReceiveListFieldCell.cellType = CellType.Field;
export default PaymentReceiveListFieldCell;

View File

@@ -1,8 +1,6 @@
import React, { useCallback, useState, useEffect } from 'react';
import { FormGroup, Intent } from '@blueprintjs/core';
import { MoneyInputGroup } from 'components';
import { CellType } from 'common';
const PercentFieldCell = ({
cell: { value: initialValue },
@@ -40,6 +38,4 @@ const PercentFieldCell = ({
);
};
PercentFieldCell.cellType = CellType.Field;
export default PercentFieldCell;

View File

@@ -0,0 +1,41 @@
import React from 'react';
import classNames from 'classnames';
import { FormGroup, Intent, Classes, Radio } from '@blueprintjs/core';
export function RadioTableCell({
row: { index, original },
column: { id, radioProps },
cell: { value: initialValue },
payload,
}) {
const [value, setValue] = React.useState(initialValue);
const onChange = (e) => {
// const newValue = e.target.checked;
// debugger;
// setValue(newValue);
// payload.updateData(index, id, newValue);
};
React.useEffect(() => {
setValue(initialValue);
}, [initialValue]);
const error = payload.errors?.[index]?.[id];
return (
<FormGroup
intent={error ? Intent.DANGER : null}
className={classNames(Classes.FILL)}
>
<Radio
value={value}
label={'Warehouse #1'}
onChange={onChange}
checked={initialValue}
minimal={true}
{...radioProps}
/>
</FormGroup>
);
}

View File

@@ -2,7 +2,6 @@ import React from 'react';
import classNames from 'classnames';
import { Classes, Switch, FormGroup, Intent } from '@blueprintjs/core';
import { CellType } from 'common';
import { safeInvoke } from 'utils';
/**
@@ -49,6 +48,4 @@ const SwitchEditableCell = ({
);
};
SwitchEditableCell.cellType = CellType.Field;
export default SwitchEditableCell;
export default SwitchEditableCell;

View File

@@ -1,7 +1,6 @@
import React, { useState, useEffect } from 'react';
import classNames from 'classnames';
import { Classes, TextArea, FormGroup, Intent } from '@blueprintjs/core';
import { CellType } from 'common';
const TextAreaEditableCell = ({
row: { index },
@@ -40,6 +39,4 @@ const TextAreaEditableCell = ({
);
};
TextAreaEditableCell.cellType = CellType.Field;
export default TextAreaEditableCell;

View File

@@ -9,7 +9,7 @@ import NumericInputCell from './NumericInputCell';
import CheckBoxFieldCell from './CheckBoxFieldCell';
import SwitchFieldCell from './SwitchFieldCell';
import TextAreaCell from './TextAreaCell';
import BranchesListFieldCell from './BranchesListFieldCell';
import { RadioTableCell } from './RadioFieldCell';
export {
AccountsListFieldCell,
@@ -24,5 +24,5 @@ export {
CheckBoxFieldCell,
SwitchFieldCell,
TextAreaCell,
BranchesListFieldCell,
RadioTableCell,
};

View File

@@ -1,7 +1,8 @@
import React from 'react';
import styled from 'styled-components';
import { DataTable } from 'components';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import { DataTable, If } from 'components';
import 'style/components/DataTable/DataTableEditable.scss';
/**
* Editable datatable.
@@ -10,106 +11,26 @@ export default function DatatableEditable({
totalRow = false,
actions,
name,
className,
...tableProps
}) {
return (
<DatatableEditableRoot>
<div
className={classNames(
CLASSES.DATATABLE_EDITOR,
{
[`${CLASSES.DATATABLE_EDITOR}--${name}`]: name,
},
className,
)}
>
<DataTable {...tableProps} />
</DatatableEditableRoot>
<If condition={actions}>
<div className={classNames(CLASSES.DATATABLE_EDITOR_ACTIONS)}>
{actions}
</div>
</If>
</div>
);
}
const DatatableEditableRoot = styled.div`
.bp3-form-group {
margin-bottom: 0;
}
.table {
border: 1px solid #d2dce2;
border-radius: 5px;
background-color: #fff;
.th,
.td {
border-left: 1px solid #e2e2e2;
&:first-of-type{
border-left: 0;
}
}
.thead {
.tr .th {
padding: 9px 14px;
background-color: #f2f3fb;
font-size: 13px;
color: #415060;
border-bottom: 1px solid #d2dce2;
&,
.inner-resizer {
border-left-color: transparent;
}
}
}
.tbody {
.tr .td {
border-bottom: 0;
border-bottom: 1px solid #d8d8d8;
min-height: 38px;
padding: 4px 14px;
&.td-field-type,
&.td-button-type{
padding: 2px;
}
}
.tr:last-of-type .td {
border-bottom: 0;
}
.tr {
&:hover .td,
.bp3-input {
background-color: transparent;
}
.bp3-form-group:not(.bp3-intent-danger) .bp3-input,
.form-group--select-list .bp3-button {
border-color: #ffffff;
color: #222;
border-radius: 3px;
text-align: inherit;
}
.bp3-form-group:not(.bp3-intent-danger) .bp3-input {
border-radius: 2px;
padding-left: 14px;
padding-right: 14px;
&:focus {
box-shadow: 0 0 0 2px #116cd0;
}
}
.form-group--select-list .bp3-button {
padding-left: 6px;
padding-right: 6px;
&:after {
display: none;
}
}
.form-group--select-list,
.bp3-form-group {
&.bp3-intent-danger {
.bp3-button:not(.bp3-minimal),
.bp3-input {
border-color: #f7b6b6;
}
}
}
.td.actions {
.bp3-button {
color: #80858f;
}
}
}
}
}
`;

View File

@@ -1,8 +1,7 @@
import React, { useContext } from 'react';
import classNames from 'classnames';
import { camelCase} from 'lodash';
import { If, Skeleton } from 'components';
import { If } from 'components';
import { Skeleton } from 'components';
import { useAppIntlContext } from 'components/AppIntlProvider';
import TableContext from './TableContext';
import { saveInvoke, ignoreEventFromSelectors } from 'utils';
@@ -57,8 +56,7 @@ export default function TableCell({ cell, row, index }) {
return;
}
saveInvoke(onCellClick, cell, event);
};
const cellType = camelCase(cell.column.Cell.cellType) || 'text';
};
return (
<div
@@ -67,9 +65,6 @@ export default function TableCell({ cell, row, index }) {
'is-text-overview': cell.column.textOverview,
clickable: cell.column.clickable,
'align-right': cell.column.align === 'right',
'align-center': cell.column.align === 'center',
[`td-${cell.column.id}`]: cell.column.id,
[`td-${cellType}-type`]: !!cellType,
}),
onClick: handleCellClick,
})}

View File

@@ -1,6 +1,6 @@
import React from 'react';
import { Checkbox } from '@blueprintjs/core';
import { CellType } from 'common';
export default function TableIndeterminateCheckboxRow({ row }) {
return (
<div class="selection-checkbox">
@@ -8,5 +8,3 @@ export default function TableIndeterminateCheckboxRow({ row }) {
</div>
);
}
TableIndeterminateCheckboxRow.cellType = CellType.Field;

View File

@@ -1,34 +0,0 @@
import React from 'react';
import intl from 'react-intl-universal';
import * as R from 'ramda';
import { DetailItem } from 'components';
import { isEqual } from 'lodash';
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
/**
* Detail exchange rate item.
* @param {*} param0
* @param {*} param1
* @returns
*/
function DetailExchangeRate({
exchangeRate,
toCurrency,
// #withCurrentOrganization
organization: { base_currency },
}) {
if (isEqual(base_currency, toCurrency)) {
return null;
}
return (
<DetailItem label={intl.get('exchange_rate')}>
1 {base_currency} = {exchangeRate} {toCurrency}
</DetailItem>
);
}
export const ExchangeRateDetailItem = R.compose(withCurrentOrganization())(
DetailExchangeRate,
);

View File

@@ -38,8 +38,6 @@ import WarehouseFormDialog from '../containers/Dialogs/WarehouseFormDialog';
import BranchFormDialog from '../containers/Dialogs/BranchFormDialog';
import BranchActivateDialog from '../containers/Dialogs/BranchActivateDialog';
import WarehouseActivateDialog from '../containers/Dialogs/WarehouseActivateDialog';
import CustomerOpeningBalanceDialog from '../containers/Dialogs/CustomerOpeningBalanceDialog';
import VendorOpeningBalanceDialog from '../containers/Dialogs/VendorOpeningBalanceDialog';
/**
* Dialogs container.
@@ -88,8 +86,6 @@ export default function DialogsContainer() {
<BranchFormDialog dialogName={'branch-form'} />
<BranchActivateDialog dialogName={'branch-activate'} />
<WarehouseActivateDialog dialogName={'warehouse-activate'} />
<CustomerOpeningBalanceDialog dialogName={'customer-opening-balance'} />
<VendorOpeningBalanceDialog dialogName={'vendor-opening-balance'} />
</div>
);
}

View File

@@ -4,7 +4,6 @@ import { Classes, Icon, H4, Button } from '@blueprintjs/core';
import withDrawerActions from 'containers/Drawer/withDrawerActions';
import styled from 'styled-components';
import { compose } from 'utils';
/**
@@ -14,7 +13,6 @@ function DrawerHeaderContent(props) {
const {
icon,
title = <T id={'view_paper'} />,
subTitle,
onClose,
name,
closeDrawer,
@@ -32,10 +30,7 @@ function DrawerHeaderContent(props) {
return (
<div className={Classes.DRAWER_HEADER}>
<Icon icon={icon} iconSize={Icon.SIZE_LARGE} />
<H4>
{title}
<SubTitle>{subTitle}</SubTitle>
</H4>
<H4>{title}</H4>
<Button
aria-label="Close"
@@ -49,24 +44,3 @@ function DrawerHeaderContent(props) {
}
export default compose(withDrawerActions)(DrawerHeaderContent);
/**
* SubTitle Drawer header.
* @returns {React.JSX}
*/
function SubTitle({ children }) {
if (children == null) {
return null;
}
return <SubTitleHead>{children}</SubTitleHead>;
}
const SubTitleHead = styled.div`
color: #666;
font-size: 12px;
font-weight: 400;
line-height: 1;
padding: 2px 0px;
margin: 2px 0px;
`;

View File

@@ -12,20 +12,23 @@ export function ExchangeRateInputGroup({
formGroupProps,
name,
}) {
const fromCountryCode = 'US';
const toCountryCode = 'LY';
return (
<FFormGroup inline={true} {...formGroupProps} name={name}>
<ControlGroup>
<ExchangeRatePrepend>
<ExchangeFlagIcon currencyCode={fromCurrency} /> 1 {fromCurrency} =
<ExchangeFlagIcon countryCode={fromCountryCode} /> 1 {fromCurrency} =
</ExchangeRatePrepend>
<ExchangeRateField
allowDecimals={true}
allowDecimals={false}
allowNegativeValue={true}
{...inputGroupProps}
name={name}
/>
<ExchangeRateAppend>
<ExchangeFlagIcon currencyCode={toCurrency} /> {toCurrency}
<ExchangeFlagIcon countryCode={toCountryCode} /> {toCurrency}
</ExchangeRateAppend>
</ControlGroup>
</FFormGroup>
@@ -33,7 +36,7 @@ export function ExchangeRateInputGroup({
}
const ExchangeRateField = styled(FMoneyInputGroup)`
max-width: 75px;
max-width: 88px;
`;
const ExchangeRateSideIcon = styled.div`

View File

@@ -1,94 +0,0 @@
import React from 'react';
import styled from 'styled-components';
import intl from 'react-intl-universal';
import {
Button,
Popover,
PopoverInteractionKind,
FormGroup,
Position,
Classes,
} from '@blueprintjs/core';
import { ExchangeRateInputGroup, Icon } from 'components';
export function ExchangeRateMutedField({
name,
toCurrency,
fromCurrency,
date,
exchangeRate,
exchangeRateFieldProps,
popoverProps,
}) {
const content = (
<ExchangeRateFormGroupContent>
<ExchangeRateInputGroup
name={name}
fromCurrency={fromCurrency}
toCurrency={toCurrency}
{...exchangeRateFieldProps}
/>
</ExchangeRateFormGroupContent>
);
return (
<ExchangeRateFormGroup label={`As on ${date},`}>
<Popover
content={content}
interactionKind={PopoverInteractionKind.CLICK}
position={Position.RIGHT_TOP}
modifiers={{
offset: { offset: '0, 4' },
}}
{...popoverProps}
minimal={true}
usePortal={false}
target={<div />}
>
<ExchangeRateButton>
1 {fromCurrency} = {exchangeRate} {toCurrency}
<Button
className={Classes.MINIMAL}
rightIcon={<Icon icon="pen-18" iconSize={14} />}
small={true}
/>
</ExchangeRateButton>
</Popover>
</ExchangeRateFormGroup>
);
}
const ExchangeRateFormGroup = styled(FormGroup)`
&.bp3-form-group {
label.bp3-label {
font-size: 12px;
opacity: 0.7;
line-height: 1;
margin-bottom: 5px;
}
}
`;
const ExchangeRateButton = styled.div`
display: flex;
align-items: center;
font-size: 13px;
font-weight: 400;
color: #0d244a;
position: relative;
padding-right: 28px;
.bp3-button {
position: absolute;
right: 0;
}
`;
const ExchangeRateFormGroupContent = styled.div`
padding: 5px 0;
.bp3-form-group {
padding: 2px;
margin: 2px 4px !important;
}
`;

View File

@@ -1,2 +1 @@
export * from './ExchangeRateInput';
export * from './ExchangeRateMutedField'
export * from './ExchangeRateInput';

View File

@@ -2,8 +2,7 @@ import React, { useMemo, useCallback } from 'react';
import moment from 'moment';
import intl from 'react-intl-universal';
import If from '../Utils/If';
import { FormattedMessage as T } from '../FormattedMessage';
import { If, FormattedMessage as T } from 'components';
import {
FinancialSheetRoot,
FinancialSheetFooterCurrentTime,

View File

@@ -2,8 +2,7 @@ import React from 'react';
import styled from 'styled-components';
import { Align } from 'common';
import { SkeletonText } from 'components';
import DataTable from '../../components/DataTable'
import { SkeletonText, DataTable } from 'components';
import TableSkeletonRows from 'components/Datatable/TableSkeletonRows';
import TableSkeletonHeader from 'components/Datatable/TableHeaderSkeleton';

View File

@@ -1,9 +0,0 @@
import styled from 'styled-components';
import DataTable from '../DataTable';
export const ReportDataTable = styled(DataTable)`
.table .tbody .tr.no-results:last-of-type .td {
border-bottom: 1px solid #ddd;
}
`;

View File

@@ -1,3 +1,2 @@
export * from './FinancialSheet';
export * from './FinancialSheetSkeleton';
export * from './ReportDataTable';
export * from './FinancialSheetSkeleton';

View File

@@ -1,44 +0,0 @@
import React from 'react';
import styled from 'styled-components';
import { Navbar } from '@blueprintjs/core';
/**
* Form the topbar.
* @param {JSX.Element} children
* @returns {JSX.Element}
*/
export function FormTopbar({ className, children }) {
return <FormTopBarRoot className={className}>{children}</FormTopBarRoot>;
}
const FormTopBarRoot = styled(Navbar)`
box-shadow: 0 0 0;
border-bottom: 1px solid #c7d5db;
height: 35px;
padding: 0 20px;
.bp3-navbar-group {
height: 35px;
}
.bp3-navbar-divider {
border-left-color: #d2dce2;
}
.bp3-skeleton {
max-height: 10px;
}
.bp3-button {
&:hover {
background: rgba(167, 182, 194, 0.12);
color: #32304a;
}
}
`;
export const DetailsBarSkeletonBase = styled.div`
letter-spacing: 10px;
margin-right: 10px;
margin-left: 10px;
font-size: 8px;
width: 140px;
height: 10px;
`;

View File

@@ -5,8 +5,6 @@ import {
Checkbox,
RadioGroup,
Switch,
EditableText,
TextArea,
} from '@blueprintjs-formik/core';
import { Select, MultiSelect } from '@blueprintjs-formik/select';
@@ -19,6 +17,4 @@ export {
Switch as FSwitch,
Select as FSelect,
MultiSelect as FMultiSelect,
EditableText as FEditableText,
TextArea as FTextArea,
};

View File

@@ -1,9 +1,7 @@
import { useFormikContext } from 'formik';
import { useDeepCompareEffect } from 'hooks/utils';
export function FormikObserver({ onChange }) {
const { values } = useFormikContext();
export function FormikObserver({ onChange, values }) {
useDeepCompareEffect(() => {
onChange(values);
}, [values]);

View File

@@ -1,12 +0,0 @@
import React from 'react';
import styled from 'styled-components';
export function Paper({ children, className }) {
return <PaperRoot className={className}>{children}</PaperRoot>;
}
const PaperRoot = styled.div`
border: 1px solid #d2dce2;
background: #fff;
padding: 10px;
`;

View File

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

View File

@@ -9,13 +9,3 @@ export const CurrencyTag = styled.span`
line-height: 1;
margin-left: 4px;
`;
export const BaseCurrencyRoot = styled.div`
display: flex;
align-items: center;
font-size: 10px;
margin-left: 4px;
> span {
background: #5c7080;
}
`;

View File

@@ -1,7 +1,7 @@
import React from 'react';
export const FlagIcon = ({ currencyCode, className }) => {
const source = `/icons/flags/${currencyCode}.svg`;
export const FlagIcon = ({ countryCode, className }) => {
const source = `/icons/flags/${countryCode}.svg`;
return <img alt="flag" src={source} className={className} />;
};

View File

@@ -2,7 +2,6 @@ import React from 'react';
import styled from 'styled-components';
export const TotalLineBorderStyle = {
None: 'None',
SingleDark: 'SingleDark',
DoubleDark: 'DoubleDark',
};
@@ -81,11 +80,6 @@ export const TotalLineRoot = styled.div`
`
border-bottom: 1px double #000;
`}
${(props) =>
props.borderStyle === TotalLineBorderStyle.None &&
`
border-bottom-color: transparent;
`}
${(props) =>
props.textStyle === TotalLineTextStyle.Bold &&
`

View File

@@ -1,25 +1,23 @@
import React from 'react';
import * as R from 'ramda';
import { ButtonLink } from '../Button';
import { ButtonLink } from 'components';
import withDrawerActions from 'containers/Drawer/withDrawerActions';
function VendorDrawerLinkComponent({
// #ownProps
children,
vendorId,
className,
// #withDrawerActions
openDrawer,
}) {
// Handle view customer drawer.
const handleVendorDrawer = (event) => {
const handleVendorDrawer = () => {
openDrawer('vendor-details-drawer', { vendorId });
event.preventDefault();
};
return <ButtonLink className={className} onClick={handleVendorDrawer}>{children}</ButtonLink>;
return <ButtonLink onClick={handleVendorDrawer}>{children}</ButtonLink>;
}
export const VendorDrawerLink = R.compose(withDrawerActions)(VendorDrawerLinkComponent);

View File

@@ -0,0 +1,222 @@
import React from 'react';
import styled, { createGlobalStyle } from 'styled-components';
import { PopoverInteractionKind, Position } from '@blueprintjs/core';
import { Popover2 } from '@blueprintjs/popover2';
import { DataTable } from 'components';
import { RadioTableCell } from 'components/DataTableCells';
import { compose, updateTableCell } from 'utils';
import { TableStyle } from 'common';
const Classes = {
WAREHOUSE_ITEM_ENTRY_POPOVER: 'warehouse-item-entry-popover',
};
/**
* Retrieve warehouse entries columns.
*/
export function useWarehouseEntriesColumns() {
return React.useMemo(
() => [
{
Header: 'Warehouse Name',
accessor: 'warehouse_name',
Cell: RadioTableCell,
width: 120,
disableSortBy: true,
className: 'name',
},
{
id: 'quantity',
Header: 'Quantity on Hand',
accessor: 'quantity',
disableSortBy: true,
align: 'right',
width: 60,
},
{
id: 'availiable_for_sale',
Header: 'Availiable for Sale',
accessor: 'availiable_for_sale',
disableSortBy: true,
align: 'right',
width: 60,
className: 'availiable_for_sale',
},
],
[],
);
}
export function IntegrateWarehouseTable({ children }) {
return (
<>
<GlobalPopoverStyled />
<Popover2
// minimal={true}
content={<IntegrateWarehousesTable />}
interactionKind={PopoverInteractionKind.CLICK}
position={Position.BOTTOM_RIGHT}
popoverClassName={Classes.WAREHOUSE_ITEM_ENTRY_POPOVER}
autoFocus={false}
enforceFocus={false}
shouldReturnFocusOnClose={false}
>
{children}
</Popover2>
</>
);
}
const PopoverLink = styled.button`
border: 0;
cursor: pointer;
background: transparent;
margin-top: 18px;
padding-right: 0px;
color: #0052cc;
&:hover,
&:active {
text-decoration: underline;
}
`;
export function IntegrateWarehousesTable({
// #ownProps
onUpdateData,
entries,
errors,
}) {
// warehouses entries columns.
const columns = useWarehouseEntriesColumns();
// Handle update data.
const handleUpdateData = React.useCallback(
(rowIndex, columnId, value) => {
const newRows = compose(updateTableCell(rowIndex, columnId, value))(
entries,
);
onUpdateData(newRows);
},
[onUpdateData, entries],
);
const data = React.useMemo(
() => [
{
warehouse_name: true,
quantity: '9,444',
availiable_for_sale: 0,
},
{
warehouse_name: false,
quantity: '19,444',
availiable_for_sale: 0,
},
{
warehouse_name: false,
quantity: '19,444',
availiable_for_sale: 0,
},
{
warehouse_name: false,
quantity: '19,444',
availiable_for_sale: 0,
},
],
[],
);
return (
<WarehousesRoot>
<PopoverHeader>Warehouses</PopoverHeader>
<WarehouseDataTable
columns={columns}
data={data}
styleName={TableStyle.Constrant}
payload={{
errors: errors || [],
updateData: handleUpdateData,
}}
/>
<WarehousesDesc>
<WarehousesDescItem>
Stock on Hand : This is calculated based on Bills and Invoices.
</WarehousesDescItem>
<WarehousesDescItem>
Available for Sale : Stock on Hand - Committed Stock
</WarehousesDescItem>
</WarehousesDesc>
</WarehousesRoot>
);
}
const WarehouseDataTable = styled(DataTable)`
.table {
font-size: 12px;
border-bottom: 1px solid #888;
.thead .tr:first-of-type .th,
.thead .tr:first-of-type .th {
border-top-color: #888;
}
.thead .tr .th {
border-bottom-color: #888;
font-size: 12px;
}
.tbody .tr .td {
padding: 0.6rem 0.6rem;
&:not(:first-of-type) {
border-left: 1px solid #e6e6e6;
}
}
.tbody {
max-height: 145px;
.bp3-form-group .bp3-control,
.bp3-form-group {
margin: 0;
}
.tr .td.availiable_for_sale {
font-weight: 600;
}
}
}
`;
const WarehousesRoot = styled.div`
width: 500px;
`;
const WarehousesDescItem = styled.div`
&:not(:last-of-type) {
margin-bottom: 6px;
}
`;
const WarehousesDesc = styled.div`
font-size: 10px;
padding: 12px 15px;
`;
const PopoverHeader = styled.div`
color: #222;
line-height: 1;
padding: 10px 15px;
font-size: 12px;
font-weight: 500;
`;
const GlobalPopoverStyled = createGlobalStyle`
.${Classes.WAREHOUSE_ITEM_ENTRY_POPOVER}{
&.bp3-popover2,
.bp3-popover2-content{
border-radius: 10px;
}
}
`;

View File

@@ -40,8 +40,8 @@ const warehouseItemRenderer = (
active={modifiers.active}
disabled={modifiers.disabled}
icon={isSelected ? 'tick' : 'blank'}
text={warehouse.name}
label={warehouse.code}
text={warehouse.name.toString()}
label={warehouse.code.toString()}
key={warehouse.id}
onClick={handleClick}
/>
@@ -52,7 +52,7 @@ const warehouseSelectProps = {
itemPredicate: warehouseItemPredicate,
itemRenderer: warehouseItemRenderer,
valueAccessor: (item) => item.id,
labelAccessor: (item) => item.code,
labelAccessor: (item) => item.label,
tagRenderer: (item) => item.name,
};

View File

@@ -40,7 +40,7 @@ const warehouseItemRenderer = (
<MenuItem
active={modifiers.active}
disabled={modifiers.disabled}
label={warehouse.code}
label={warehouse.name.toString()}
key={warehouse.id}
onClick={handleClick}
text={text}

View File

@@ -1,2 +1,3 @@
export * from './WarehouseSelect';
export * from './WarehouseMultiSelect';
export * from './WarehouseItemEntrySelectPopover'

View File

@@ -55,7 +55,7 @@ import AvaterCell from './AvaterCell';
import { ItemsMultiSelect } from './Items';
import MoreMenuItems from './MoreMenutItems';
import CustomSelectList from './CustomSelectList';
import { ExchangeRateDetailItem } from './DetailExchangeRate';
import BaseCurrency from './BaseCurrency';
export * from './Dialog';
export * from './Menu';
@@ -102,9 +102,6 @@ export * from './ExchangeRate';
export * from './Branches';
export * from './Warehouses';
export * from './Currencies';
export * from './FormTopbar'
export * from './Paper';
export * from './Accounts'
const Hint = FieldHint;
@@ -170,7 +167,7 @@ export {
MoneyFieldCell,
ItemsMultiSelect,
AvaterCell,
BaseCurrency,
MoreMenuItems,
CustomSelectList,
ExchangeRateDetailItem,
};

View File

@@ -70,20 +70,6 @@ export const financialReportMenus = [
subject: AbilitySubject.Report,
ability: ReportsAction.READ_AP_AGING_SUMMARY,
},
{
title: <T id={'report.balance_sheet_comparison.title'} />,
desc: <T id={'report.balance_sheet_comparison.desc'} />,
link: 'financial-reports/balance-sheet?previousYear=true&previousYearAmountChange=true&previousYearPercentageChange=true',
subject: AbilitySubject.Report,
ability: ReportsAction.READ_BALANCE_SHEET,
},
{
title: <T id={'report.profit_loss_sheet_comparison.title'} />,
desc: <T id={'report.profit_loss_sheet_comparison.desc'} />,
link: '/financial-reports/profit-loss-sheet?previousYear=true&previousYearAmountChange=true&previousYearPercentageChange=true',
subject: AbilitySubject.Report,
ability: ReportsAction.READ_PROFIT_LOSS,
},
],
},
];

View File

@@ -641,14 +641,14 @@ export default [
ability: ReportsAction.READ_AP_AGING_SUMMARY,
},
},
// {
// text: <T id={'realized_gain_or_loss.label'} />,
// href: '/financial-reports/realized-gain-loss',
// },
// {
// text: <T id={'unrealized_gain_or_loss.label'} />,
// href: '/financial-reports/unrealized-gain-loss',
// },
{
text: <T id={'realized_gain_or_loss.label'} />,
href: '/financial-reports/realized-gain-loss',
},
{
text: <T id={'unrealized_gain_or_loss.label'} />,
href: '/financial-reports/unrealized-gain-loss',
},
{
text: <T id={'Sales/Purchases'} />,
label: true,

View File

@@ -13,13 +13,13 @@ const Schema = Yup.object().shape({
.min(1)
.max(DATATYPES_LENGTH.STRING)
.label(intl.get('journal_type')),
date: Yup.date().required().label(intl.get('date')),
date: Yup.date()
.required()
.label(intl.get('date')),
currency_code: Yup.string().max(3),
publish: Yup.boolean(),
branch_id: Yup.string(),
reference: Yup.string().nullable().min(1).max(DATATYPES_LENGTH.STRING),
description: Yup.string().min(1).max(DATATYPES_LENGTH.STRING).nullable(),
exchange_rate: Yup.number(),
entries: Yup.array().of(
Yup.object().shape({
credit: Yup.number().nullable(),

View File

@@ -10,7 +10,7 @@ import { useMakeJournalFormContext } from './MakeJournalProvider';
* Make journal entries field.
*/
export default function MakeJournalEntriesField() {
const { accounts, contacts ,branches } = useMakeJournalFormContext();
const { accounts, contacts } = useMakeJournalFormContext();
return (
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
@@ -18,7 +18,6 @@ export default function MakeJournalEntriesField() {
name={'entries'}
contacts={contacts}
accounts={accounts}
branches={branches}
shouldUpdate={entriesFieldShouldUpdate}
>
{({

View File

@@ -17,7 +17,6 @@ import MakeJournalFormFloatingActions from './MakeJournalFormFloatingActions';
import MakeJournalEntriesField from './MakeJournalEntriesField';
import MakeJournalFormFooter from './MakeJournalFormFooter';
import MakeJournalFormDialogs from './MakeJournalFormDialogs';
import MakeJournalFormTopBar from './MakeJournalFormTopBar';
import withSettings from 'containers/Settings/withSettings';
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
@@ -59,7 +58,6 @@ function MakeJournalEntriesForm({
journalNumberPrefix,
journalNextNumber,
);
// Form initial values.
const initialValues = useMemo(
() => ({
@@ -70,12 +68,12 @@ function MakeJournalEntriesForm({
: {
...defaultManualJournal,
...(journalAutoIncrement && {
journal_number: journalNumber,
journal_number: defaultTo(journalNumber, ''),
}),
currency_code: base_currency,
}),
}),
[manualJournal, base_currency, journalNumber, journalAutoIncrement],
[manualJournal, base_currency, journalNumber],
);
// Handle the form submiting.
@@ -109,7 +107,7 @@ function MakeJournalEntriesForm({
return;
}
const form = {
...omit(values, ['journal_number_manually']),
...omit(values, ['journal_number', 'journal_number_manually']),
...(values.journal_number_manually && {
journal_number: values.journal_number,
}),
@@ -171,7 +169,6 @@ function MakeJournalEntriesForm({
onSubmit={handleSubmit}
>
<Form>
<MakeJournalFormTopBar />
<MakeJournalEntriesHeader />
<MakeJournalEntriesField />
<MakeJournalFormFooter />
@@ -188,7 +185,7 @@ function MakeJournalEntriesForm({
export default compose(
withMediaActions,
withSettings(({ manualJournalsSettings }) => ({
journalNextNumber: manualJournalsSettings?.nextNumber,
journalNextNumber: parseInt(manualJournalsSettings?.nextNumber, 10),
journalNumberPrefix: manualJournalsSettings?.numberPrefix,
journalAutoIncrement: manualJournalsSettings?.autoIncrement,
})),

View File

@@ -28,7 +28,6 @@ import {
} from 'components';
import withSettings from 'containers/Settings/withSettings';
import { useMakeJournalFormContext } from './MakeJournalProvider';
import { JournalExchangeRateInputField } from './components';
import withDialogActions from 'containers/Dialog/withDialogActions';
import {
currenciesFieldShouldUpdate,
@@ -53,14 +52,14 @@ function MakeJournalEntriesHeader({
// Handle journal number change.
const handleJournalNumberChange = () => {
openDialog('journal-number-form');
openDialog('journal-number-form', {});
};
// Handle journal number blur.
const handleJournalNoBlur = (form, field) => (event) => {
const newValue = event.target.value;
if (field.value !== newValue && journalAutoIncrement) {
if (field.value !== newValue) {
openDialog('journal-number-form', {
initialFormValues: {
manualTransactionNo: newValue,
@@ -202,19 +201,13 @@ function MakeJournalEntriesHeader({
selectedCurrencyCode={value}
onCurrencySelected={(currencyItem) => {
form.setFieldValue('currency_code', currencyItem.currency_code);
form.setFieldValue('exchange_rate', '');
}}
defaultSelectText={value}
disabled={true}
/>
</FormGroup>
)}
</FastField>
{/* ----------- Exchange rate ----------- */}
<JournalExchangeRateInputField
name={'exchange_rate'}
formGroupProps={{ label: ' ', inline: true }}
/>
</div>
);
}

View File

@@ -11,7 +11,7 @@ import { MakeJournalProvider } from './MakeJournalProvider';
*/
export default function MakeJournalEntriesPage() {
const { id: journalId } = useParams();
return (
<MakeJournalProvider journalId={journalId}>
<MakeJournalEntriesForm />

View File

@@ -21,16 +21,15 @@ export default function MakeJournalEntriesTable({
entries,
defaultEntry,
error,
initialLinesNumber = 1,
minLinesNumber = 1,
initialLinesNumber = 4,
minLinesNumber = 4,
currencyCode,
}) {
const { accounts, contacts, branches } = useMakeJournalFormContext();
const { accounts, contacts } = useMakeJournalFormContext();
// Memorized data table columns.
const columns = useJournalTableEntriesColumns();
// Handles update datatable data.
const handleUpdateData = (rowIndex, columnId, value) => {
const newRows = compose(
@@ -63,13 +62,13 @@ export default function MakeJournalEntriesTable({
data={entries}
sticky={true}
totalRow={true}
footer={true}
payload={{
accounts,
errors: error,
updateData: handleUpdateData,
removeRow: handleRemoveRow,
contacts,
branches,
autoFocus: ['account_id', 0],
currencyCode,
}}

View File

@@ -1,29 +1,44 @@
import React from 'react';
import { FastField } from 'formik';
import classNames from 'classnames';
import styled from 'styled-components';
import { CLASSES } from 'common/classes';
import { Row, Col, Paper } from 'components';
import { MakeJournalFormFooterLeft } from './MakeJournalFormFooterLeft';
import { MakeJournalFormFooterRight } from './MakeJournalFormFooterRight';
import { FormGroup, TextArea } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { Postbox, ErrorMessage, Row, Col } from 'components';
import Dragzone from 'components/Dragzone';
import { inputIntent } from 'utils';
export default function MakeJournalFormFooter() {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<MakeJournalFooterPaper>
<Postbox title={<T id={'journal_details'} />} defaultOpen={false}>
<Row>
<Col md={8}>
<MakeJournalFormFooterLeft />
<FastField name={'description'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'description'} />}
className={'form-group--description'}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="description" />}
fill={true}
>
<TextArea fill={true} {...field} />
</FormGroup>
)}
</FastField>
</Col>
<Col md={4}>
<MakeJournalFormFooterRight />
<Dragzone
initialFiles={[]}
// onDrop={handleDropFiles}
// onDeleteFile={handleDeleteFile}
hint={<T id={'attachments_maximum'} />}
/>
</Col>
</Row>
</MakeJournalFooterPaper>
</Postbox>
</div>
);
}
const MakeJournalFooterPaper = styled(Paper)`
padding: 20px;
`;

View File

@@ -1,32 +0,0 @@
import React from 'react';
import styled from 'styled-components';
import { FFormGroup, FEditableText, FormattedMessage as T } from 'components';
export function MakeJournalFormFooterLeft() {
return (
<React.Fragment>
{/* --------- Description --------- */}
<DescriptionFormGroup
label={<T id={'description'} />}
name={'description'}
>
<FEditableText
name={'description'}
placeholder={<T id={'make_jorunal.decscrption.placeholder'} />}
/>
</DescriptionFormGroup>
</React.Fragment>
);
}
const DescriptionFormGroup = styled(FFormGroup)`
&.bp3-form-group {
.bp3-label {
font-size: 12px;
margin-bottom: 12px;
}
.bp3-form-content {
margin-left: 10px;
}
}
`;

View File

@@ -1,34 +0,0 @@
import React from 'react';
import styled from 'styled-components';
import {
T,
TotalLines,
TotalLine,
TotalLineBorderStyle,
TotalLineTextStyle,
} from 'components';
import { useJournalTotals } from './utils';
export function MakeJournalFormFooterRight() {
const { formattedSubtotal, formattedTotal } = useJournalTotals();
return (
<MakeJouranlTotalLines>
<TotalLine
title={<T id={'make_journal.label.subtotal'} />}
value={formattedSubtotal}
borderStyle={TotalLineBorderStyle.None}
/>
<TotalLine
title={<T id={'make_journal.label.total'} />}
value={formattedTotal}
textStyle={TotalLineTextStyle.Bold}
/>
</MakeJouranlTotalLines>
);
}
const MakeJouranlTotalLines = styled(TotalLines)`
width: 100%;
color: #555555;
`;

View File

@@ -1,68 +0,0 @@
import React from 'react';
import intl from 'react-intl-universal';
import { Button, Alignment, NavbarGroup, Classes } from '@blueprintjs/core';
import styled from 'styled-components';
import { useSetPrimaryBranchToForm } from './utils';
import { useFeatureCan } from 'hooks/state';
import {
Icon,
BranchSelect,
FeatureCan,
FormTopbar,
DetailsBarSkeletonBase,
} from 'components';
import { useMakeJournalFormContext } from './MakeJournalProvider';
import { Features } from 'common';
/**
* Make journal form topbar.
* @returns
*/
export default function MakeJournalFormTopBar() {
// Features guard.
const { featureCan } = useFeatureCan();
// Sets the primary branch to form.
useSetPrimaryBranchToForm();
// Can't display the navigation bar if branches feature is not enabled.
if (!featureCan(Features.Branches)) {
return null;
}
return (
<FormTopbar>
<NavbarGroup align={Alignment.LEFT}>
<FeatureCan feature={Features.Branches}>
<MakeJournalFormSelectBranch />
</FeatureCan>
</NavbarGroup>
</FormTopbar>
);
}
function MakeJournalFormSelectBranch() {
// Invoice form context.
const { branches, isBranchesLoading } = useMakeJournalFormContext();
return isBranchesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<BranchSelect
name={'branch_id'}
branches={branches}
input={MakeJournalBranchSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function MakeJournalBranchSelectButton({ label }) {
return (
<Button
text={intl.get('make_journal.branch_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'branch-16'} iconSize={16} />}
/>
);
}

View File

@@ -1,7 +1,4 @@
import React, { createContext, useState } from 'react';
import { isEqual, isUndefined } from 'lodash';
import { Features } from 'common';
import { useFeatureCan } from 'hooks/state';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import {
useAccounts,
@@ -11,8 +8,7 @@ import {
useCreateJournal,
useEditJournal,
useSettings,
useBranches,
useSettingsManualJournals,
useSettingsManualJournals
} from 'hooks/query';
const MakeJournalFormContext = createContext();
@@ -20,17 +16,15 @@ const MakeJournalFormContext = createContext();
/**
* Make journal form provider.
*/
function MakeJournalProvider({ journalId, query, ...props }) {
// Features guard.
const { featureCan } = useFeatureCan();
const isBranchFeatureCan = featureCan(Features.Branches);
function MakeJournalProvider({ journalId, ...props }) {
// Load the accounts list.
const { data: accounts, isLoading: isAccountsLoading } = useAccounts();
// Load the customers list.
const { data: contacts, isLoading: isContactsLoading } =
useAutoCompleteContacts();
const {
data: contacts,
isLoading: isContactsLoading,
} = useAutoCompleteContacts();
// Load the currencies list.
const { data: currencies, isLoading: isCurrenciesLoading } = useCurrencies();
@@ -49,27 +43,15 @@ function MakeJournalProvider({ journalId, query, ...props }) {
// Loading the journal settings.
const { isLoading: isSettingsLoading } = useSettingsManualJournals();
// Fetches the branches list.
const {
data: branches,
isLoading: isBranchesLoading,
isSuccess: isBranchesSuccess,
} = useBranches(query, { enabled: isBranchFeatureCan });
// Submit form payload.
const [submitPayload, setSubmitPayload] = useState({});
// Determines whether the warehouse and branches are loading.
const isFeatureLoading = isBranchesLoading;
const provider = {
accounts,
contacts,
currencies,
manualJournal,
branches,
createJournalMutate,
editJournalMutate,
@@ -77,13 +59,12 @@ function MakeJournalProvider({ journalId, query, ...props }) {
isContactsLoading,
isCurrenciesLoading,
isJournalLoading,
isFeatureLoading,
isSettingsLoading,
isBranchesSuccess,
isNewMode: !journalId,
submitPayload,
setSubmitPayload,
setSubmitPayload
};
return (
@@ -92,7 +73,7 @@ function MakeJournalProvider({ journalId, query, ...props }) {
isJournalLoading ||
isAccountsLoading ||
isCurrenciesLoading ||
isContactsLoading ||
isContactsLoading ||
isSettingsLoading
}
name={'make-journal-page'}

View File

@@ -1,28 +1,15 @@
import React from 'react';
import { Menu, MenuItem, Position, Button } from '@blueprintjs/core';
import { Popover2 } from '@blueprintjs/popover2';
import { useFormikContext } from 'formik';
import { Intent, Position, Button, Tooltip } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { Icon, Money, Hint } from 'components';
import intl from 'react-intl-universal';
import {
ExchangeRateInputGroup,
Icon,
Hint,
FormattedMessage as T,
} from 'components';
import {
AccountsListFieldCell,
MoneyFieldCell,
InputGroupCell,
ContactsListFieldCell,
BranchesListFieldCell,
} from 'components/DataTableCells';
import { CellType, Features, Align } from 'common';
import { useFeatureCan } from 'hooks/state';
import { useCurrentOrganization } from 'hooks/state';
import { useJournalIsForeign } from './utils';
import { safeSumBy } from 'utils';
/**
* Contact header cell.
@@ -53,6 +40,42 @@ export function DebitHeaderCell({ payload: { currencyCode } }) {
return intl.get('debit_currency', { currency: currencyCode });
}
/**
* Account footer cell.
*/
function AccountFooterCell({ payload: { currencyCode } }) {
return (
<span>
{intl.get('total_currency', { currency: currencyCode })}
</span>
);
}
/**
* Total credit table footer cell.
*/
function TotalCreditFooterCell({ payload: { currencyCode }, rows }) {
const credit = safeSumBy(rows, 'original.credit');
return (
<span>
<Money amount={credit} currency={currencyCode} />
</span>
);
}
/**
* Total debit table footer cell.
*/
function TotalDebitFooterCell({ payload: { currencyCode }, rows }) {
const debit = safeSumBy(rows, 'original.debit');
return (
<span>
<Money amount={debit} currency={currencyCode} />
</span>
);
}
/**
* Actions cell renderer.
*/
@@ -63,123 +86,95 @@ export const ActionsCellRenderer = ({
data,
payload,
}) => {
const handleClickRemoveRole = () => {
const onClickRemoveRole = () => {
payload.removeRow(index);
};
const exampleMenu = (
<Menu>
<MenuItem
onClick={handleClickRemoveRole}
text={intl.get('make_journal.entries.remove_row')}
/>
</Menu>
);
return (
<Popover2 content={exampleMenu} placement="left-start">
<Tooltip content={<T id={'remove_the_line'} />} position={Position.LEFT}>
<Button
icon={<Icon icon={'more-13'} iconSize={13} />}
icon={<Icon icon="times-circle" iconSize={14} />}
iconSize={14}
className="m12"
className="ml2"
minimal={true}
intent={Intent.DANGER}
onClick={onClickRemoveRole}
/>
</Popover2>
</Tooltip>
);
};
ActionsCellRenderer.cellType = CellType.Button;
/**
* Retrieve columns of make journal entries table.
*/
export const useJournalTableEntriesColumns = () => {
const { featureCan } = useFeatureCan();
return React.useMemo(
() => [
{
Header: '#',
accessor: 'index',
Cell: ({ row: { index } }) => <span>{index + 1}</span>,
className: 'index',
width: 40,
disableResizing: true,
disableSortBy: true,
sticky: 'left',
},
{
Header: intl.get('account'),
id: 'account_id',
accessor: 'account_id',
Cell: AccountsListFieldCell,
Footer: AccountFooterCell,
className: 'account',
disableSortBy: true,
width: 160,
fieldProps: { allowCreate: true },
fieldProps: { allowCreate: true }
},
{
Header: CreditHeaderCell,
accessor: 'credit',
Cell: MoneyFieldCell,
Footer: TotalCreditFooterCell,
className: 'credit',
disableSortBy: true,
width: 100,
align: Align.Right,
},
{
Header: DebitHeaderCell,
accessor: 'debit',
Cell: MoneyFieldCell,
Footer: TotalDebitFooterCell,
className: 'debit',
disableSortBy: true,
width: 100,
align: Align.Right,
},
{
Header: ContactHeaderCell,
id: 'contact_id',
accessor: 'contact_id',
Cell: ContactsListFieldCell,
className: 'contact',
disableSortBy: true,
width: 120,
},
...(featureCan(Features.Branches)
? [
{
Header: intl.get('branch'),
id: 'branch_id',
accessor: 'branch_id',
Cell: BranchesListFieldCell,
disableSortBy: true,
width: 120,
},
]
: []),
{
Header: intl.get('note'),
accessor: 'note',
Cell: InputGroupCell,
disableSortBy: true,
className: 'note',
width: 200,
},
{
Header: '',
accessor: 'action',
Cell: ActionsCellRenderer,
className: 'actions',
disableSortBy: true,
disableResizing: true,
width: 45,
align: Align.Center,
},
],
[],
);
};
/**
* Journal exchange rate input field.
* @returns {JSX.Element}
*/
export function JournalExchangeRateInputField({ ...props }) {
const currentOrganization = useCurrentOrganization();
const { values } = useFormikContext();
const isForeignJouranl = useJournalIsForeign();
// Can't continue if the customer is not foreign.
if (!isForeignJouranl) {
return null;
}
return (
<ExchangeRateInputGroup
fromCurrency={values.currency_code}
toCurrency={currentOrganization.base_currency}
{...props}
/>
);
}

View File

@@ -1,6 +1,6 @@
import React from 'react';
import { Intent } from '@blueprintjs/core';
import { sumBy, setWith, toSafeInteger, get, first } from 'lodash';
import { sumBy, setWith, toSafeInteger, get } from 'lodash';
import moment from 'moment';
import * as R from 'ramda';
import {
@@ -9,15 +9,11 @@ import {
repeatValue,
transformToForm,
defaultFastFieldShouldUpdate,
ensureEntriesHasEmptyLine,
formattedAmount,
safeSumBy,
ensureEntriesHasEmptyLine
} from 'utils';
import { AppToaster } from 'components';
import intl from 'react-intl-universal';
import { useFormikContext } from 'formik';
import { useMakeJournalFormContext } from './MakeJournalProvider';
import { useCurrentOrganization } from 'hooks/state';
const ERROR = {
JOURNAL_NUMBER_ALREADY_EXISTS: 'JOURNAL.NUMBER.ALREADY.EXISTS',
@@ -30,30 +26,25 @@ const ERROR = {
ENTRIES_SHOULD_ASSIGN_WITH_CONTACT: 'ENTRIES_SHOULD_ASSIGN_WITH_CONTACT',
};
export const MIN_LINES_NUMBER = 1;
export const DEFAULT_LINES_NUMBER = 1;
export const MIN_LINES_NUMBER = 4;
export const defaultEntry = {
account_id: '',
credit: '',
debit: '',
contact_id: '',
branch_id: '',
note: '',
};
export const defaultManualJournal = {
journal_number: '',
journal_number_manually: false,
journal_type: 'Journal',
date: moment(new Date()).format('YYYY-MM-DD'),
description: '',
reference: '',
currency_code: '',
publish: '',
branch_id: '',
exchange_rate: 1,
entries: [...repeatValue(defaultEntry, DEFAULT_LINES_NUMBER)],
entries: [...repeatValue(defaultEntry, 4)],
};
// Transform to edit form.
@@ -188,7 +179,6 @@ export const entriesFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.accounts !== oldProps.accounts ||
newProps.contacts !== oldProps.contacts ||
newProps.branches !== oldProps.branches ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
@@ -202,63 +192,3 @@ export const currenciesFieldShouldUpdate = (newProps, oldProps) => {
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
export const useSetPrimaryBranchToForm = () => {
const { setFieldValue } = useFormikContext();
const { branches, isBranchesSuccess } = useMakeJournalFormContext();
React.useEffect(() => {
if (isBranchesSuccess) {
const primaryBranch = branches.find((b) => b.primary) || first(branches);
if (primaryBranch) {
setFieldValue('branch_id', primaryBranch.id);
}
}
}, [isBranchesSuccess, setFieldValue, branches]);
};
/**
* Retreives the Journal totals.
*/
export const useJournalTotals = () => {
const {
values: { entries, currency_code: currencyCode },
} = useFormikContext();
// Retrieves the invoice entries total.
const totalCredit = safeSumBy(entries, 'credit');
const totalDebit = safeSumBy(entries, 'debit');
const total = Math.max(totalCredit, totalDebit);
// Retrieves the formatted total money.
const formattedTotal = React.useMemo(
() => formattedAmount(total, currencyCode),
[total, currencyCode],
);
// Retrieves the formatted subtotal.
const formattedSubtotal = React.useMemo(
() => formattedAmount(total, currencyCode, { money: false }),
[total, currencyCode],
);
return {
formattedTotal,
formattedSubtotal,
};
};
/**
* Detarmines whether the expenses has foreign .
* @returns {boolean}
*/
export const useJournalIsForeign = () => {
const { values } = useFormikContext();
const currentOrganization = useCurrentOrganization();
const isForeignJournal = React.useMemo(
() => values.currency_code !== currentOrganization.base_currency,
[values.currency_code, currentOrganization.base_currency],
);
return isForeignJournal;
};

View File

@@ -15,8 +15,6 @@ import withSettings from '../Settings/withSettings';
import { useAccountsChartContext } from './AccountsChartProvider';
import { useMemorizedColumnsWidths } from '../../hooks';
import { AccountDialogAction } from '../Dialogs/AccountDialog/utils';
import withAlertsActions from 'containers/Alert/withAlertActions';
import withDialogActions from 'containers/Dialog/withDialogActions';
import withDrawerActions from 'containers/Drawer/withDrawerActions';
@@ -60,10 +58,7 @@ function AccountsDataTable({
// Handle edit account action.
const handleEditAccount = (account) => {
openDialog('account-form', {
action: AccountDialogAction.Edit,
id: account.id,
});
openDialog('account-form', { action: 'edit', id: account.id });
};
// Handle view detail account.
@@ -74,7 +69,7 @@ function AccountsDataTable({
// Handle new child button click.
const handleNewChildAccount = (account) => {
openDialog('account-form', {
action: AccountDialogAction.NewChild,
action: 'new_child',
parentAccountId: account.id,
accountType: account.account_type,
});

View File

@@ -5,7 +5,6 @@ import { Intent, Alert } from '@blueprintjs/core';
import { AppToaster } from 'components';
import { useDeleteBranch } from 'hooks/query';
import { handleDeleteErrors } from '../../Preferences/Branches/utils';
import withAlertStoreConnect from 'containers/Alert/withAlertStoreConnect';
import withAlertActions from 'containers/Alert/withAlertActions';
@@ -25,6 +24,7 @@ function BranchDeleteAlert({
// #withAlertActions
closeAlert,
}) {
const { mutateAsync: deleteBranch, isLoading } = useDeleteBranch();
// Handle cancel delete alert.
@@ -46,9 +46,7 @@ function BranchDeleteAlert({
response: {
data: { errors },
},
}) => {
handleDeleteErrors(errors);
},
}) => {},
)
.finally(() => {
closeAlert(name);

View File

@@ -3,7 +3,7 @@ import intl from 'react-intl-universal';
import { Intent, Alert } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { useMarkBranchAsPrimary } from 'hooks/query';
import { useMarkPrimaryBranches } from 'hooks/query';
import { AppToaster } from 'components';
import withAlertActions from 'containers/Alert/withAlertActions';
@@ -25,7 +25,7 @@ function BranchMarkPrimaryAlert({
closeAlert,
}) {
const { mutateAsync: markPrimaryBranchMutate, isLoading } =
useMarkBranchAsPrimary();
useMarkPrimaryBranches();
// Handle cancel mark primary alert.
const handleCancelMarkPrimaryAlert = () => {
@@ -49,8 +49,8 @@ function BranchMarkPrimaryAlert({
return (
<Alert
// cancelButtonText={<T id={'cancel'} />}
// confirmButtonText={<T id={'make_primary'} />}
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={<T id={'make_primary'} />}
intent={Intent.WARNING}
isOpen={isOpen}
onCancel={handleCancelMarkPrimaryAlert}

View File

@@ -4,7 +4,6 @@ import { FormattedMessage as T, FormattedHTMLMessage } from 'components';
import { Intent, Alert } from '@blueprintjs/core';
import { AppToaster } from 'components';
import { useDeleteWarehouse } from 'hooks/query';
import { handleDeleteErrors } from '../../Preferences/Warehouses/utils';
import withAlertStoreConnect from 'containers/Alert/withAlertStoreConnect';
import withAlertActions from 'containers/Alert/withAlertActions';
@@ -47,9 +46,7 @@ function WarehouseDeleteAlert({
response: {
data: { errors },
},
}) => {
handleDeleteErrors(errors);
},
}) => {},
)
.finally(() => {
closeAlert(name);

View File

@@ -3,7 +3,7 @@ import intl from 'react-intl-universal';
import { Intent, Alert } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { useMarkWarehouseAsPrimary } from 'hooks/query';
import { useMarkPrimaryWarehouse } from 'hooks/query';
import { AppToaster } from 'components';
import withAlertActions from 'containers/Alert/withAlertActions';
@@ -24,14 +24,14 @@ function WarehouseMarkPrimaryAlert({
// #withAlertActions
closeAlert,
}) {
// const { mutateAsync: markPrimaryWarehouseMutate, isLoading } =
// useMarkWarehouseAsPrimary();
const { mutateAsync: markPrimaryWarehouseMutate, isLoading } =
useMarkPrimaryWarehouse();
// Handle cancel mark primary alert.
const handleCancelMarkPrimaryAlert = () => {
closeAlert(name);
};
console.log(warehouseId, 'XX');
// andle cancel mark primary confirm.
const handleConfirmMarkPrimaryWarehouse = () => {
markPrimaryWarehouseMutate(warehouseId)

View File

@@ -1,71 +0,0 @@
import React from 'react';
import { FormattedMessage as T } from 'components';
import intl from 'react-intl-universal';
import { Intent, Alert } from '@blueprintjs/core';
import { useTransferredWarehouseTransfer } from 'hooks/query';
import { AppToaster } from 'components';
import withAlertStoreConnect from 'containers/Alert/withAlertStoreConnect';
import withAlertActions from 'containers/Alert/withAlertActions';
import { compose } from 'utils';
/**
* warehouse transfer transferred alert.
* @returns
*/
function TransferredWarehouseTransferAlert({
name,
// #withAlertStoreConnect
isOpen,
payload: { warehouseTransferId },
// #withAlertActions
closeAlert,
}) {
const { mutateAsync: transferredWarehouseTransferMutate, isLoading } =
useTransferredWarehouseTransfer();
// handle cancel alert.
const handleCancelAlert = () => {
closeAlert(name);
};
// Handle confirm alert.
const handleConfirmTransferred = () => {
transferredWarehouseTransferMutate(warehouseTransferId)
.then(() => {
AppToaster.show({
message: intl.get('warehouse_transfer.alert.transferred_warehouse'),
intent: Intent.SUCCESS,
});
})
.catch((error) => {})
.finally(() => {
closeAlert(name);
});
};
return (
<Alert
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={<T id={'deliver'} />}
intent={Intent.WARNING}
isOpen={isOpen}
onCancel={handleCancelAlert}
onConfirm={handleConfirmTransferred}
loading={isLoading}
>
<p>
<T id={'warehouse_transfer.alert.are_you_sure_you_want_to_deliver'} />
</p>
</Alert>
);
}
export default compose(
withAlertStoreConnect(),
withAlertActions,
)(TransferredWarehouseTransferAlert);

View File

@@ -1,71 +0,0 @@
import React from 'react';
import { FormattedMessage as T } from 'components';
import intl from 'react-intl-universal';
import { Intent, Alert } from '@blueprintjs/core';
import { useInitiateWarehouseTransfer } from 'hooks/query';
import { AppToaster } from 'components';
import withAlertStoreConnect from 'containers/Alert/withAlertStoreConnect';
import withAlertActions from 'containers/Alert/withAlertActions';
import { compose } from 'utils';
/**
* warehouse transfer initiate alert.
* @returns
*/
function WarehouseTransferInitiateAlert({
name,
// #withAlertStoreConnect
isOpen,
payload: { warehouseTransferId },
// #withAlertActions
closeAlert,
}) {
const { mutateAsync: initialWarehouseTransferMutate, isLoading } =
useInitiateWarehouseTransfer();
// handle cancel alert.
const handleCancelAlert = () => {
closeAlert(name);
};
// Handle confirm alert.
const handleConfirmInitiated = () => {
initialWarehouseTransferMutate(warehouseTransferId)
.then(() => {
AppToaster.show({
message: intl.get('warehouse_transfer.alert.initiate_warehouse'),
intent: Intent.SUCCESS,
});
})
.catch((error) => {})
.finally(() => {
closeAlert(name);
});
};
return (
<Alert
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={<T id={'warehouse_transfer.label.initiate'} />}
intent={Intent.WARNING}
isOpen={isOpen}
onCancel={handleCancelAlert}
onConfirm={handleConfirmInitiated}
loading={isLoading}
>
<p>
<T id={'warehouse_transfer.alert.are_you_sure_you_want_to_initate'} />
</p>
</Alert>
);
}
export default compose(
withAlertStoreConnect(),
withAlertActions,
)(WarehouseTransferInitiateAlert);

View File

@@ -16,9 +16,6 @@ import DashboardActionsBar from 'components/Dashboard/DashboardActionsBar';
import withDialogActions from 'containers/Dialog/withDialogActions';
import withCashflowAccountsTableActions from '../AccountTransactions/withCashflowAccountsTableActions';
import { AccountDialogAction } from '../../Dialogs/AccountDialog/utils';
import { ACCOUNT_TYPE } from '../../../common';
import { compose } from 'utils';
/**
@@ -40,15 +37,15 @@ function CashFlowAccountsActionsBar({
// Handle add bank account.
const handleAddBankAccount = () => {
openDialog('account-form', {
action: AccountDialogAction.NewDefinedType,
accountType: ACCOUNT_TYPE.CASH,
action: 'NEW_ACCOUNT_DEFINED_TYPE',
accountType: 'cash',
});
};
// Handle add cash account.
const handleAddCashAccount = () => {
openDialog('account-form', {
action: AccountDialogAction.NewDefinedType,
accountType: ACCOUNT_TYPE.BANK,
action: 'NEW_ACCOUNT_DEFINED_TYPE',
accountType: 'bank',
});
};
// Handle inactive switch changing.

View File

@@ -3,33 +3,32 @@ import classNames from 'classnames';
import { FormGroup, Position, Classes, ControlGroup } from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FastField, ErrorMessage } from 'formik';
import { FFormGroup } from '../../../components/Forms';
import moment from 'moment';
import { Features } from 'common';
import {
MoneyInputGroup,
InputPrependText,
CurrencySelectList,
BranchSelect,
BranchSelectButton,
FeatureCan,
Row,
Col,
} from 'components';
import { FormattedMessage as T } from 'components';
import { useCustomerFormContext } from './CustomerFormProvider';
import { useSetPrimaryBranchToForm } from './utils';
import { momentFormatter, tansformDateValue, inputIntent } from 'utils';
import {
momentFormatter,
tansformDateValue,
inputIntent,
} from 'utils';
/**
* Customer financial panel.
*/
export default function CustomerFinancialPanel() {
const { currencies, customerId, branches } = useCustomerFormContext();
// Sets the primary branch to form.
useSetPrimaryBranchToForm();
const {
currencies,
customerId
} = useCustomerFormContext();
return (
<div className={'tab-panel--financial'}>
@@ -63,7 +62,12 @@ export default function CustomerFinancialPanel() {
{/*------------ Opening balance -----------*/}
<FastField name={'opening_balance'}>
{({ form, field, field: { value }, meta: { error, touched } }) => (
{({
form,
field,
field: { value },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'opening_balance'} />}
className={classNames(
@@ -88,23 +92,6 @@ export default function CustomerFinancialPanel() {
)}
</FastField>
{/*------------ Opening branch -----------*/}
<FeatureCan feature={Features.Branches}>
<FFormGroup
label={<T id={'customer.label.opening_branch'} />}
name={'opening_balance_branch_id'}
inline={true}
className={classNames('form-group--select-list', Classes.FILL)}
>
<BranchSelect
name={'opening_balance_branch_id'}
branches={branches}
input={BranchSelectButton}
popoverProps={{ minimal: true }}
/>
</FFormGroup>
</FeatureCan>
{/*------------ Currency -----------*/}
<FastField name={'currency_code'}>
{({ form, field: { value }, meta: { error, touched } }) => (

View File

@@ -42,7 +42,6 @@ const Schema = Yup.object().shape({
opening_balance: Yup.number().nullable(),
currency_code: Yup.string(),
opening_balance_at: Yup.date(),
opening_balance_branch_id: Yup.string(),
});
export const CreateCustomerForm = Schema;

View File

@@ -6,20 +6,14 @@ import {
useCreateCustomer,
useEditCustomer,
useContact,
useBranches,
} from 'hooks/query';
import { Features } from 'common';
import { useFeatureCan } from 'hooks/state';
const CustomerFormContext = createContext();
function CustomerFormProvider({ query, customerId, ...props }) {
function CustomerFormProvider({ customerId, ...props }) {
const { state } = useLocation();
const contactId = state?.action;
// Features guard.
const { featureCan } = useFeatureCan();
const isBranchFeatureCan = featureCan(Features.Branches);
const contactId = state?.action;
// Handle fetch customer details.
const { data: customer, isLoading: isCustomerLoading } = useCustomer(
@@ -34,13 +28,6 @@ function CustomerFormProvider({ query, customerId, ...props }) {
// Handle fetch Currencies data table
const { data: currencies, isLoading: isCurrenciesLoading } = useCurrencies();
// Fetches the branches list.
const {
data: branches,
isLoading: isBranchesLoading,
isSuccess: isBranchesSuccess,
} = useBranches(query, { enabled: isBranchFeatureCan });
// Form submit payload.
const [submitPayload, setSubmitPayload] = useState({});
@@ -51,20 +38,18 @@ function CustomerFormProvider({ query, customerId, ...props }) {
const isNewMode = contactId || !customerId;
const isFormLoading =
isCustomerLoading || isCurrenciesLoading || isBranchesLoading;
isCustomerLoading || isCurrenciesLoading || isContactLoading;
const provider = {
customerId,
customer,
currencies,
branches,
contactDuplicate,
submitPayload,
isNewMode,
isCustomerLoading,
isCurrenciesLoading,
isBranchesSuccess,
isFormLoading,
setSubmitPayload,

View File

@@ -1,9 +1,5 @@
import React from 'react';
import moment from 'moment';
import { useFormikContext } from 'formik';
import { first } from 'lodash';
import { useCustomerFormContext } from './CustomerFormProvider';
export const defaultInitialValues = {
customer_type: 'business',
@@ -39,20 +35,4 @@ export const defaultInitialValues = {
opening_balance: '',
currency_code: '',
opening_balance_at: moment(new Date()).format('YYYY-MM-DD'),
opening_balance_branch_id: '',
};
export const useSetPrimaryBranchToForm = () => {
const { setFieldValue } = useFormikContext();
const { branches, isBranchesSuccess } = useCustomerFormContext();
React.useEffect(() => {
if (isBranchesSuccess) {
const primaryBranch = branches.find((b) => b.primary) || first(branches);
if (primaryBranch) {
setFieldValue('opening_balance_branch_id', primaryBranch.id);
}
}
}, [isBranchesSuccess, setFieldValue, branches]);
};

View File

@@ -5,9 +5,21 @@ import AccountDialogForm from './AccountDialogForm';
/**
* Account dialog content.
*/
export default function AccountDialogContent({ dialogName, payload }) {
export default function AccountDialogContent({
dialogName,
accountId,
action,
parentAccountId,
accountType,
}) {
return (
<AccountDialogProvider dialogName={dialogName} payload={payload}>
<AccountDialogProvider
dialogName={dialogName}
accountId={accountId}
action={action}
parentAccountId={parentAccountId}
accountType={accountType}
>
<AccountDialogForm />
</AccountDialogProvider>
);

View File

@@ -25,7 +25,6 @@ const defaultInitialValues = {
name: '',
code: '',
description: '',
currency_code:'',
subaccount: false,
};
@@ -43,7 +42,9 @@ function AccountFormDialogContent({
account,
accountId,
payload,
action,
parentAccountId,
accountType,
isNewMode,
dialogName,
} = useAccountDialogContext();
@@ -99,6 +100,7 @@ function AccountFormDialogContent({
.catch(handleError);
}
};
// Form initial values in create and edit mode.
const initialValues = {
...defaultInitialValues,
@@ -108,7 +110,11 @@ function AccountFormDialogContent({
* as well.
*/
...transformToForm(
transformAccountToForm(account, payload),
transformAccountToForm(account, {
action,
parentAccountId,
accountType,
}),
defaultInitialValues,
),
};
@@ -126,7 +132,7 @@ function AccountFormDialogContent({
>
<AccountDialogFormContent
dialogName={dialogName}
action={payload?.action}
action={action}
onClose={handleClose}
/>
</Formik>

View File

@@ -17,14 +17,12 @@ import {
Hint,
AccountsSelectList,
AccountsTypesSelect,
CurrencySelect,
} from 'components';
import withAccounts from 'containers/Accounts/withAccounts';
import { inputIntent } from 'utils';
import { compose } from 'redux';
import { useAutofocus } from 'hooks';
import { FOREIGN_CURRENCY_ACCOUNTS } from '../../../common/accountTypes';
import { useAccountDialogContext } from './AccountDialogProvider';
/**
@@ -39,8 +37,7 @@ function AccountFormDialogFields({
const accountNameFieldRef = useAutofocus();
// Account form context.
const { fieldsDisabled, accounts, accountsTypes, currencies } =
useAccountDialogContext();
const { accounts, accountsTypes } = useAccountDialogContext();
return (
<Form>
@@ -61,9 +58,12 @@ function AccountFormDialogFields({
defaultSelectText={<T id={'select_account_type'} />}
onTypeSelected={(accountType) => {
form.setFieldValue('account_type', accountType.key);
form.setFieldValue('currency_code', '');
}}
disabled={fieldsDisabled.accountType}
disabled={
action === 'edit' ||
action === 'new_child' ||
action === 'NEW_ACCOUNT_DEFINED_TYPE'
}
popoverProps={{ minimal: true }}
popoverFill={true}
/>
@@ -143,7 +143,6 @@ function AccountFormDialogFields({
)}
inline={true}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="parent_account_id" />}
>
<AccountsSelectList
accounts={accounts}
@@ -160,24 +159,6 @@ function AccountFormDialogFields({
</FastField>
</If>
<If condition={FOREIGN_CURRENCY_ACCOUNTS.includes(values.account_type)}>
{/*------------ Currency -----------*/}
<FastField name={'currency_code'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'currency'} />}
className={classNames('form-group--select-list', Classes.FILL)}
inline={true}
>
<CurrencySelect
name={'currency_code'}
currencies={currencies}
popoverProps={{ minimal: true }}
/>
</FormGroup>
)}
</FastField>
</If>
<FastField name={'description'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
@@ -206,7 +187,7 @@ function AccountFormDialogFields({
<Button
intent={Intent.PRIMARY}
loading={isSubmitting}
style={{ minWidth: '95px' }}
style={{ minWidth: '75px' }}
type="submit"
>
{action === 'edit' ? <T id={'edit'} /> : <T id={'submit'} />}

View File

@@ -3,19 +3,25 @@ import { DialogContent } from 'components';
import {
useCreateAccount,
useAccountsTypes,
useCurrencies,
useAccount,
useAccounts,
useEditAccount,
} from 'hooks/query';
import { AccountDialogAction, getDisabledFormFields } from './utils';
const AccountDialogContext = createContext();
/**
* Account form provider.
*/
function AccountDialogProvider({ dialogName, payload, ...props }) {
function AccountDialogProvider({
accountId,
parentAccountId,
action,
accountType,
dialogName,
...props
}) {
// Create and edit account mutations.
const { mutateAsync: createAccountMutate } = useCreateAccount();
const { mutateAsync: editAccountMutate } = useEditAccount();
@@ -24,36 +30,25 @@ function AccountDialogProvider({ dialogName, payload, ...props }) {
const { data: accounts, isLoading: isAccountsLoading } = useAccounts();
// Fetches accounts types.
const { data: accountsTypes, isLoading: isAccountsTypesLoading } =
useAccountsTypes();
const {
data: accountsTypes,
isLoading: isAccountsTypesLoading,
} = useAccountsTypes();
// Fetches the specific account details.
const { data: account, isLoading: isAccountLoading } = useAccount(
payload.accountId,
{
enabled:
!!payload.accountId && payload.action === AccountDialogAction.Edit,
},
);
const { data: account, isLoading: isAccountLoading } = useAccount(accountId, {
enabled: !!accountId,
});
// Handle fetch Currencies data table
const { data: currencies, isLoading: isCurrenciesLoading } = useCurrencies();
const isNewMode = !payload?.action;
// Retrieves the disabled fields of the form.
const fieldsDisabled = React.useMemo(
() => getDisabledFormFields(account, payload),
[account, payload],
);
const isNewMode = !accountId;
// Provider payload.
const provider = {
dialogName,
payload,
fieldsDisabled,
currencies,
accountId,
parentAccountId,
action,
accountType,
createAccountMutate,
editAccountMutate,
@@ -62,15 +57,11 @@ function AccountDialogProvider({ dialogName, payload, ...props }) {
account,
isAccountsLoading,
isCurrenciesLoading,
isNewMode,
isNewMode
};
const isLoading =
isAccountsLoading ||
isAccountsTypesLoading ||
isAccountLoading ||
isCurrenciesLoading;
isAccountsLoading || isAccountsTypesLoading || isAccountLoading;
return (
<DialogContent isLoading={isLoading}>

View File

@@ -18,11 +18,9 @@ function AccountFormDialog({
<Dialog
name={dialogName}
title={
payload.action === 'edit' ? (
<T id={'edit_account'} />
) : (
<T id={'new_account'} />
)
(payload.action === 'edit') ?
(<T id={'edit_account'} />) :
(<T id={'new_account'} />)
}
className={'dialog--account-form'}
autoFocus={true}
@@ -30,10 +28,18 @@ function AccountFormDialog({
isOpen={isOpen}
>
<DialogSuspense>
<AccountDialogContent dialogName={dialogName} payload={payload} />
<AccountDialogContent
dialogName={dialogName}
accountId={payload.id}
action={payload.action}
parentAccountId={payload.parentAccountId}
accountType={payload.accountType}
/>
</DialogSuspense>
</Dialog>
);
}
export default compose(withDialogRedux())(AccountFormDialog);
export default compose(
withDialogRedux(),
)(AccountFormDialog);

View File

@@ -1,17 +1,7 @@
import intl from 'react-intl-universal';
import * as R from 'ramda';
import { isUndefined } from 'lodash';
import { isEmpty } from 'lodash';
//
export const AccountDialogAction = {
Edit: 'edit',
NewChild: 'NewChild',
NewDefinedType: 'NewDefinedType',
};
/**
* Transformes the response API errors.
*/
export const transformApiErrors = (errors) => {
const fields = {};
if (errors.find((e) => e.type === 'NOT_UNIQUE_CODE')) {
@@ -20,20 +10,13 @@ export const transformApiErrors = (errors) => {
if (errors.find((e) => e.type === 'ACCOUNT.NAME.NOT.UNIQUE')) {
fields.name = intl.get('account_name_is_already_used');
}
if (
errors.find((e) => e.type === 'ACCOUNT_CURRENCY_NOT_SAME_PARENT_ACCOUNT')
) {
fields.parent_account_id = intl.get(
'accounts.error.account_currency_not_same_parent_account',
);
}
return fields;
};
/**
* Payload transformer in account edit mode.
*/
function tranformNewChildAccountPayload(payload) {
function transformEditMode(payload) {
return {
parent_account_id: payload.parentAccountId || '',
account_type: payload.accountType || '',
@@ -44,7 +27,7 @@ function tranformNewChildAccountPayload(payload) {
/**
* Payload transformer in new account with defined type.
*/
function transformNewDefinedTypePayload(payload) {
function transformNewAccountDefinedType(payload) {
return {
account_type: payload.accountType || '',
};
@@ -70,9 +53,9 @@ const defaultPayloadTransform = () => ({});
*/
function getConditions() {
return [
[AccountDialogAction.Edit],
[AccountDialogAction.NewChild, tranformNewChildAccountPayload],
[AccountDialogAction.NewDefinedType, transformNewDefinedTypePayload],
['edit'],
['new_child', transformEditMode],
['NEW_ACCOUNT_DEFINED_TYPE', transformNewAccountDefinedType],
];
}
@@ -83,7 +66,7 @@ export const transformAccountToForm = (account, payload) => {
const conditions = getConditions();
const results = conditions.map((condition) => {
const transformer = !isUndefined(condition[1])
const transformer = !isEmpty(condition[1])
? condition[1]
: defaultPayloadTransform;
@@ -94,15 +77,3 @@ export const transformAccountToForm = (account, payload) => {
});
return R.cond(results)(account);
};
/**
* Detarmines whether the for fields are disabled.
*/
export const getDisabledFormFields = (account, payload) => {
return {
accountType:
payload.action === AccountDialogAction.Edit ||
payload.action === AccountDialogAction.NewChild ||
payload.action === AccountDialogAction.NewDefinedType,
};
};

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