Merge remote-tracking branch 'origin/feature/exchange_rates'

This commit is contained in:
Ahmed Bouhuolia
2020-05-12 01:10:11 +02:00
62 changed files with 2587 additions and 1155 deletions

View File

@@ -6,6 +6,7 @@ import {
} from '@blueprintjs/core';
// import {Select} from '@blueprintjs/select';
import MultiSelect from 'components/MultiSelect';
import { FormattedMessage as T, useIntl } from 'react-intl';
export default function AccountsMultiSelect({
accounts,
@@ -58,7 +59,7 @@ export default function AccountsMultiSelect({
<Button
rightIcon='caret-down'
text={countSelectedAccounts === 0 ?
'All accounts' :
<T id={'all_accounts'}/>:
`(${countSelectedAccounts}) Selected accounts`
}
/>

View File

@@ -36,7 +36,6 @@ export default function AccountsSelectList({
filterable={true}
onItemSelect={onAccountSelect}>
<Button
rightIcon='caret-down'
text={selectedAccount ? selectedAccount.name : defautlSelectText}
/>
</Select>

View File

@@ -1,26 +1,32 @@
import React from 'react';
import { Redirect, Route, Switch, Link } from 'react-router-dom';
import BodyClassName from 'react-body-classname';
import BodyClassName from 'react-body-classname';
import authenticationRoutes from 'routes/authentication';
import { FormattedMessage as T, useIntl } from 'react-intl';
export default function AuthenticationWrapper({ isAuthenticated =false, ...rest }) {
const to = {pathname: '/dashboard/homepage'};
export default function AuthenticationWrapper({
isAuthenticated = false,
...rest
}) {
const to = { pathname: '/dashboard/homepage' };
return (
<Route path="/auth">
{ (isAuthenticated) ?
(<Redirect to={to} />) : (
<Route path='/auth'>
{isAuthenticated ? (
<Redirect to={to} />
) : (
<BodyClassName className={'authentication'}>
<Switch>
<div class="authentication-page">
<div class='authentication-page'>
<Link
to={'bigcapital.io'}
className={'authentication-page__goto-bigcapital'}>
Go to bigcapital.com
className={'authentication-page__goto-bigcapital'}
>
<T id={'go_to_bigcapital_com'} />
</Link>
<div class="authentication-page__form-wrapper">
{ authenticationRoutes.map((route, index) => (
<div class='authentication-page__form-wrapper'>
{authenticationRoutes.map((route, index) => (
<Route
key={index}
path={route.path}
@@ -32,8 +38,7 @@ export default function AuthenticationWrapper({ isAuthenticated =false, ...rest
</div>
</Switch>
</BodyClassName>
)
}
)}
</Route>
);
}
}

View File

@@ -10,6 +10,7 @@ import {
Select
} from '@blueprintjs/select';
import { FormattedMessage as T, useIntl } from 'react-intl';
export default function CurrenciesSelectList(props) {
const {formGroupProps, selectProps, onItemSelect} = props;
@@ -39,7 +40,7 @@ export default function CurrenciesSelectList(props) {
return (
<FormGroup
label={'Currency'}
label={<T id={'currency'}/>}
className={'form-group--select-list form-group--currency'}
{...formGroupProps}
>

View File

@@ -12,6 +12,7 @@ import DashboardTopbarUser from 'components/Dashboard/TopbarUser';
import Icon from 'components/Icon';
import SearchConnect from 'connectors/Search.connect';
import { compose } from 'utils';
import { FormattedMessage as T, useIntl } from 'react-intl';
function DashboardTopbar({
pageTitle,
@@ -77,18 +78,18 @@ function DashboardTopbar({
onClick={() => openGlobalSearch(true)}
className={Classes.MINIMAL}
icon='home'
text='Search'
text={<T id={'search'}/>}
/>
<Button
className={Classes.MINIMAL}
icon='document'
text='Filters'
text={<T id={'filters'}/>}
/>
<Button
className={Classes.MINIMAL}
icon='document'
text='Add order'
text={<T id={'add_order'}/>}
/>
<Button className={Classes.MINIMAL} icon='document' text='More' />
</NavbarGroup>

View File

@@ -4,10 +4,12 @@ import UserFormDialog from 'containers/Dialogs/UserFormDialog';
import ItemCategoryDialog from 'containers/Dialogs/ItemCategoryDialog';
import CurrencyDialog from 'containers/Dialogs/CurrencyDialog';
import InviteUserDialog from 'containers/Dialogs/InviteUserDialog';
import ExchangeRateDialog from 'containers/Dialogs/ExchangeRateDialog';
export default function DialogsContainer() {
return (
<React.Fragment>
<ExchangeRateDialog />
<InviteUserDialog />
<CurrencyDialog />
<ItemCategoryDialog />

View File

@@ -13,7 +13,7 @@ import {
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { Select } from '@blueprintjs/select';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { momentFormatter } from 'utils';
import moment from 'moment';
import AppToaster from 'components/AppToaster';
@@ -25,8 +25,7 @@ export default function ExpenseForm({
expenseDetails,
currencies
}) {
const intl = useIntl();
console.log({ accounts });
const {formatMessage} = useIntl();
const [state, setState] = useState({
selectedExpenseAccount: null,
@@ -121,7 +120,7 @@ export default function ExpenseForm({
<div class='expense-form'>
<form onSubmit={formik.handleSubmit}>
<FormGroup
label={'Date'}
label={<T id={'date'}/>}
inline={true}
intent={formik.errors.date && Intent.DANGER}
helperText={formik.errors.date && formik.errors.date}
@@ -135,7 +134,7 @@ export default function ExpenseForm({
</FormGroup>
<FormGroup
label={'Expense Account'}
label={<T id={'expense_account'}/>}
className={'form-group--expense-account'}
inline={true}
intent={formik.errors.expense_account_id && Intent.DANGER}
@@ -159,7 +158,7 @@ export default function ExpenseForm({
</FormGroup>
<FormGroup
label={'Amount'}
label={<T id={'amount'}/>}
className={'form-group--amount'}
intent={formik.errors.amount && Intent.DANGER}
helperText={formik.errors.amount && formik.errors.amount}
@@ -191,7 +190,7 @@ export default function ExpenseForm({
</FormGroup>
<FormGroup
label={'Exchange Rate'}
label={<T id={'exchange_rate'}/>}
className={'form-group--exchange-rate'}
inline={true}
>
@@ -199,7 +198,7 @@ export default function ExpenseForm({
</FormGroup>
<FormGroup
label={'Payment Account'}
label={<T id={'payment_account'}/>}
className={'form-group--payment-account'}
inline={true}
intent={formik.errors.payment_account_id && Intent.DANGER}
@@ -223,7 +222,7 @@ export default function ExpenseForm({
</FormGroup>
<FormGroup
label={'Description'}
label={<T id={'description'}/>}
className={'form-group--description'}
inline={true}
>
@@ -236,10 +235,10 @@ export default function ExpenseForm({
<div class='form__floating-footer'>
<Button intent={Intent.PRIMARY} type='submit'>
Save
<T id={'save'}/>
</Button>
<Button>Save as Draft</Button>
<Button onClick={handleClose}>Close</Button>
<Button><T id={'save_as_draft'}/></Button>
<Button onClick={handleClose}><T id={'close'}/></Button>
</div>
</form>
</div>

View File

@@ -16,6 +16,7 @@ import { useRouteMatch } from 'react-router-dom'
import classNames from 'classnames';
import DashboardActionsBar from 'components/Dashboard/DashboardActionsBar';
import Icon from 'components/Icon';
import { FormattedMessage as T, useIntl } from 'react-intl';
export default function ExpensesActionsBar({
@@ -39,7 +40,7 @@ export default function ExpensesActionsBar({
<Button
className={classNames(Classes.MINIMAL, 'button--table-views')}
icon={<Icon icon='table' />}
text='Table Views'
text={<T id={'table_views'}/>}
rightIcon={'caret-down'}
/>
</Popover>
@@ -50,31 +51,31 @@ export default function ExpensesActionsBar({
className={Classes.MINIMAL}
icon={<Icon icon='plus' />}
href='/dashboard/expenses/new'
text='New Expense'
text={<T id={'new_expense'}/>}
onClick={onClickNewAccount}
/>
<Button
className={Classes.MINIMAL}
intent={Intent.DANGER}
icon={<Icon icon='plus' />}
text='Delete'
text={<T id={'delete'}/>}
onClick={onClickNewAccount}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='plus' />}
text='Bulk Update'
text={<T id={'bulk_update'}/>}
onClick={onClickNewAccount}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-import' />}
text='Import'
text={<T id={'import'}/>}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-export' />}
text='Export'
text={<T id={'export'}/>}
/>
</NavbarGroup>
</DashboardActionsBar>

View File

@@ -13,6 +13,7 @@ import { usePrevious } from 'react-use';
import { debounce } from 'lodash';
import Icon from 'components/Icon';
import { checkRequiredProperties } from 'utils';
import { FormattedMessage as T, useIntl } from 'react-intl';
export default function FilterDropdown({
fields,
@@ -146,7 +147,7 @@ export default function FilterDropdown({
minimal={true}
intent={Intent.PRIMARY}
onClick={onClickNewFilter}>
+ New Conditional
<T id={'new_conditional'}/>
</Button>
</div>
</div>

View File

@@ -1,9 +1,11 @@
import If from './Utils/If';
import Money from './Money';
// import Choose from './Utils/Choose';
// import For from './Utils/For';
export {
If,
Money,
// Choose,
// For,
};

View File

@@ -1,17 +1,17 @@
export default [
{
divider: true
divider: true,
},
{
icon: 'homepage',
iconSize: 20,
text: 'Homepage',
disabled: false,
href: '/dashboard/homepage'
href: '/dashboard/homepage',
},
{
divider: true
divider: true,
},
{
icon: 'homepage',
@@ -20,20 +20,20 @@ export default [
children: [
{
text: 'Items List',
href: '/dashboard/items'
href: '/dashboard/items',
},
{
text: 'New Item',
href: '/dashboard/items/new'
href: '/dashboard/items/new',
},
{
text: 'Category List',
href: '/dashboard/items/categories'
href: '/dashboard/items/categories',
},
]
],
},
{
divider: true
divider: true,
},
{
icon: 'balance-scale',
@@ -42,29 +42,33 @@ export default [
children: [
{
text: 'Accounts Chart',
href: '/dashboard/accounts'
href: '/dashboard/accounts',
},
{
text: 'Manual Journal',
href: '/dashboard/accounting/manual-journals'
href: '/dashboard/accounting/manual-journals',
},
{
text: 'Make Journal',
href: '/dashboard/accounting/make-journal-entry'
href: '/dashboard/accounting/make-journal-entry',
},
]
{
text: 'Exchange Rate',
href: '/dashboard/ExchangeRates',
},
],
},
{
icon: 'university',
iconSize: 20,
text: 'Banking',
children: []
children: [],
},
{
icon: 'shopping-cart',
iconSize: 20,
text: 'Sales',
children: []
children: [],
},
{
icon: 'balance-scale',
@@ -75,9 +79,9 @@ export default [
icon: 'cut',
text: 'cut',
label: '⌘C',
disabled: false
}
]
disabled: false,
},
],
},
{
icon: 'analytics',
@@ -86,25 +90,25 @@ export default [
children: [
{
text: 'Balance Sheet',
href: '/dashboard/accounting/balance-sheet'
href: '/dashboard/accounting/balance-sheet',
},
{
text: 'Trial Balance Sheet',
href: '/dashboard/accounting/trial-balance-sheet'
href: '/dashboard/accounting/trial-balance-sheet',
},
{
text: 'Journal',
href: '/dashboard/accounting/journal-sheet'
href: '/dashboard/accounting/journal-sheet',
},
{
text: 'General Ledger',
href: '/dashboard/accounting/general-ledger'
href: '/dashboard/accounting/general-ledger',
},
{
text: 'Profit Loss Sheet',
href: '/dashboard/accounting/profit-loss-sheet'
}
]
href: '/dashboard/accounting/profit-loss-sheet',
},
],
},
{
text: 'Expenses',
@@ -113,23 +117,23 @@ export default [
children: [
{
text: 'Expenses List',
href: '/dashboard/expenses'
href: '/dashboard/expenses',
},
{
text: 'New Expenses',
href: '/dashboard/expenses/new'
}
]
href: '/dashboard/expenses/new',
},
],
},
{
divider: true
divider: true,
},
{
text: 'Preferences',
href: '/dashboard/preferences'
href: '/dashboard/preferences',
},
{
text: 'Auditing System',
href: '/dashboard/auditing/list'
}
href: '/dashboard/auditing/list',
},
];

View File

@@ -1,9 +1,6 @@
import React, {useMemo} from 'react';
import {
Intent,
Button,
} from '@blueprintjs/core';
import { FormattedList } from 'react-intl';
import React, { useMemo } from 'react';
import { Intent, Button } from '@blueprintjs/core';
import { FormattedMessage as T, useIntl } from 'react-intl';
export default function MakeJournalEntriesFooter({
formik: { isSubmitting },
@@ -12,15 +9,16 @@ export default function MakeJournalEntriesFooter({
}) {
return (
<div>
<div class="form__floating-footer">
<div class='form__floating-footer'>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
name={'save'}
onClick={() => {
onSubmitClick({ publish: true, redirect: true });
}}>
Save
}}
>
<T id={'save'} />
</Button>
<Button
@@ -29,28 +27,31 @@ export default function MakeJournalEntriesFooter({
className={'ml1'}
name={'save_and_new'}
onClick={() => {
onSubmitClick({ publish: true, redirect: false });
}}>
Save & New
onSubmitClick({ publish: true, redirect: false });
}}
>
<T id={'save_new'} />
</Button>
<Button
disabled={isSubmitting}
className={'button-secondary ml1'}
onClick={() => {
onSubmitClick({ publish: false, redirect: false });
}}>
Save as Draft
onSubmitClick({ publish: false, redirect: false });
}}
>
<T id={'save_as_draft'} />
</Button>
<Button
className={'button-secondary ml1'}
onClick={() => {
onCancelClick && onCancelClick();
}}>
Cancel
}}
>
<T id={'cancel'}/>
</Button>
</div>
</div>
);
}
}

View File

@@ -1,9 +1,10 @@
import React, {useMemo, useState, useEffect, useRef, useCallback} from 'react';
import * as Yup from 'yup';
import {useFormik} from "formik";
import { useFormik } from "formik";
import moment from 'moment';
import { Intent } from '@blueprintjs/core';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { pick } from 'lodash';
import MakeJournalEntriesHeader from './MakeJournalEntriesHeader';
import MakeJournalEntriesFooter from './MakeJournalEntriesFooter';
@@ -15,7 +16,6 @@ import withAccountsActions from 'containers/Accounts/withAccountsActions';
import withDashboardActions from 'containers/Dashboard/withDashboard';
import AppToaster from 'components/AppToaster';
import {pick} from 'lodash';
import Dragzone from 'components/Dragzone';
import MediaConnect from 'connectors/Media.connect';
@@ -55,10 +55,10 @@ function MakeJournalEntriesForm({
useEffect(() => {
if (manualJournal && manualJournal.id) {
changePageTitle('Edit Journal');
changePageTitle(formatMessage({id:'edit_journal'}));
changePageSubtitle(`No. ${manualJournal.journal_number}`);
} else {
changePageTitle('New Journal');
changePageTitle(formatMessage({id:'new_journal'}));
}
}, [changePageTitle, changePageSubtitle, manualJournal]);

View File

@@ -6,7 +6,7 @@ import {
Position,
} from '@blueprintjs/core';
import {DateInput} from '@blueprintjs/datetime';
import {useIntl} from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import {Row, Col} from 'react-grid-system';
import moment from 'moment';
import {momentFormatter} from 'utils';
@@ -17,7 +17,7 @@ import ErrorMessage from 'components/ErrorMessage';
export default function MakeJournalEntriesHeader({
formik: { errors, touched, setFieldValue, getFieldProps }
}) {
const intl = useIntl();
const {formatMessage} = useIntl();
const handleDateChange = useCallback((date) => {
const formatted = moment(date).format('YYYY-MM-DD');
@@ -32,7 +32,7 @@ export default function MakeJournalEntriesHeader({
<Row>
<Col sm={3}>
<FormGroup
label={'Journal number'}
label={<T id={'journal_number'}/>}
labelInfo={infoIcon}
className={'form-group--journal-number'}
intent={(errors.journal_number && touched.journal_number) && Intent.DANGER}
@@ -48,7 +48,7 @@ export default function MakeJournalEntriesHeader({
<Col sm={2}>
<FormGroup
label={intl.formatMessage({'id': 'date'})}
label={<T id={'date'}/>}
intent={(errors.date && touched.date) && Intent.DANGER}
helperText={<ErrorMessage name="date" {...{errors, touched}} />}
minimal={true}>
@@ -63,7 +63,7 @@ export default function MakeJournalEntriesHeader({
<Col sm={4}>
<FormGroup
label={intl.formatMessage({'id': 'description'})}
label={<T id={'description'}/>}
className={'form-group--description'}
intent={(errors.name && touched.name) && Intent.DANGER}
helperText={<ErrorMessage name="description" {...{errors, touched}} />}
@@ -80,7 +80,7 @@ export default function MakeJournalEntriesHeader({
<Row>
<Col sm={3}>
<FormGroup
label={'Reference'}
label={<T id={'reference'}/>}
labelInfo={infoIcon}
className={'form-group--reference'}
intent={(errors.reference && touched.reference) && Intent.DANGER}

View File

@@ -1,11 +1,8 @@
import React, {useState, useMemo, useEffect, useCallback} from 'react';
import {
Button,
Intent,
} from '@blueprintjs/core';
import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { Button, Intent } from '@blueprintjs/core';
import DataTable from 'components/DataTable';
import Icon from 'components/Icon';
import { compose, formattedAmount} from 'utils';
import { compose, formattedAmount } from 'utils';
import {
AccountsListFieldCell,
MoneyFieldCell,
@@ -14,7 +11,7 @@ import {
import { omit } from 'lodash';
import withAccounts from 'containers/Accounts/withAccounts';
import { FormattedMessage as T, useIntl } from 'react-intl';
// Actions cell renderer.
const ActionsCellRenderer = ({
@@ -24,55 +21,54 @@ const ActionsCellRenderer = ({
data,
payload,
}) => {
if (data.length <= (index + 2)) {
if (data.length <= index + 2) {
return '';
}
const onClickRemoveRole = () => {
payload.removeRow(index);
};
return (
<Button
icon={<Icon icon="times-circle" iconSize={14} />}
<Button
icon={<Icon icon='times-circle' iconSize={14} />}
iconSize={14}
className="ml2"
className='ml2'
minimal={true}
intent={Intent.DANGER}
onClick={onClickRemoveRole} />
onClick={onClickRemoveRole}
/>
);
};
// Total text cell renderer.
const TotalAccountCellRenderer = (chainedComponent) => (props) => {
if (props.data.length === (props.row.index + 2)) {
return (<span>{ 'Total USD' }</span>);
if (props.data.length === props.row.index + 2) {
return <span>{'Total USD'}</span>;
}
return chainedComponent(props);
};
// Total credit/debit cell renderer.
const TotalCreditDebitCellRenderer = (chainedComponent, type) => (props) => {
if (props.data.length === (props.row.index + 2)) {
const total = props.data.reduce((total, entry) => {
if (props.data.length === props.row.index + 2) {
const total = props.data.reduce((total, entry) => {
const amount = parseInt(entry[type], 10);
const computed = amount ? total + amount : total;
return computed;
}, 0);
return (<span>{ formattedAmount(total, 'USD') }</span>);
return <span>{formattedAmount(total, 'USD')}</span>;
}
return chainedComponent(props);
};
const NoteCellRenderer = (chainedComponent) => (props) => {
if (props.data.length === (props.row.index + 2)) {
if (props.data.length === props.row.index + 2) {
return '';
}
return chainedComponent(props);
};
/**
* Make journal entries table component.
*/
@@ -88,116 +84,128 @@ function MakeJournalEntriesTable({
formik: { errors, values, setFieldValue },
}) {
const [rows, setRow] = useState([]);
useEffect(() => {
const { formatMessage } = useIntl();
useEffect(() => {
setRow([
...initialValues.entries.map((e) => ({ ...e, rowType: 'editor'})),
...initialValues.entries.map((e) => ({ ...e, rowType: 'editor' })),
defaultRow,
defaultRow,
])
}, [initialValues, defaultRow])
]);
}, [initialValues, defaultRow]);
// Handles update datatable data.
const handleUpdateData = useCallback((rowIndex, columnId, value) => {
const newRows = rows.map((row, index) => {
if (index === rowIndex) {
return { ...rows[rowIndex], [columnId]: value };
}
return { ...row };
});
setRow(newRows);
setFieldValue('entries', newRows.map(row => ({
...omit(row, ['rowType']),
})));
}, [rows, setFieldValue]);
const handleUpdateData = useCallback(
(rowIndex, columnId, value) => {
const newRows = rows.map((row, index) => {
if (index === rowIndex) {
return { ...rows[rowIndex], [columnId]: value };
}
return { ...row };
});
setRow(newRows);
setFieldValue(
'entries',
newRows.map((row) => ({
...omit(row, ['rowType']),
}))
);
},
[rows, setFieldValue]
);
// Handles click remove datatable row.
const handleRemoveRow = useCallback((rowIndex) => {
const removeIndex = parseInt(rowIndex, 10);
const newRows = rows.filter((row, index) => index !== removeIndex);
setRow([ ...newRows ]);
setFieldValue('entries', newRows
.filter(row => row.rowType === 'editor')
.map(row => ({ ...omit(row, ['rowType']) })
));
onClickRemoveRow && onClickRemoveRow(removeIndex);
}, [rows, setFieldValue, onClickRemoveRow]);
const handleRemoveRow = useCallback(
(rowIndex) => {
const removeIndex = parseInt(rowIndex, 10);
const newRows = rows.filter((row, index) => index !== removeIndex);
setRow([...newRows]);
setFieldValue(
'entries',
newRows
.filter((row) => row.rowType === 'editor')
.map((row) => ({ ...omit(row, ['rowType']) }))
);
onClickRemoveRow && onClickRemoveRow(removeIndex);
},
[rows, setFieldValue, onClickRemoveRow]
);
// Memorized data table columns.
const columns = useMemo(() => [
{
Header: '#',
accessor: 'index',
Cell: ({ row: {index} }) => (
<span>{ index + 1 }</span>
),
className: "index",
width: 40,
disableResizing: true,
disableSortBy: true,
},
{
Header: 'Account',
id: 'account_id',
accessor: 'account_id',
Cell: TotalAccountCellRenderer(AccountsListFieldCell),
className: "account",
disableSortBy: true,
disableResizing: true,
width: 250,
},
{
Header: 'Credit (USD)',
accessor: 'credit',
Cell: TotalCreditDebitCellRenderer(MoneyFieldCell, 'credit'),
className: "credit",
disableSortBy: true,
disableResizing: true,
width: 150,
},
{
Header: 'Debit (USD)',
accessor: 'debit',
Cell: TotalCreditDebitCellRenderer(MoneyFieldCell, 'debit'),
className: "debit",
disableSortBy: true,
disableResizing: true,
width: 150,
},
{
Header: 'Note',
accessor: 'note',
Cell: NoteCellRenderer(InputGroupCell),
disableSortBy: true,
className: "note",
},
{
Header: '',
accessor: 'action',
Cell: ActionsCellRenderer,
className: "actions",
disableSortBy: true,
disableResizing: true,
width: 45,
}
], []);
const columns = useMemo(
() => [
{
Header: '#',
accessor: 'index',
Cell: ({ row: { index } }) => <span>{index + 1}</span>,
className: 'index',
width: 40,
disableResizing: true,
disableSortBy: true,
},
{
Header: formatMessage({ id: 'account' }),
id: 'account_id',
accessor: 'account_id',
Cell: TotalAccountCellRenderer(AccountsListFieldCell),
className: 'account',
disableSortBy: true,
disableResizing: true,
width: 250,
},
{
Header: formatMessage({ id: 'credit_currency' }, { currency: 'USD' }),
accessor: 'credit',
Cell: TotalCreditDebitCellRenderer(MoneyFieldCell, 'credit'),
className: 'credit',
disableSortBy: true,
disableResizing: true,
width: 150,
},
{
Header: formatMessage({ id: 'debit_currency' }, { currency: 'USD' }),
accessor: 'debit',
Cell: TotalCreditDebitCellRenderer(MoneyFieldCell, 'debit'),
className: 'debit',
disableSortBy: true,
disableResizing: true,
width: 150,
},
{
Header: formatMessage({ id: 'note' }),
accessor: 'note',
Cell: NoteCellRenderer(InputGroupCell),
disableSortBy: true,
className: 'note',
},
{
Header: '',
accessor: 'action',
Cell: ActionsCellRenderer,
className: 'actions',
disableSortBy: true,
disableResizing: true,
width: 45,
},
],
[]
);
// Handles click new line.
const onClickNewRow = useCallback(() => {
setRow([
...rows,
{ ...defaultRow, rowType: 'editor' },
]);
setRow([...rows, { ...defaultRow, rowType: 'editor' }]);
onClickAddNewRow && onClickAddNewRow();
}, [defaultRow, rows, onClickAddNewRow]);
const rowClassNames = useCallback((row) => ({
'row--total': rows.length === (row.index + 2),
}), [rows]);
const rowClassNames = useCallback(
(row) => ({
'row--total': rows.length === row.index + 2,
}),
[rows]
);
return (
<div class="make-journal-entries__table">
<div class='make-journal-entries__table'>
<DataTable
columns={columns}
data={rows}
@@ -207,21 +215,24 @@ function MakeJournalEntriesTable({
errors: errors.entries || [],
updateData: handleUpdateData,
removeRow: handleRemoveRow,
}}/>
}}
/>
<div class="mt1">
<div class='mt1'>
<Button
small={true}
className={'button--secondary button--new-line'}
onClick={onClickNewRow}>
New lines
onClick={onClickNewRow}
>
<T id={'new_lines'} />
</Button>
<Button
small={true}
className={'button--secondary button--clear-lines ml1'}
onClick={onClickNewRow}>
Clear all lines
onClick={onClickNewRow}
>
<T id={'clear_all_lines'} />
</Button>
</div>
</div>
@@ -232,4 +243,4 @@ export default compose(
withAccounts(({ accounts }) => ({
accounts,
})),
)(MakeJournalEntriesTable);
)(MakeJournalEntriesTable);

View File

@@ -25,6 +25,7 @@ import withResourceDetail from 'containers/Resources/withResourceDetails';
import withManualJournals from 'containers/Accounting/withManualJournals';
import withManualJournalsActions from 'containers/Accounting/withManualJournalsActions';
import { FormattedMessage as T, useIntl } from 'react-intl';
function ManualJournalActionsBar({
// #withResourceDetail
@@ -43,6 +44,7 @@ function ManualJournalActionsBar({
}) {
const { path } = useRouteMatch();
const history = useHistory();
const {formatMessage} = useIntl();
const viewsMenuItems = manualJournalsViews.map(view => {
return (
@@ -82,7 +84,7 @@ function ManualJournalActionsBar({
<Button
className={classNames(Classes.MINIMAL, 'button--table-views')}
icon={<Icon icon='table' />}
text='Table Views'
text={<T id={'table_views'}/>}
rightIcon={'caret-down'}
/>
</Popover>
@@ -92,7 +94,7 @@ function ManualJournalActionsBar({
<Button
className={Classes.MINIMAL}
icon={<Icon icon='plus' />}
text='New Journal'
text={<T id={'new_journal'}/>}
onClick={onClickNewManualJournal}
/>
<Popover
@@ -111,7 +113,7 @@ function ManualJournalActionsBar({
<Button
className={Classes.MINIMAL}
icon={<Icon icon='trash' iconSize={15} />}
text='Delete'
text={<T id={'delete'}/>}
intent={Intent.DANGER}
onClick={handleBulkDelete}
/>
@@ -120,12 +122,12 @@ function ManualJournalActionsBar({
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-import' />}
text='Import'
text={<T id={'import'}/>}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-export' />}
text='Export'
text={<T id={'export'}/>}
/>
</NavbarGroup>
</DashboardActionsBar>

View File

@@ -11,6 +11,8 @@ import {
Position,
} from '@blueprintjs/core';
import { useParams } from 'react-router-dom';
import { FormattedMessage as T, useIntl } from 'react-intl';
import Icon from 'components/Icon';
import { compose } from 'utils';
import moment from 'moment';
@@ -20,14 +22,13 @@ import DialogConnect from 'connectors/Dialog.connector';
import { useUpdateEffect } from 'hooks';
import DataTable from 'components/DataTable';
import Money from 'components/Money';
import withDashboardActions from 'containers/Dashboard/withDashboard';
import withViewDetails from 'containers/Views/withViewDetails';
import withManualJournals from 'containers/Accounting/withManualJournals';
import withManualJournalsActions from 'containers/Accounting/withManualJournalsActions';
import { If } from 'components';
import { If, Money } from 'components';
function ManualJournalsDataTable({
@@ -52,6 +53,8 @@ function ManualJournalsDataTable({
const { custom_view_id: customViewId } = useParams();
const [initialMount, setInitialMount] = useState(false);
const { formatMessage } = useIntl();
useUpdateEffect(() => {
if (!manualJournalsLoading) {
setInitialMount(true);
@@ -72,63 +75,75 @@ function ManualJournalsDataTable({
viewMeta,
]);
const handlePublishJournal = useCallback((journal) => () => {
onPublishJournal && onPublishJournal(journal);
}, [onPublishJournal]);
const handlePublishJournal = useCallback(
(journal) => () => {
onPublishJournal && onPublishJournal(journal);
},
[onPublishJournal]
);
const handleEditJournal = useCallback((journal) => () => {
onEditJournal && onEditJournal(journal);
}, [onEditJournal]);
const handleEditJournal = useCallback(
(journal) => () => {
onEditJournal && onEditJournal(journal);
},
[onEditJournal]
);
const handleDeleteJournal = useCallback((journal) => () => {
onDeleteJournal && onDeleteJournal(journal);
}, [onDeleteJournal]);
const handleDeleteJournal = useCallback(
(journal) => () => {
onDeleteJournal && onDeleteJournal(journal);
},
[onDeleteJournal]
);
const actionMenuList = (journal) => (
<Menu>
<MenuItem text='View Details' />
<MenuItem text={<T id={'view_details'} />} />
<MenuDivider />
{!journal.status && (
<MenuItem
text="Publish Journal"
onClick={handlePublishJournal(journal)} />
)}
text={<T id={'publish_journal'} />}
onClick={handlePublishJournal(journal)}
/>
)}
<MenuItem
text='Edit Journal'
onClick={handleEditJournal(journal)} />
text={<T id={'edit_journal'} />}
onClick={handleEditJournal(journal)}
/>
<MenuItem
text='Delete Journal'
text={<T id={'delete_journal'} />}
intent={Intent.DANGER}
onClick={handleDeleteJournal(journal)} />
onClick={handleDeleteJournal(journal)}
/>
</Menu>
);
const columns = useMemo(() => [
{
id: 'date',
Header: 'Date',
accessor: r => moment().format('YYYY-MM-DD'),
Header: formatMessage({ id: 'date' }),
accessor: (r) => moment().format('YYYY-MM-DD'),
disableResizing: true,
width: 150,
className: 'date',
},
{
id: 'amount',
Header: 'Amount',
Header: formatMessage({ id: 'amount' }),
accessor: r => (<Money amount={r.amount} currency={'USD'} />),
disableResizing: true,
className: 'amount',
},
{
id: 'journal_number',
Header: 'Journal No.',
Header: formatMessage({ id: 'journal_no' }),
accessor: 'journal_number',
disableResizing: true,
className: 'journal_number',
},
{
id: 'status',
Header: 'Status',
Header: formatMessage({ id: 'status' }),
accessor: (r) => {
return r.status ? 'Published' : 'Draft';
},
@@ -138,7 +153,7 @@ function ManualJournalsDataTable({
},
{
id: 'note',
Header: 'Note',
Header: formatMessage({ id: 'note' }),
accessor: (row) => (
<If condition={row.description}>
<Tooltip
@@ -157,14 +172,14 @@ function ManualJournalsDataTable({
},
{
id: 'transaction_type',
Header: 'Transaction type ',
Header: formatMessage({ id: 'transaction_type' }),
accessor: 'transaction_type',
width: 100,
className: 'transaction_type',
},
{
id: 'created_at',
Header: 'Created At',
Header: formatMessage({ id: 'created_at' }),
accessor: r => moment().format('YYYY-MM-DD'),
disableResizing: true,
width: 150,
@@ -192,7 +207,7 @@ function ManualJournalsDataTable({
}, [onFetchData]);
const handleSelectedRowsChange = useCallback((selectedRows) => {
onSelectedRowsChange && onSelectedRowsChange(selectedRows.map(s => s.original));
onSelectedRowsChange && onSelectedRowsChange(selectedRows.map((s) => s.original));
}, [onSelectedRowsChange]);
return (
@@ -214,7 +229,6 @@ function ManualJournalsDataTable({
export default compose(
DialogConnect,
withDashboardActions,
// withViewsActions,
withManualJournalsActions,
withManualJournals(({ manualJournals, manualJournalsLoading, }) => ({
manualJournals,

View File

@@ -3,6 +3,7 @@ import { Route, Switch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { Alert, Intent } from '@blueprintjs/core';
import AppToaster from 'components/AppToaster';
import { FormattedMessage as T, useIntl } from 'react-intl';
import DashboardPageContent from 'components/Dashboard/DashboardPageContent';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
@@ -17,7 +18,6 @@ import withViewsActions from 'containers/Views/withViewsActions';
import { compose } from 'utils';
/**
* Manual journals table.
*/
@@ -39,22 +39,26 @@ function ManualJournalsTable({
const [deleteManualJournal, setDeleteManualJournal] = useState(false);
const [selectedRows, setSelectedRows] = useState([]);
const [bulkDelete, setBulkDelete] = useState(false);
const { formatMessage } = useIntl();
const fetchViews = useQuery('journals-resource-views', () => {
return requestFetchResourceViews('manual_journals');
});
const fetchManualJournals = useQuery('manual-journals-table', () =>
requestFetchManualJournalsTable());
const fetchManualJournals = useQuery('manual-journals-table', () =>
requestFetchManualJournalsTable()
);
useEffect(() => {
changePageTitle('Manual Journals');
changePageTitle(formatMessage({id:'manual_journals'}));
}, [changePageTitle]);
// Handle delete manual journal click.
const handleDeleteJournal = useCallback((journal) => {
setDeleteManualJournal(journal);
}, [setDeleteManualJournal]);
const handleDeleteJournal = useCallback(
(journal) => {
setDeleteManualJournal(journal);
},
[setDeleteManualJournal]
);
// Handle cancel delete manual journal.
const handleCancelManualJournalDelete = useCallback(() => {
@@ -69,30 +73,35 @@ function ManualJournalsTable({
});
}, [deleteManualJournal, requestDeleteManualJournal]);
const handleBulkDelete = useCallback((accountsIds) => {
setBulkDelete(accountsIds);
}, [setBulkDelete]);
const handleBulkDelete = useCallback(
(accountsIds) => {
setBulkDelete(accountsIds);
},
[setBulkDelete]
);
const handleConfirmBulkDelete = useCallback(() => {
requestDeleteBulkManualJournals(bulkDelete).then(() => {
setBulkDelete(false);
AppToaster.show({ message: 'the_accounts_have_been_deleted' });
}).catch((error) => {
setBulkDelete(false);
});
}, [
requestDeleteBulkManualJournals,
bulkDelete,
]);
requestDeleteBulkManualJournals(bulkDelete)
.then(() => {
setBulkDelete(false);
AppToaster.show({ message: 'the_accounts_have_been_deleted' });
})
.catch((error) => {
setBulkDelete(false);
});
}, [requestDeleteBulkManualJournals, bulkDelete]);
const handleCancelBulkDelete = useCallback(() => {
setBulkDelete(false);
}, []);
const handleEditJournal = useCallback((journal) => {
history.push(`/dashboard/accounting/manual-journals/${journal.id}/edit`);
}, [history]);
const handleEditJournal = useCallback(
(journal) => {
history.push(`/dashboard/accounting/manual-journals/${journal.id}/edit`);
},
[history]
);
// Handle filter change to re-fetch data-table.
const handleFilterChanged = useCallback(() => {
fetchManualJournals.refetch();
@@ -104,36 +113,49 @@ function ManualJournalsTable({
}, [fetchManualJournals]);
// Handle fetch data of manual jouranls datatable.
const handleFetchData = useCallback(({ pageIndex, pageSize, sortBy }) => {
addManualJournalsTableQueries({
...(sortBy.length > 0) ? {
column_sort_by: sortBy[0].id,
sort_order: sortBy[0].desc ? 'desc' : 'asc',
} : {},
});
}, [
addManualJournalsTableQueries,
]);
const handleFetchData = useCallback(
({ pageIndex, pageSize, sortBy }) => {
addManualJournalsTableQueries({
...(sortBy.length > 0
? {
column_sort_by: sortBy[0].id,
sort_order: sortBy[0].desc ? 'desc' : 'asc',
}
: {}),
});
},
[addManualJournalsTableQueries]
);
const handlePublishJournal = useCallback((journal) => {
requestPublishManualJournal(journal.id).then(() => {
AppToaster.show({ message: 'the_manual_journal_id_has_been_published' });
})
}, [requestPublishManualJournal]);
const handlePublishJournal = useCallback(
(journal) => {
requestPublishManualJournal(journal.id).then(() => {
AppToaster.show({
message: 'the_manual_journal_id_has_been_published',
});
});
},
[requestPublishManualJournal]
);
// Handle selected rows change.
const handleSelectedRowsChange = useCallback((accounts) => {
setSelectedRows(accounts);
}, [setSelectedRows]);
const handleSelectedRowsChange = useCallback(
(accounts) => {
setSelectedRows(accounts);
},
[setSelectedRows]
);
return (
<DashboardInsider
loading={fetchViews.isFetching || fetchManualJournals.isFetching}
name={'manual-journals'}>
name={'manual-journals'}
>
<ManualJournalsActionsBar
onBulkDelete={handleBulkDelete}
selectedRows={selectedRows}
onFilterChanged={handleFilterChanged} />
onFilterChanged={handleFilterChanged}
/>
<DashboardPageContent>
<Switch>
@@ -142,8 +164,7 @@ function ManualJournalsTable({
path={[
'/dashboard/accounting/manual-journals/:custom_view_id/custom_view',
'/dashboard/accounting/manual-journals',
]}>
]}>
</Route>
</Switch>
@@ -152,11 +173,12 @@ function ManualJournalsTable({
onFetchData={handleFetchData}
onEditJournal={handleEditJournal}
onPublishJournal={handlePublishJournal}
onSelectedRowsChange={handleSelectedRowsChange} />
onSelectedRowsChange={handleSelectedRowsChange}
/>
<Alert
cancelButtonText='Cancel'
confirmButtonText='Move to Trash'
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={<T id={'move_to_trash'} />}
icon='trash'
intent={Intent.DANGER}
isOpen={deleteManualJournal}
@@ -170,8 +192,8 @@ function ManualJournalsTable({
</Alert>
<Alert
cancelButtonText='Cancel'
confirmButtonText='Move to Trash'
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={<T id={'move_to_trash'} />}
icon='trash'
intent={Intent.DANGER}
isOpen={bulkDelete}
@@ -191,5 +213,5 @@ function ManualJournalsTable({
export default compose(
withDashboardActions,
withManualJournalsActions,
withViewsActions,
withViewsActions
)(ManualJournalsTable);

View File

@@ -27,6 +27,7 @@ import withAccountsTableActions from 'containers/Accounts/withAccountsTableActio
import withAccounts from 'containers/Accounts/withAccounts';
import {compose} from 'utils';
import { FormattedMessage as T, useIntl } from 'react-intl';
function AccountsActionsBar({
@@ -89,7 +90,7 @@ function AccountsActionsBar({
<Button
className={classNames(Classes.MINIMAL, 'button--table-views')}
icon={<Icon icon='table' />}
text='Table Views'
text={<T id={'table_views'}/>}
rightIcon={'caret-down'}
/>
</Popover>
@@ -99,7 +100,7 @@ function AccountsActionsBar({
<Button
className={Classes.MINIMAL}
icon={<Icon icon='plus' />}
text='New Account'
text={<T id={'new_account'}/>}
onClick={onClickNewAccount}
/>
<Popover
@@ -110,7 +111,7 @@ function AccountsActionsBar({
<Button
className={classNames(Classes.MINIMAL, 'button--filter')}
text={filterCount <= 0 ? 'Filter' : `${filterCount} filters applied`}
text={filterCount <= 0 ? <T id={'filter'}/> : `${filterCount} filters applied`}
icon={ <Icon icon="filter" /> }/>
</Popover>
@@ -118,13 +119,13 @@ function AccountsActionsBar({
<Button
className={Classes.MINIMAL}
icon={<Icon icon='archive' iconSize={15} />}
text='Archive'
text={<T id={'archive'}/>}
onClick={handleBulkArchive}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='trash' iconSize={15} />}
text='Delete'
text={<T id={'delete'}/>}
intent={Intent.DANGER}
onClick={handleBulkDelete}
/>
@@ -133,12 +134,12 @@ function AccountsActionsBar({
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-import' />}
text='Import'
text={<T id={'import'}/>}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-export' />}
text='Export'
text={<T id={'export'}/>}
/>
</NavbarGroup>
</DashboardActionsBar>

View File

@@ -5,7 +5,7 @@ import {
} from 'react-router-dom';
import { Alert, Intent } from '@blueprintjs/core';
import { useQuery } from 'react-query'
import { useIntl } from 'react-intl';
import { FormattedMessage as T, FormattedHTMLMessage, useIntl } from 'react-intl';
import AppToaster from 'components/AppToaster';
@@ -23,7 +23,6 @@ import withViewsActions from 'containers/Views/withViewsActions';
import withAccounts from 'containers/Accounts/withAccounts';
import { compose } from 'utils';
import { FormattedMessage as T, FormattedHTMLMessage } from 'react-intl';
function AccountsChart({
@@ -68,16 +67,21 @@ function AccountsChart({
});
// Fetch accounts list according to the given custom view id.
const fetchAccountsHook = useQuery(['accounts-table', accountsTableQuery],
() => requestFetchAccountsTable());
const fetchAccountsHook = useQuery(
['accounts-table', accountsTableQuery],
() => requestFetchAccountsTable(),
{ refetchInterval: 3000 }
);
useEffect(() => {
changePageTitle('Chart of Accounts');
changePageTitle(formatMessage({ id: 'chart_of_accounts' }));
}, [changePageTitle]);
// Handle click and cancel/confirm account delete
const handleDeleteAccount = (account) => { setDeleteAccount(account); };
const handleDeleteAccount = (account) => {
setDeleteAccount(account);
};
// handle cancel delete account alert.
const handleCancelAccountDelete = useCallback(() => { setDeleteAccount(false); }, []);
@@ -157,13 +161,7 @@ function AccountsChart({
});
});
const handleEditAccount = (account) => {
};
const handleRestoreAccount = (account) => {
};
const handleRestoreAccount = (account) => {};
// Handle accounts bulk delete button click.,
const handleBulkDelete = useCallback((accountsIds) => {
@@ -189,17 +187,22 @@ function AccountsChart({
setBulkDelete(false);
}, []);
const handleBulkArchive = useCallback((accounts) => {
const handleBulkArchive = useCallback((accounts) => {}, []);
const handleEditAccount = useCallback(() => {
}, []);
// Handle selected rows change.
const handleSelectedRowsChange = useCallback((accounts) => {
setSelectedRows(accounts);
}, [setSelectedRows]);
const handleSelectedRowsChange = useCallback(
(accounts) => {
setSelectedRows(accounts);
},
[setSelectedRows]
);
// Refetches accounts data table when current custom view changed.
const handleFilterChanged = useCallback(() => {
const handleFilterChanged = useCallback(() => {
fetchAccountsHook.refetch();
}, [fetchAccountsHook]);
@@ -215,28 +218,32 @@ function AccountsChart({
}, [tableLoading, fetchAccountsHook.isFetching]);
// Handle fetch data of accounts datatable.
const handleFetchData = useCallback(({ pageIndex, pageSize, sortBy }) => {
addAccountsTableQueries({
...(sortBy.length > 0) ? {
column_sort_by: sortBy[0].id,
sort_order: sortBy[0].desc ? 'desc' : 'asc',
} : {},
});
fetchAccountsHook.refetch();
}, [fetchAccountsHook, addAccountsTableQueries]);
const handleFetchData = useCallback(
({ pageIndex, pageSize, sortBy }) => {
addAccountsTableQueries({
...(sortBy.length > 0
? {
column_sort_by: sortBy[0].id,
sort_order: sortBy[0].desc ? 'desc' : 'asc',
}
: {}),
});
fetchAccountsHook.refetch();
},
[fetchAccountsHook, addAccountsTableQueries]
);
// Calculates the data table selected rows count.
const selectedRowsCount = useMemo(() => Object.values(selectedRows).length, [selectedRows]);
return (
<DashboardInsider
loading={fetchHook.isFetching}
name={'accounts-chart'}>
<DashboardInsider loading={fetchHook.isFetching} name={'accounts-chart'}>
<DashboardActionsBar
selectedRows={selectedRows}
onFilterChanged={handleFilterChanged}
onBulkDelete={handleBulkDelete}
onBulkArchive={handleBulkArchive} />
onBulkArchive={handleBulkArchive}
/>
<DashboardPageContent>
<Switch>
@@ -245,9 +252,9 @@ function AccountsChart({
path={[
'/dashboard/accounts/:custom_view_id/custom_view',
'/dashboard/accounts',
]}>
<AccountsViewsTabs
onViewChanged={handleViewChanged} />
]}
>
<AccountsViewsTabs onViewChanged={handleViewChanged} />
<AccountsDataTable
onDeleteAccount={handleDeleteAccount}
@@ -257,7 +264,8 @@ function AccountsChart({
onEditAccount={handleEditAccount}
onFetchData={handleFetchData}
onSelectedRowsChange={handleSelectedRowsChange}
loading={tableLoading} />
loading={tableLoading}
/>
</Route>
</Switch>
@@ -268,7 +276,8 @@ function AccountsChart({
intent={Intent.DANGER}
isOpen={deleteAccount}
onCancel={handleCancelAccountDelete}
onConfirm={handleConfirmAccountDelete}>
onConfirm={handleConfirmAccountDelete}
>
<p>
<FormattedHTMLMessage
id={'once_delete_this_account_you_will_able_to_restore_it'} />
@@ -276,20 +285,21 @@ function AccountsChart({
</Alert>
<Alert
cancelButtonText="Cancel"
confirmButtonText="Inactivate"
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={<T id={'inactivate'} />}
intent={Intent.WARNING}
isOpen={inactiveAccount}
onCancel={handleCancelInactiveAccount}
onConfirm={handleConfirmAccountActive}>
onConfirm={handleConfirmAccountActive}
>
<p>
<T id={'are_sure_to_inactive_this_account'} />
</p>
</Alert>
<Alert
cancelButtonText="Cancel"
confirmButtonText="Activate"
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={<T id={'activate'} />}
intent={Intent.WARNING}
isOpen={activateAccount}
onCancel={handleCancelActivateAccount}
@@ -306,7 +316,8 @@ function AccountsChart({
intent={Intent.DANGER}
isOpen={bulkDelete}
onCancel={handleCancelBulkDelete}
onConfirm={handleConfirmBulkDelete}>
onConfirm={handleConfirmBulkDelete}
>
<p>
<T id={'once_delete_these_accounts_you_will_not_able_restore_them'} />
</p>
@@ -325,4 +336,4 @@ export default compose(
withAccounts(({ accountsTableQuery }) => ({
accountsTableQuery,
})),
)(AccountsChart);
)(AccountsChart);

View File

@@ -9,7 +9,7 @@ import {
Classes,
Tooltip,
} from '@blueprintjs/core';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import Icon from 'components/Icon';
import { compose } from 'utils';
@@ -61,13 +61,13 @@ function AccountsDataTable({
const actionMenuList = useCallback((account) => (
<Menu>
<MenuItem text='View Details' />
<MenuItem text={<T id={'view_details'}/>} />
<MenuDivider />
<MenuItem
text='Edit Account'
text={<T id={'edit_account'}/>}
onClick={handleEditAccount(account)} />
<MenuItem
text='New Account'
text={<T id={'new_account'}/>}
onClick={() => handleNewParentAccount(account)} />
<MenuDivider />
<If condition={account.active}>
@@ -81,7 +81,7 @@ function AccountsDataTable({
onClick={() => onActivateAccount(account)} />
</If>
<MenuItem
text='Delete Account'
text={<T id={'delete_account'}/>}
onClick={() => onDeleteAccount(account)} />
</Menu>
), [handleEditAccount, onDeleteAccount, onInactiveAccount]);
@@ -89,7 +89,7 @@ function AccountsDataTable({
const columns = useMemo(() => [
{
id: 'name',
Header: 'Account Name',
Header: formatMessage({id:'account_name'}),
accessor: row => {
return (row.description) ?
(<Tooltip
@@ -105,21 +105,21 @@ function AccountsDataTable({
},
{
id: 'code',
Header: 'Code',
Header: formatMessage({id:'code'}),
accessor: 'code',
className: 'code',
width: 100,
},
{
id: 'type',
Header: 'Type',
Header: formatMessage({id:'type'}),
accessor: 'type.name',
className: 'type',
width: 120,
},
{
id: 'normal',
Header: 'Normal',
Header: formatMessage({id:'normal'}),
Cell: ({ cell }) => {
const account = cell.row.original;
const normal = account.type ? account.type.normal : '';
@@ -140,7 +140,7 @@ function AccountsDataTable({
},
{
id: 'balance',
Header: 'Balance',
Header: formatMessage({id:'balance'}),
Cell: ({ cell }) => {
const account = cell.row.original;
const {balance = null} = account;

View File

@@ -22,4 +22,4 @@ export default (mapState) => {
};
return connect(mapStateToProps);
};
};

View File

@@ -1,7 +1,7 @@
import React, { useCallback, useMemo, useState } from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import ErrorMessage from 'components/ErrorMessage';
import AppToaster from 'components/AppToaster';
import { compose } from 'utils';
@@ -15,27 +15,29 @@ import {
Position,
Spinner,
} from '@blueprintjs/core';
import Icon from 'components/Icon';
import { Row, Col } from 'react-grid-system';
import AuthInsider from 'containers/Authentication/AuthInsider';
import { Link, useHistory } from 'react-router-dom';
import useAsync from 'hooks/async';
import { If } from 'components';
function Invite({
requestInviteAccept,
requestInviteMetaByToken,
}) {
const intl = useIntl();
function Invite({ requestInviteAccept, requestInviteMetaByToken }) {
const { formatMessage } = useIntl();
const { token } = useParams();
const history = useHistory();
const [shown, setShown] = useState(false);
const passwordRevealer = useCallback(() => { setShown(!shown); }, [shown]);
const passwordRevealer = useCallback(() => {
setShown(!shown);
}, [shown]);
const ValidationSchema = Yup.object().shape({
first_name: Yup.string().required(),
last_name: Yup.string().required(),
phone_number: Yup.string().matches().required(),
first_name: Yup.string().required(formatMessage({ id: 'required' })),
last_name: Yup.string().required(formatMessage({ id: 'required' })),
phone_number: Yup.string()
.matches()
.required(formatMessage({ id: 'required' })),
password: Yup.string()
.min(4, 'Password has to be longer than 4 characters!')
.required('Password is required!'),
@@ -49,11 +51,10 @@ function Invite({
const inviteValue = {
organization_name: '',
invited_email: '',
...inviteMeta.value ?
inviteMeta.value.data.data : {},
...(inviteMeta.value ? inviteMeta.value.data.data : {}),
};
if (inviteErrors.find(e => e.type === 'INVITE.TOKEN.NOT.FOUND')) {
if (inviteErrors.find((e) => e.type === 'INVITE.TOKEN.NOT.FOUND')) {
AppToaster.show({
message: 'An unexpected error occurred',
intent: Intent.DANGER,
@@ -62,12 +63,15 @@ function Invite({
history.push('/auth/login');
}
const initialValues = useMemo(() => ({
first_name: '',
last_name: '',
phone_number: '',
password: '',
}), []);
const initialValues = useMemo(
() => ({
first_name: '',
last_name: '',
phone_number: '',
password: '',
}),
[]
);
const {
values,
@@ -95,15 +99,15 @@ function Invite({
.catch((errors) => {
if (errors.find((e) => e.type === 'INVITE.TOKEN.NOT.FOUND')) {
AppToaster.show({
message: 'An unexpected error occurred',
message: formatMessage({ id: 'an_unexpected_error_occurred' }),
intent: Intent.DANGER,
position: Position.BOTTOM,
});
history.push('/auth/login');
}
if (errors.find(e => e.type === 'PHONE_MUMNER.ALREADY.EXISTS')){
if (errors.find((e) => e.type === 'PHONE_MUMNER.ALREADY.EXISTS')) {
setErrors({
phone_number: 'This phone number is used in another account.'
phone_number: 'This phone number is used in another account.',
});
}
setSubmitting(false);
@@ -111,23 +115,40 @@ function Invite({
},
});
const passwordRevealerTmp = useMemo(() => (
<span class="password-revealer" onClick={() => passwordRevealer()}>
{(shown) ? (
<><Icon icon='eye-slash' /> <span class="text">Hide</span></>
) : (
<><Icon icon='eye' /> <span class="text">Show</span></>
)}
</span>), [shown, passwordRevealer]);
const passwordRevealerTmp = useMemo(
() => (
<span class='password-revealer' onClick={() => passwordRevealer()}>
<If condition={shown}>
<>
<Icon icon='eye-slash' />{' '}
<span class='text'>
<T id={'hide'} />
</span>
</>
</If>
<If condition={!shown}>
<>
<Icon icon='eye' />{' '}
<span class='text'>
<T id={'show'} />
</span>
</>
</If>
</span>
),
[shown, passwordRevealer]
);
return (
<AuthInsider>
<div className={'invite-form'}>
<div className={'authentication-page__label-section'}>
<h3>Welcome to Bigcapital</h3>
<h3>
<T id={'welcome_to_bigcapital'} />
</h3>
<p>
Enter your personal information <b>{ inviteValue.organization_name }</b>{' '}
Organization.
<T id={'enter_your_personal_information'} />
<b>{inviteValue.organization_name}</b> Organization.
</p>
</div>
@@ -135,30 +156,37 @@ function Invite({
<Row>
<Col md={6}>
<FormGroup
label={'First Name'}
label={<T id={'First Name'} />}
className={'form-group--first_name'}
intent={(errors.first_name && touched.first_name) && Intent.DANGER}
helperText={<ErrorMessage name={'first_name'} {...{errors, touched}} />}
intent={
errors.first_name && touched.first_name && Intent.DANGER
}
helperText={
<ErrorMessage name={'first_name'} {...{ errors, touched }} />
}
>
<InputGroup
intent={(errors.first_name && touched.first_name) &&
Intent.DANGER
intent={
errors.first_name && touched.first_name && Intent.DANGER
}
{...getFieldProps('first_name')} />
{...getFieldProps('first_name')}
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup
label={'Last Name'}
label={<T id={'Last Name'} />}
className={'form-group--last_name'}
intent={(errors.last_name && touched.last_name) &&
Intent.DANGER
intent={errors.last_name && touched.last_name && Intent.DANGER}
helperText={
<ErrorMessage name={'last_name'} {...{ errors, touched }} />
}
helperText={<ErrorMessage name={'last_name'} {...{errors, touched}} />}
>
<InputGroup
intent={(errors.last_name && touched.last_name) && Intent.DANGER}
intent={
errors.last_name && touched.last_name && Intent.DANGER
}
{...getFieldProps('last_name')}
/>
</FormGroup>
@@ -166,57 +194,73 @@ function Invite({
</Row>
<FormGroup
label={'Phone Number'}
label={<T id={'Phone Number'} />}
className={'form-group--phone_number'}
intent={(errors.phone_number && touched.phone_number) && Intent.DANGER}
helperText={<ErrorMessage name={'phone_number'} {...{errors, touched}} />}
intent={
errors.phone_number && touched.phone_number && Intent.DANGER
}
helperText={
<ErrorMessage name={'phone_number'} {...{ errors, touched }} />
}
>
<InputGroup
intent={(errors.phone_number && touched.phone_number) && Intent.DANGER}
intent={
errors.phone_number && touched.phone_number && Intent.DANGER
}
{...getFieldProps('phone_number')}
/>
</FormGroup>
<FormGroup
label={'Password'}
label={<T id={'password'} />}
labelInfo={passwordRevealerTmp}
className={'form-group--password has-password-revealer'}
intent={(errors.password && touched.password) && Intent.DANGER}
helperText={<ErrorMessage name={'password'} {...{errors, touched}} />}
intent={errors.password && touched.password && Intent.DANGER}
helperText={
<ErrorMessage name={'password'} {...{ errors, touched }} />
}
>
<InputGroup
lang={true}
type={shown ? 'text' : 'password'}
intent={(errors.password && touched.password) && Intent.DANGER}
intent={errors.password && touched.password && Intent.DANGER}
{...getFieldProps('password')}
/>
</FormGroup>
<div className={'invite-form__statement-section'}>
<p>
You email address is <b>{ inviteValue.invited_email },</b> <br />
You will use this address to sign in to Bigcapital.
<T id={'You email address is'} />{' '}
<b>{inviteValue.invited_email},</b> <br />
<T id={'you_will_use_this_address_to_sign_in_to_bigcapital'} />
</p>
<p>
By signing in or creating an account, you agree with our <br />
<Link>Terms & Conditions</Link> and <Link> Privacy Statement</Link>
<T id={'signing_in_or_creating'} /> <br />
<Link>
<T id={'terms_conditions'} />
</Link>{' '}
<T id={'and'} />
<Link>
{' '}
<T id={'privacy_statement'} />
</Link>
</p>
</div>
<div className={'authentication-page__submit-button-wrap'}>
<Button
intent={Intent.PRIMARY}
type='submit'
fill={true}
loading={isSubmitting}
loading={isSubmitting}
>
Create Account
<T id={'create_account'} />
</Button>
</div>
</form>
{ inviteMeta.pending && (
<div class="authentication-page__loading-overlay">
{inviteMeta.pending && (
<div class='authentication-page__loading-overlay'>
<Spinner size={40} />
</div>
)}
@@ -225,6 +269,4 @@ function Invite({
);
}
export default compose(
withAuthenticationActions,
)(Invite);
export default compose(withAuthenticationActions)(Invite);

View File

@@ -69,7 +69,7 @@ function Login({
const toastBuilders = [];
if (errors.find((e) => e.type === ERRORS_TYPES.INVALID_DETAILS)) {
toastBuilders.push({
message: formatMessage('email_and_password_entered_did_not_match'),
message: formatMessage({id:'email_and_password_entered_did_not_match'}),
intent: Intent.DANGER,
});
}
@@ -102,7 +102,7 @@ function Login({
<div className='login-form'>
<div className={'authentication-page__label-section'}>
<h3><T id={'log_in'} /></h3>
<T id={'need_bigcapital_account?'} />
<T id={'need_bigcapital_account'} />
<Link to='/auth/register'> <T id={'create_an_account'} /></Link>
</div>

View File

@@ -1,13 +1,14 @@
import React, { useMemo, useState, useCallback } from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import {
Button,
InputGroup,
Intent,
FormGroup,
Spinner
Spinner,
} from '@blueprintjs/core';
import { Row, Col } from 'react-grid-system';
import { Link, useHistory } from 'react-router-dom';
@@ -19,35 +20,40 @@ import { compose } from 'utils';
import Icon from 'components/Icon';
import { If } from 'components';
function Register({
requestRegister,
}) {
const intl = useIntl();
function Register({ requestRegister }) {
const { formatMessage } = useIntl();
const history = useHistory();
const [shown, setShown] = useState(false);
const passwordRevealer = useCallback(() => { setShown(!shown); }, [shown]);
const passwordRevealer = useCallback(() => {
setShown(!shown);
}, [shown]);
const ValidationSchema = Yup.object().shape({
organization_name: Yup.string().required(),
first_name: Yup.string().required(),
last_name: Yup.string().required(),
email: Yup.string().email().required(),
organization_name: Yup.string().required(formatMessage({ id: 'required' })),
first_name: Yup.string().required(formatMessage({ id: 'required' })),
last_name: Yup.string().required(formatMessage({ id: 'required' })),
email: Yup.string()
.email()
.required(formatMessage({ id: 'required' })),
phone_number: Yup.string()
.matches()
.required(intl.formatMessage({ id: 'required' })),
.required(formatMessage({ id: 'required' })),
password: Yup.string()
.min(4, 'Password has to be longer than 8 characters!')
.required('Password is required!'),
});
const initialValues = useMemo(() => ({
organization_name: '',
first_name: '',
last_name: '',
email: '',
phone_number: '',
password: '',
}), []);
const initialValues = useMemo(
() => ({
organization_name: '',
first_name: '',
last_name: '',
email: '',
phone_number: '',
password: '',
}),
[]
);
const {
errors,
@@ -62,26 +68,27 @@ function Register({
validationSchema: ValidationSchema,
initialValues: {
...initialValues,
country: 'libya'
country: 'libya',
},
onSubmit: (values, { setSubmitting, setErrors }) => {
requestRegister(values)
.then((response) => {
AppToaster.show({
message: 'success',
message: formatMessage({ id: 'success' }),
});
setSubmitting(false);
history.push('/auth/login');
})
.catch((errors) => {
if (errors.some(e => e.type === 'PHONE_NUMBER_EXISTS')) {
if (errors.some((e) => e.type === 'PHONE_NUMBER_EXISTS')) {
setErrors({
phone_number: 'The phone number is already used in another account.'
phone_number:
'The phone number is already used in another account.',
});
}
if (errors.some(e => e.type === 'EMAIL_EXISTS')) {
if (errors.some((e) => e.type === 'EMAIL_EXISTS')) {
setErrors({
email: 'The email is already used in another account.'
email: 'The email is already used in another account.',
});
}
setSubmitting(false);
@@ -89,34 +96,66 @@ function Register({
},
});
const passwordRevealerTmp = useMemo(() => (
<span class="password-revealer" onClick={() => passwordRevealer()}>
{(shown) ? (
<><Icon icon='eye-slash' /> <span class="text">Hide</span></>
) : (
<><Icon icon='eye' /> <span class="text">Show</span></>
)}
</span>), [shown, passwordRevealer]);
const passwordRevealerTmp = useMemo(
() => (
<span class='password-revealer' onClick={() => passwordRevealer()}>
<If condition={shown}>
<>
<Icon icon='eye-slash' />{' '}
<span class='text'>
<T id={'hide'} />
</span>
</>
</If>
<If condition={!shown}>
<>
<Icon icon='eye' />{' '}
<span class='text'>
<T id={'show'} />
</span>
</>
</If>
</span>
),
[shown, passwordRevealer]
);
return (
<AuthInsider>
<div className={'register-form'}>
<div className={'authentication-page__label-section'}>
<h3>
Register a New <br />Organization.
<T id={'register_a_new_organization'} />
</h3>
You have a bigcapital account ?<Link to='/auth/login'> Login</Link>
<T id={'you_have_a_bigcapital_account'} />
<Link to='/auth/login'>
{' '}
<T id={'login'} />
</Link>
</div>
<form onSubmit={handleSubmit} className={'authentication-page__form'}>
<FormGroup
label={'Organization Name'}
label={<T id={'organization_name'} />}
className={'form-group--name'}
intent={(errors.organization_name && touched.organization_name) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name={'organization_name'} />}
intent={
errors.organization_name &&
touched.organization_name &&
Intent.DANGER
}
helperText={
<ErrorMessage
{...{ errors, touched }}
name={'organization_name'}
/>
}
>
<InputGroup
intent={(errors.organization_name && touched.organization_name) && Intent.DANGER}
intent={
errors.organization_name &&
touched.organization_name &&
Intent.DANGER
}
{...getFieldProps('organization_name')}
/>
</FormGroup>
@@ -124,13 +163,19 @@ function Register({
<Row className={'name-section'}>
<Col md={6}>
<FormGroup
label={'First Name'}
intent={(errors.first_name && touched.first_name) && Intent.DANGER}
helperText={<ErrorMessage name={'first_name'} {...{errors, touched}} />}
label={<T id={'first_name'} />}
intent={
errors.first_name && touched.first_name && Intent.DANGER
}
helperText={
<ErrorMessage name={'first_name'} {...{ errors, touched }} />
}
className={'form-group--first-name'}
>
<InputGroup
intent={(errors.first_name && touched.first_name) && Intent.DANGER}
intent={
errors.first_name && touched.first_name && Intent.DANGER
}
{...getFieldProps('first_name')}
/>
</FormGroup>
@@ -138,65 +183,83 @@ function Register({
<Col md={6}>
<FormGroup
label={'Last Name'}
intent={(errors.last_name && touched.last_name) && Intent.DANGER}
helperText={<ErrorMessage name={'last_name'} {...{errors, touched}} />}
label={<T id={'last_name'} />}
intent={errors.last_name && touched.last_name && Intent.DANGER}
helperText={
<ErrorMessage name={'last_name'} {...{ errors, touched }} />
}
className={'form-group--last-name'}
>
<InputGroup
intent={(errors.last_name && touched.last_name) && Intent.DANGER}
intent={
errors.last_name && touched.last_name && Intent.DANGER
}
{...getFieldProps('last_name')}
/>
</FormGroup>
</Col>
</Row>
<FormGroup
label={'Phone Number'}
intent={(errors.phone_number && touched.phone_number) && Intent.DANGER}
helperText={<ErrorMessage name={'phone_number'} {...{errors, touched}} />}
label={<T id={'phone_number'} />}
intent={
errors.phone_number && touched.phone_number && Intent.DANGER
}
helperText={
<ErrorMessage name={'phone_number'} {...{ errors, touched }} />
}
className={'form-group--phone-number'}
>
<InputGroup
intent={
(errors.phone_number && touched.phone_number) &&
Intent.DANGER
errors.phone_number && touched.phone_number && Intent.DANGER
}
{...getFieldProps('phone_number')}
/>
</FormGroup>
<FormGroup
label={'Email'}
intent={(errors.email && touched.email) && Intent.DANGER}
helperText={<ErrorMessage name={'email'} {...{errors, touched}} />}
label={<T id={'email'} />}
intent={errors.email && touched.email && Intent.DANGER}
helperText={
<ErrorMessage name={'email'} {...{ errors, touched }} />
}
className={'form-group--email'}
>
<InputGroup
intent={(errors.email && touched.email) && Intent.DANGER}
intent={errors.email && touched.email && Intent.DANGER}
{...getFieldProps('email')}
/>
</FormGroup>
<FormGroup
label={'Password'}
label={<T id={'password'} />}
labelInfo={passwordRevealerTmp}
intent={(errors.password && touched.password) && Intent.DANGER}
helperText={<ErrorMessage name={'password'} {...{errors, touched}} />}
intent={errors.password && touched.password && Intent.DANGER}
helperText={
<ErrorMessage name={'password'} {...{ errors, touched }} />
}
className={'form-group--password has-password-revealer'}
>
<InputGroup
lang={true}
type={shown ? 'text' : 'password'}
intent={(errors.password && touched.password) && Intent.DANGER}
intent={errors.password && touched.password && Intent.DANGER}
{...getFieldProps('password')}
/>
</FormGroup>
<div className={'register-form__agreement-section'}>
<p>
By signing in or creating an account, you agree with our <br />
<Link>Terms & Conditions</Link> and <Link> Privacy Statement</Link>
<p>
<T id={'signing_in_or_creating'} /> <br />
<Link>
<T id={'terms_conditions'} />
</Link>{' '}
<T id={'and'} />
<Link>
{' '}
<T id={'privacy_statement'} />
</Link>
</p>
</div>
@@ -208,13 +271,13 @@ function Register({
fill={true}
loading={isSubmitting}
>
Register
<T id={'register'} />
</Button>
</div>
</form>
<If condition={isSubmitting}>
<div class="authentication-page__loading-overlay">
<div class='authentication-page__loading-overlay'>
<Spinner size={50} />
</div>
</If>
@@ -223,6 +286,4 @@ function Register({
);
}
export default compose(
withAuthenticationActions,
)(Register);
export default compose(withAuthenticationActions)(Register);

View File

@@ -1,7 +1,7 @@
import React, { useEffect, useMemo } from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import { useIntl } from 'react-intl';
import {
Button,
InputGroup,
@@ -15,12 +15,10 @@ import AppToaster from 'components/AppToaster';
import { compose } from 'utils';
import withAuthenticationActions from './withAuthenticationActions';
import AuthInsider from 'containers/Authentication/AuthInsider';
import { FormattedMessage as T, useIntl } from 'react-intl';
function ResetPassword({
requestResetPassword,
}) {
const intl = useIntl();
function ResetPassword({ requestResetPassword }) {
const { formatMessage } = useIntl();
const { token } = useParams();
const history = useHistory();
@@ -33,10 +31,13 @@ function ResetPassword({
.required('Confirm Password is required'),
});
const initialValues = useMemo(() => ({
password: '',
confirm_password: '',
}), []);
const initialValues = useMemo(
() => ({
password: '',
confirm_password: '',
}),
[]
);
const {
touched,
@@ -56,7 +57,7 @@ function ResetPassword({
requestResetPassword(values, token)
.then((response) => {
AppToaster.show({
message: 'The password for your account was successfully updated.',
message: formatMessage('password_successfully_updated'),
intent: Intent.DANGER,
position: Position.BOTTOM,
});
@@ -64,9 +65,9 @@ function ResetPassword({
setSubmitting(false);
})
.catch((errors) => {
if (errors.find(e => e.type === 'TOKEN_INVALID')) {
if (errors.find((e) => e.type === 'TOKEN_INVALID')) {
AppToaster.show({
message: 'An unexpected error occurred',
message: formatMessage('an_unexpected_error_occurred'),
intent: Intent.DANGER,
position: Position.BOTTOM,
});
@@ -79,17 +80,24 @@ function ResetPassword({
return (
<AuthInsider>
<div className={'submit-np-form'}>
<div className={'submit-np-form'}>
<div className={'authentication-page__label-section'}>
<h3>Choose a new password</h3>
You remembered your password ? <Link to='/auth/login'>Login</Link>
<h3>
<T id={'choose_a_new_password'} />
</h3>
<T id={'you_remembered_your_password'} />{' '}
<Link to='/auth/login'>
<T id={'login'} />
</Link>
</div>
<form onSubmit={handleSubmit}>
<FormGroup
label={'Password'}
intent={(errors.password && touched.password) && Intent.DANGER}
helperText={<ErrorMessage name={'password'} {...{errors, touched}} />}
label={<T id={'password'} />}
intent={errors.password && touched.password && Intent.DANGER}
helperText={
<ErrorMessage name={'password'} {...{ errors, touched }} />
}
className={'form-group--password'}
>
<InputGroup
@@ -99,18 +107,31 @@ function ResetPassword({
{...getFieldProps('password')}
/>
</FormGroup>
<FormGroup
label={'New Password'}
label={<T id={'new_password'} />}
labelInfo={'(again):'}
intent={(errors.confirm_password && touched.confirm_password) && Intent.DANGER}
helperText={<ErrorMessage name={'confirm_password'} {...{errors, touched}} />}
intent={
errors.confirm_password &&
touched.confirm_password &&
Intent.DANGER
}
helperText={
<ErrorMessage
name={'confirm_password'}
{...{ errors, touched }}
/>
}
className={'form-group--confirm-password'}
>
<InputGroup
lang={true}
type={'password'}
intent={(errors.confirm_password && touched.confirm_password) && Intent.DANGER}
intent={
errors.confirm_password &&
touched.confirm_password &&
Intent.DANGER
}
{...getFieldProps('confirm_password')}
/>
</FormGroup>
@@ -121,8 +142,9 @@ function ResetPassword({
className={'btn-new'}
intent={Intent.PRIMARY}
type='submit'
loading={isSubmitting}>
Submit new password
loading={isSubmitting}
>
<T id={'submit_new_password'} />
</Button>
</div>
</form>
@@ -131,6 +153,4 @@ function ResetPassword({
);
}
export default compose(
withAuthenticationActions,
)(ResetPassword);
export default compose(withAuthenticationActions)(ResetPassword);

View File

@@ -1,7 +1,7 @@
import React, { useMemo } from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { Link, useHistory } from 'react-router-dom';
import { Button, InputGroup, Intent, FormGroup } from '@blueprintjs/core';
import { FormattedMessage } from 'react-intl';
@@ -15,23 +15,23 @@ import AuthInsider from 'containers/Authentication/AuthInsider';
import withAuthenticationActions from './withAuthenticationActions';
function SendResetPassword({
requestSendResetPassword,
}) {
const intl = useIntl();
function SendResetPassword({ requestSendResetPassword }) {
const { formatMessage } = useIntl();
const history = useHistory();
// Validation schema.
const ValidationSchema = Yup.object().shape({
crediential: Yup.string('')
.required(intl.formatMessage({ id: 'required' }))
.email(intl.formatMessage({ id: 'invalid_email_or_phone_numner' })),
.required(formatMessage({ id: 'required' }))
.email(formatMessage({ id: 'invalid_email_or_phone_numner' })),
});
const initialValues = useMemo(() => ({
crediential: '',
}), []);
const initialValues = useMemo(
() => ({
crediential: '',
}),
[]
);
// Formik validation
const {
@@ -60,9 +60,9 @@ function SendResetPassword({
setSubmitting(false);
})
.catch((errors) => {
if (errors.find(e => e.type === 'EMAIL.NOT.REGISTERED')){
if (errors.find((e) => e.type === 'EMAIL.NOT.REGISTERED')) {
AppToaster.show({
message: 'We couldn\'t find your account with that email',
message: "We couldn't find your account with that email",
intent: Intent.DANGER,
});
}
@@ -73,21 +73,29 @@ function SendResetPassword({
return (
<AuthInsider>
<div class='reset-form'>
<div class='reset-form'>
<div className={'authentication-page__label-section'}>
<h3>Reset Your Password</h3>
<p>Enter your email address and well send you a link to reset your password.</p>
<h3>
<T id={'reset_your_password'} />
</h3>
<p>
<T id={'we_ll_send_you_a_link_to_reset_your_password'} />
</p>
</div>
<form onSubmit={handleSubmit} className={'send-reset-password'}>
<FormGroup
label={'Email or Phone Number'}
intent={(errors.crediential && touched.crediential) && Intent.DANGER}
helperText={<ErrorMessage name={'crediential'} {...{errors, touched}} />}
intent={errors.crediential && touched.crediential && Intent.DANGER}
helperText={
<ErrorMessage name={'crediential'} {...{ errors, touched }} />
}
className={'form-group--crediential'}
>
<InputGroup
intent={(errors.crediential && touched.crediential) && Intent.DANGER}
intent={
errors.crediential && touched.crediential && Intent.DANGER
}
large={true}
{...getFieldProps('crediential')}
/>
@@ -100,14 +108,14 @@ function SendResetPassword({
fill={true}
loading={isSubmitting}
>
{intl.formatMessage({ id: 'Send password reset link' })}
<T id={'send_password_reset_link'} />
</Button>
</div>
</form>
<div class='authentication-page__footer-links'>
<Link to='/auth/login'>
<FormattedMessage id='Return to log in' />
<T id={'return_to_log_in'} />
</Link>
</div>
</div>
@@ -115,6 +123,4 @@ function SendResetPassword({
);
}
export default compose(
withAuthenticationActions,
)(SendResetPassword);
export default compose(withAuthenticationActions)(SendResetPassword);

View File

@@ -8,12 +8,13 @@ import {
TextArea,
MenuItem,
Checkbox,
Position
Position,
} from '@blueprintjs/core';
import { Select } from '@blueprintjs/select';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { omit } from 'lodash';
import { useQuery, queryCache } from 'react-query';
@@ -27,7 +28,6 @@ import Icon from 'components/Icon';
import ErrorMessage from 'components/ErrorMessage';
import { fetchAccountTypes } from 'store/accounts/accounts.actions';
function AccountFormDialog({
name,
payload,
@@ -60,22 +60,26 @@ function AccountFormDialog({
description: Yup.string().trim()
});
const initialValues = useMemo(() => ({
account_type_id: null,
name: '',
description: '',
}), []);
const initialValues = useMemo(
() => ({
account_type_id: null,
name: '',
description: '',
}),
[]
);
const [selectedAccountType, setSelectedAccountType] = useState(null);
const [selectedSubaccount, setSelectedSubaccount] = useState(
payload.action === 'new_child' ?
accounts.find(a => a.id === payload.id) : null,
payload.action === 'new_child'
? accounts.find((a) => a.id === payload.id)
: null
);
const transformApiErrors = (errors) => {
const fields = {};
if (errors.find(e => e.type === 'NOT_UNIQUE_CODE')) {
fields.code = 'Account code is not unqiue.'
if (errors.find((e) => e.type === 'NOT_UNIQUE_CODE')) {
fields.code = 'Account code is not unqiue.';
}
return fields;
};
@@ -84,7 +88,7 @@ function AccountFormDialog({
const formik = useFormik({
enableReinitialize: true,
initialValues: {
...(payload.action === 'edit' && account) ? account : initialValues,
...(payload.action === 'edit' && account ? account : initialValues),
},
validationSchema: accountFormValidationSchema,
onSubmit: (values, { setSubmitting, setErrors }) => {
@@ -106,11 +110,6 @@ function AccountFormDialog({
}),
intent: Intent.SUCCESS,
});
setSubmitting(false);
queryCache.refetchQueries('accounts-table', { force: true });
}).catch((errors) => {
setSubmitting(false);
setErrors(transformApiErrors(errors));
});
} else {
requestSubmitAccount({ form: { ...omit(values, exclude) } }).then((response) => {
@@ -125,22 +124,18 @@ function AccountFormDialog({
intent: Intent.SUCCESS,
position: Position.BOTTOM,
});
setSubmitting(false);
queryCache.refetchQueries('accounts-table', { force: true });
}).catch((errors) => {
setSubmitting(false);
setErrors(transformApiErrors(errors));
});
}
}
},
});
const { errors, values, touched } = useMemo(() => (formik), [formik]);
const { errors, values, touched } = useMemo(() => formik, [formik]);
// Set default account type.
useEffect(() => {
if (account && account.account_type_id) {
const defaultType = accountsTypes.find((t) =>
t.id === account.account_type_id);
const defaultType = accountsTypes.find(
(t) => t.id === account.account_type_id
);
defaultType && setSelectedAccountType(defaultType);
}
@@ -166,44 +161,64 @@ function AccountFormDialog({
// Account item of select accounts field.
const accountItem = (item, { handleClick, modifiers, query }) => {
return (
<MenuItem text={item.name} label={item.code} key={item.id} onClick={handleClick} />
<MenuItem
text={item.name}
label={item.code}
key={item.id}
onClick={handleClick}
/>
);
};
// Filters accounts items.
const filterAccountsPredicater = useCallback((query, account, _index, exactMatch) => {
const normalizedTitle = account.name.toLowerCase();
const normalizedQuery = query.toLowerCase();
const filterAccountsPredicater = useCallback(
(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;
}
}, []);
if (exactMatch) {
return normalizedTitle === normalizedQuery;
} else {
return (
`${account.code} ${normalizedTitle}`.indexOf(normalizedQuery) >= 0
);
}
},
[]
);
// Handles dialog close.
const handleClose = useCallback(() => { closeDialog(name); }, [closeDialog, name]);
const handleClose = useCallback(() => {
closeDialog(name);
}, [closeDialog, name]);
// Fetches accounts list.
const fetchAccountsList = useQuery('accounts-list',
() => requestFetchAccounts(), { manual: true });
const fetchAccountsList = useQuery(
'accounts-list',
() => requestFetchAccounts(),
{ manual: true }
);
// Fetches accounts types.
const fetchAccountsTypes = useQuery('accounts-types-list', async () => {
await requestFetchAccountTypes();
}, { manual: true });
const fetchAccountsTypes = useQuery(
'accounts-types-list',
async () => {
await requestFetchAccountTypes();
},
{ manual: true }
);
// Fetch the given account id on edit mode.
const fetchAccount = useQuery(
payload.action === 'edit' && ['account', payload.id],
(key, id) => requestFetchAccount(id),
{ manual: true });
{ manual: true }
);
const isFetching = (
fetchAccountsList.isFetching ||
fetchAccountTypes.isFetching ||
fetchAccount.isFetching);
const isFetching =
fetchAccountsList.isFetching ||
fetchAccountTypes.isFetching ||
fetchAccount.isFetching;
// Fetch requests on dialog opening.
const onDialogOpening = useCallback(() => {
@@ -212,16 +227,22 @@ function AccountFormDialog({
fetchAccount.refetch();
}, []);
const onChangeAccountType = useCallback((accountType) => {
setSelectedAccountType(accountType);
formik.setFieldValue('account_type_id', accountType.id);
}, [setSelectedAccountType, formik]);
const onChangeAccountType = useCallback(
(accountType) => {
setSelectedAccountType(accountType);
formik.setFieldValue('account_type_id', accountType.id);
},
[setSelectedAccountType, formik]
);
// Handles change sub-account.
const onChangeSubaccount = useCallback((account) => {
setSelectedSubaccount(account);
formik.setFieldValue('parent_account_id', account.id);
}, [setSelectedSubaccount, formik]);
const onChangeSubaccount = useCallback(
(account) => {
setSelectedSubaccount(account);
formik.setFieldValue('parent_account_id', account.id);
},
[setSelectedSubaccount, formik]
);
const onDialogClosed = useCallback(() => {
formik.resetForm();
@@ -229,21 +250,25 @@ function AccountFormDialog({
setSelectedAccountType(null);
}, [formik]);
const infoIcon = useMemo(() => (<Icon icon="info-circle" iconSize={12} />), []);
const infoIcon = useMemo(() => <Icon icon='info-circle' iconSize={12} />, []);
const subAccountLabel = useMemo(() => {
return (<span>{'Sub account?'} <Icon icon="info-circle" iconSize={12} /></span>);
return (
<span>
<T id={'sub_account'}/> <Icon icon='info-circle' iconSize={12} />
</span>
);
}, []);
const requiredSpan = useMemo(() => (<span class="required">*</span>), []);
const requiredSpan = useMemo(() => <span class='required'>*</span>, []);
return (
<Dialog
name={name}
title={payload.action === 'edit' ? 'Edit Account' : 'New Account'}
title={payload.action === 'edit' ? <T id={'edit_account'}/> : <T id={'new_account'}/>}
className={{
'dialog--loading': isFetching,
'dialog--account-form': true
'dialog--account-form': true,
}}
autoFocus={true}
canEscapeKeyClose={true}
@@ -256,15 +281,18 @@ function AccountFormDialog({
<form onSubmit={formik.handleSubmit}>
<div className={Classes.DIALOG_BODY}>
<FormGroup
label={'Account Type'}
label={<T id={'account_type'}/>}
labelInfo={requiredSpan}
className={classNames(
'form-group--account-type',
'form-group--select-list',
Classes.FILL)}
Classes.FILL
)}
inline={true}
helperText={<ErrorMessage name="account_type_id" {...formik} />}
intent={(errors.account_type_id && touched.account_type_id) && Intent.DANGER}
helperText={<ErrorMessage name='account_type_id' {...formik} />}
intent={
errors.account_type_id && touched.account_type_id && Intent.DANGER
}
>
<Select
items={accountsTypes}
@@ -275,40 +303,38 @@ function AccountFormDialog({
onItemSelect={onChangeAccountType}
>
<Button
rightIcon='caret-down'
text={selectedAccountType ?
selectedAccountType.name : 'Select account type'}
text={selectedAccountType ? selectedAccountType.name : <T id={'select_account_type'} />}
disabled={payload.action === 'edit'}
/>
</Select>
</FormGroup>
<FormGroup
label={'Account Name'}
label={<T id={'account_name'}/>}
labelInfo={requiredSpan}
className={'form-group--account-name'}
intent={(errors.name && touched.name) && Intent.DANGER}
helperText={<ErrorMessage name="name" {...formik} />}
intent={errors.name && touched.name && Intent.DANGER}
helperText={<ErrorMessage name='name' {...formik} />}
inline={true}
>
<InputGroup
medium={true}
intent={(errors.name && touched.name) && Intent.DANGER}
intent={errors.name && touched.name && Intent.DANGER}
{...formik.getFieldProps('name')}
/>
</FormGroup>
<FormGroup
label={'Account Code'}
label={<T id={'account_code'}/>}
className={'form-group--account-code'}
intent={(errors.code && touched.code) && Intent.DANGER}
helperText={<ErrorMessage name="code" {...formik} />}
intent={errors.code && touched.code && Intent.DANGER}
helperText={<ErrorMessage name='code' {...formik} />}
inline={true}
labelInfo={infoIcon}
>
<InputGroup
medium={true}
intent={(errors.code && touched.code) && Intent.DANGER}
intent={errors.code && touched.code && Intent.DANGER}
{...formik.getFieldProps('code')}
/>
</FormGroup>
@@ -327,11 +353,12 @@ function AccountFormDialog({
{values.subaccount && (
<FormGroup
label={'Parent Account'}
label={<T id={'parent_account'}/>}
className={classNames(
'form-group--parent-account',
'form-group--select-list',
Classes.FILL)}
Classes.FILL
)}
inline={true}
>
<Select
@@ -346,7 +373,9 @@ function AccountFormDialog({
<Button
rightIcon='caret-down'
text={
selectedSubaccount ? selectedSubaccount.name : 'Select Parent Account'
selectedSubaccount
? selectedSubaccount.name
: 'Select Parent Account'
}
/>
</Select>
@@ -354,7 +383,7 @@ function AccountFormDialog({
)}
<FormGroup
label={'Description'}
label={<T id={'description'}/>}
className={'form-group--description'}
intent={formik.errors.description && Intent.DANGER}
helperText={formik.errors.description && formik.errors.credential}
@@ -370,9 +399,13 @@ function AccountFormDialog({
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button onClick={handleClose}>Close</Button>
<Button intent={Intent.PRIMARY} disabled={formik.isSubmitting} type='submit'>
{payload.action === 'edit' ? 'Edit' : 'Submit'}
<Button onClick={handleClose}><T id={'close'}/></Button>
<Button
intent={Intent.PRIMARY}
disabled={formik.isSubmitting}
type='submit'
>
{payload.action === 'edit' ? <T id={'edit'}/> : <T id={'submit'}/>}
</Button>
</div>
</div>
@@ -381,6 +414,4 @@ function AccountFormDialog({
);
}
export default AccountFormDialogContainer(
AccountFormDialog,
);
export default AccountFormDialogContainer(AccountFormDialog);

View File

@@ -7,7 +7,7 @@ import {
Intent,
} from '@blueprintjs/core';
import * as Yup from 'yup';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { useFormik } from 'formik';
import { useQuery } from 'react-query';
import { connect } from 'react-redux';
@@ -44,15 +44,15 @@ function CurrencyDialog({
requestSubmitCurrencies,
requestEditCurrency,
}) {
const intl = useIntl();
const {formatMessage} = useIntl();
const ValidationSchema = Yup.object().shape({
currency_name: Yup.string().required(
intl.formatMessage({ id: 'required' })
formatMessage({ id: 'required' })
),
currency_code: Yup.string()
.max(4)
.required(intl.formatMessage({ id: 'required' })),
.required(formatMessage({ id: 'required' })),
});
const initialValues = useMemo(() => ({
currency_name: '',
@@ -126,7 +126,7 @@ function CurrencyDialog({
return (
<Dialog
name={name}
title={payload.action === 'edit' ? 'Edit Currency' : ' New Currency'}
title={payload.action === 'edit' ? <T id={'edit_currency'}/> : <T id={'new_currency'}/>}
className={classNames(
{
'dialog--loading': fetchCurrencies.isFetching,
@@ -142,7 +142,7 @@ function CurrencyDialog({
<form onSubmit={handleSubmit}>
<div className={Classes.DIALOG_BODY}>
<FormGroup
label={'Currency Name'}
label={<T id={'currency_name'}/>}
labelInfo={requiredSpan}
className={'form-group--currency-name'}
intent={(errors.currency_name && touched.currency_name) && Intent.DANGER}
@@ -157,7 +157,7 @@ function CurrencyDialog({
</FormGroup>
<FormGroup
label={'Currency Code'}
label={<T id={'currency_code'}/>}
labelInfo={requiredSpan}
className={'form-group--currency-code'}
intent={(errors.currency_code && touched.currency_code) && Intent.DANGER}
@@ -174,9 +174,9 @@ function CurrencyDialog({
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button onClick={handleClose}>Close</Button>
<Button onClick={handleClose}><T id={'cancel'} /></Button>
<Button intent={Intent.PRIMARY} type='submit' disabled={isSubmitting}>
{payload.action === 'edit' ? 'Edit' : 'Submit'}
{payload.action === 'edit' ? <T id={'edit'} /> : <T id={'submit'} /> }
</Button>
</div>
</div>

View File

@@ -0,0 +1,35 @@
import { connect } from 'react-redux';
import { compose } from 'utils';
import { getDialogPayload } from 'store/dashboard/dashboard.reducer';
import DialogConnect from 'connectors/Dialog.connector';
import DialogReduxConnect from 'components/DialogReduxConnect';
import withExchangeRatesActions from 'containers/ExchangeRates/withExchangeRatesActions';
import withExchangeRates from 'containers/ExchangeRates/withExchangeRates';
import withCurrencies from 'containers/Currencies/withCurrencies';
const mapStateToProps = (state, props) => {
const dialogPayload = getDialogPayload(state, 'exchangeRate-form');
return {
name: 'exchangeRate-form',
payload: { action: 'new', id: null, ...dialogPayload },
};
};
const withExchangeRateDialog = connect(mapStateToProps);
export default compose(
withExchangeRateDialog,
withCurrencies(({ currenciesList }) => ({
currenciesList,
})),
withExchangeRatesActions,
withExchangeRates(({ exchangeRatesList }) => ({
exchangeRatesList,
})),
DialogReduxConnect,
DialogConnect,
);

View File

@@ -0,0 +1,267 @@
import React, { useState, useMemo, useCallback, useEffect } from 'react';
import {
Button,
Classes,
FormGroup,
InputGroup,
Intent,
Position,
MenuItem,
} from '@blueprintjs/core';
import { pick } from 'lodash';
import * as Yup from 'yup';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { useFormik } from 'formik';
import Dialog from 'components/Dialog';
import AppToaster from 'components/AppToaster';
import { useQuery, queryCache } from 'react-query';
import ErrorMessage from 'components/ErrorMessage';
import classNames from 'classnames';
import { Select } from '@blueprintjs/select';
import moment from 'moment';
import { DateInput } from '@blueprintjs/datetime';
import { momentFormatter } from 'utils';
import withExchangeRatesDialog from './ExchangeRateDialog.container';
function ExchangeRateDialog({
name,
payload,
isOpen,
// #withDialog
closeDialog,
// #withCurrencies
currenciesList,
// #withExchangeRatesActions
requestSubmitExchangeRate,
requestFetchExchangeRates,
requestEditExchangeRate,
requestFetchCurrencies,
editExchangeRate,
}) {
const { formatMessage } = useIntl();
const [selectedItems, setSelectedItems] = useState({});
const validationSchema = Yup.object().shape({
exchange_rate: Yup.number().required(),
currency_code: Yup.string().max(3).required(),
date: Yup.date().required(),
});
const initialValues = useMemo(() => ({
exchange_rate: '',
currency_code: '',
date: moment(new Date()).format('YYYY-MM-DD'),
}), []);
const {
values,
touched,
errors,
isSubmitting,
handleSubmit,
getFieldProps,
setFieldValue,
resetForm,
} = useFormik({
enableReinitialize: true,
validationSchema,
initialValues: {
...(payload.action === 'edit' &&
pick(editExchangeRate, Object.keys(initialValues))),
},
onSubmit: (values, { setSubmitting }) => {
if (payload.action === 'edit') {
requestEditExchangeRate(payload.id, values)
.then((response) => {
closeDialog(name);
AppToaster.show({
message: 'the_exchange_rate_has_been_edited',
});
setSubmitting(false);
})
.catch((error) => {
setSubmitting(false);
});
} else {
requestSubmitExchangeRate(values)
.then((response) => {
closeDialog(name);
AppToaster.show({
message: 'the_exchangeRate_has_been_submit',
});
setSubmitting(false);
})
.catch((error) => {
setSubmitting(false);
});
}
},
});
const requiredSpan = useMemo(() => <span class='required'>*</span>, []);
const handleClose = useCallback(() => {
closeDialog(name);
}, [name, closeDialog]);
const fetchExchangeRatesDialog = useQuery('exchange-rates-dialog',
() => requestFetchExchangeRates());
const onDialogClosed = useCallback(() => {
resetForm();
closeDialog(name);
}, [closeDialog, name]);
const onDialogOpening = useCallback(() => {
fetchExchangeRatesDialog.refetch();
}, [fetchExchangeRatesDialog]);
const handleDateChange = useCallback(
(date) => {
const formatted = moment(date).format('YYYY-MM-DD');
setFieldValue('date', formatted);
},
[setFieldValue]
);
const onItemsSelect = useCallback(
(filedName) => {
return (filed) => {
setSelectedItems({
...selectedItems,
[filedName]: filed,
});
setFieldValue(filedName, filed.currency_code);
};
},
[setFieldValue, selectedItems]
);
const filterCurrencyCode = (query, currency_code, _index, exactMatch) => {
const normalizedTitle = currency_code.currency_code.toLowerCase();
const normalizedQuery = query.toLowerCase();
if (exactMatch) {
return normalizedTitle === normalizedQuery;
} else {
return (
`${currency_code.currency_code} ${normalizedTitle}`.indexOf(
normalizedQuery
) >= 0
);
}
};
const currencyCodeRenderer = useCallback((CurrencyCode, { handleClick }) => {
return (
<MenuItem
className={'exchangeRate-menu'}
key={CurrencyCode.id}
text={CurrencyCode.currency_code}
onClick={handleClick}
/>
);
}, []);
const getSelectedItemLabel = useCallback((fieldName, defaultLabel) => {
return typeof selectedItems[fieldName] !== 'undefined'
? selectedItems[fieldName].currency_code
: defaultLabel;
}, [selectedItems]);
return (
<Dialog
name={name}
title={payload.action === 'edit'
? <T id={'edit_exchange_rate'}/> : <T id={'new_exchange_rate'}/>}
className={classNames(
{'dialog--loading': fetchExchangeRatesDialog.isFetching},
'dialog--exchangeRate-form'
)}
isOpen={isOpen}
onClosed={onDialogClosed}
onOpening={onDialogOpening}
isLoading={fetchExchangeRatesDialog.isFetching}
onClose={handleClose}
>
<form onSubmit={handleSubmit}>
<div className={Classes.DIALOG_BODY}>
<FormGroup
label={<T id={'date'}/>}
inline={true}
labelInfo={requiredSpan}
intent={errors.date && touched.date && Intent.DANGER}
helperText={<ErrorMessage name='date' {...{errors, touched}} />}
>
<DateInput
fill={true}
{...momentFormatter('YYYY-MM-DD')}
defaultValue={new Date()}
onChange={handleDateChange}
popoverProps={{ position: Position.BOTTOM }}
// disabled={payload.action === 'edit'}
/>
</FormGroup>
<FormGroup
label={<T id={'exchange_rate'}/>}
labelInfo={requiredSpan}
intent={errors.exchange_rate && touched.exchange_rate && Intent.DANGER}
helperText={<ErrorMessage name='exchange_rate' {...{errors, touched}} />}
inline={true}
>
<InputGroup
medium={true}
intent={errors.exchange_rate && touched.exchange_rate && Intent.DANGER}
{...getFieldProps('exchange_rate')}
/>
</FormGroup>
<FormGroup
label={<T id={'currency_code'}/>}
labelInfo={requiredSpan}
className={classNames('form-group--select-list', Classes.FILL)}
inline={true}
intent={(errors.currency_code && touched.currency_code) && Intent.DANGER}
helperText={<ErrorMessage name='currency_code' {...{errors, touched}} />}
>
<Select
items={currenciesList}
noResults={<MenuItem disabled={true} text='No results.' />}
itemRenderer={currencyCodeRenderer}
itemPredicate={filterCurrencyCode}
popoverProps={{ minimal: true }}
onItemSelect={onItemsSelect('currency_code')}
>
<Button
rightIcon='caret-down'
fill={true}
text={getSelectedItemLabel(
'currency_code',
'select Currency Code'
)}
/>
</Select>
</FormGroup>
</div>
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button onClick={handleClose}><T id={'close'}/></Button>
<Button intent={Intent.PRIMARY} type='submit' disabled={isSubmitting}>
{payload.action === 'edit' ? <T id={'edit'}/> : <T id={'submit'}/>}
</Button>
</div>
</div>
</form>
</Dialog>
);
}
export default withExchangeRatesDialog(ExchangeRateDialog);

View File

@@ -1,5 +1,5 @@
import React, { useMemo, useCallback } from 'react';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import {
@@ -28,7 +28,7 @@ function InviteUserDialog({
requestFetchUser,
requestEditUser,
}) {
const intl = useIntl();
const { formatMessage } = useIntl();
const fetchHook = useAsync(async () => {
await Promise.all([
@@ -37,12 +37,12 @@ function InviteUserDialog({
}, false);
const validationSchema = Yup.object().shape({
first_name: Yup.string().required(intl.formatMessage({ id: 'required' })),
last_name: Yup.string().required(intl.formatMessage({ id: 'required' })),
first_name: Yup.string().required(formatMessage({ id: 'required' })),
last_name: Yup.string().required(formatMessage({ id: 'required' })),
email: Yup.string()
.email()
.required(intl.formatMessage({ id: 'required' })),
phone_number: Yup.number().required(intl.formatMessage({ id: 'required' })),
.required(formatMessage({ id: 'required' })),
phone_number: Yup.number().required(formatMessage({ id: 'required' })),
});
const initialValues = useMemo(
@@ -101,7 +101,7 @@ function InviteUserDialog({
return (
<Dialog
name={name}
title={payload.action === 'edit' ? 'Edit invite' : ''}
title={payload.action === 'edit' ? <T id={'edit_invite'} /> : ''}
className={classNames({
'dialog--loading': fetchHook.pending,
'dialog--invite-user': true,
@@ -116,7 +116,7 @@ function InviteUserDialog({
<form onSubmit={formik.handleSubmit}>
<div className={Classes.DIALOG_BODY}>
<FormGroup
label={'First Name'}
label={<T id={'first_name'} />}
className={'form-group--first-name'}
intent={errors.first_name && touched.first_name && Intent.DANGER}
helperText={<ErrorMessage name='first_name' {...formik} />}
@@ -129,7 +129,7 @@ function InviteUserDialog({
</FormGroup>
<FormGroup
label={'Last Name'}
label={<T id={'last_name'} />}
className={'form-group--last-name'}
intent={errors.last_name && touched.last_name && Intent.DANGER}
helperText={<ErrorMessage name='last_name' {...formik} />}
@@ -142,7 +142,7 @@ function InviteUserDialog({
</FormGroup>
<FormGroup
label={'Email'}
label={<T id={'email'} />}
className={'form-group--email'}
intent={errors.email && touched.email && Intent.DANGER}
helperText={<ErrorMessage name='email' {...formik} />}
@@ -156,7 +156,7 @@ function InviteUserDialog({
</FormGroup>
<FormGroup
label={'Phone Number'}
label={<T id={'phone_number'} />}
className={'form-group--phone-number'}
intent={
errors.phone_number && touched.phone_number && Intent.DANGER
@@ -175,9 +175,9 @@ function InviteUserDialog({
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button onClick={handleClose}>Close</Button>
<Button onClick={handleClose}><T id={'close'}/></Button>
<Button intent={Intent.PRIMARY} type='submit'>
{payload.action === 'edit' ? 'Edit' : ''}
{payload.action === 'edit' ? <T id={'edit'}/> : ''}
</Button>
</div>
</div>

View File

@@ -11,7 +11,7 @@ import {
import { Select } from '@blueprintjs/select';
import { pick } from 'lodash';
import * as Yup from 'yup';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { useFormik } from 'formik';
import { compose } from 'utils';
import { useQuery, queryCache } from 'react-query';
@@ -165,7 +165,7 @@ function ItemCategoryDialog({
return (
<Dialog
name={name}
title={payload.action === 'edit' ? 'Edit Category' : ' New Category'}
title={payload.action === 'edit' ? <T id={'edit_category'}/> : <T id={'new_category'}/>}
className={classNames({
'dialog--loading': fetchList.isFetching,
},
@@ -180,7 +180,7 @@ function ItemCategoryDialog({
<form onSubmit={handleSubmit}>
<div className={Classes.DIALOG_BODY}>
<FormGroup
label={'Category Name'}
label={<T id={'category_name'}/>}
labelInfo={requiredSpan}
className={'form-group--category-name'}
intent={(errors.name && touched.name) && Intent.DANGER}
@@ -195,7 +195,7 @@ function ItemCategoryDialog({
</FormGroup>
<FormGroup
label={'Parent Category'}
label={<T id={'parent_category'}/>}
labelInfo={infoIcon}
className={classNames(
'form-group--select-list',
@@ -215,7 +215,6 @@ function ItemCategoryDialog({
onItemSelect={onChangeParentCategory}
>
<Button
rightIcon='caret-down'
text={selectedParentCategory
? selectedParentCategory.name : 'Select Parent Category'}
/>
@@ -223,7 +222,7 @@ function ItemCategoryDialog({
</FormGroup>
<FormGroup
label={'Description'}
label={<T id={'description'}/>}
className={'form-group--description'}
intent={(errors.description && touched.description) && Intent.DANGER}
helperText={(<ErrorMessage name="description" {...{errors, touched}} />)}
@@ -239,9 +238,9 @@ function ItemCategoryDialog({
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button onClick={handleClose}>Close</Button>
<Button onClick={handleClose}><T id={'close'}/></Button>
<Button intent={Intent.PRIMARY} type='submit' disabled={isSubmitting}>
{payload.action === 'edit' ? 'Edit' : 'Submit'}
{payload.action === 'edit' ? <T id={'edit'}/> : <T id={'submit'}/>}
</Button>
</div>
</div>

View File

@@ -5,10 +5,10 @@ import {
FormGroup,
InputGroup,
Intent,
TextArea
TextArea,
} from '@blueprintjs/core';
import * as Yup from 'yup';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { useFormik } from 'formik';
import { compose } from 'utils';
import Dialog from 'components/Dialog';
@@ -25,30 +25,30 @@ function ItemFromDialog({
submitItemCategory,
fetchCategory,
openDialog,
closeDialog
closeDialog,
}) {
const [state, setState] = useState({});
const intl = useIntl();
const { formatMessage } = useIntl();
const ValidationSchema = Yup.object().shape({
name: Yup.string().required(intl.formatMessage({ id: 'required' })),
description: Yup.string().trim()
name: Yup.string().required(formatMessage({ id: 'required' })),
description: Yup.string().trim(),
});
const formik = useFormik({
enableReinitialize: true,
initialValues: {},
validationSchema: ValidationSchema,
onSubmit: values => {
onSubmit: (values) => {
submitItemCategory({ values })
.then(response => {
.then((response) => {
AppToaster.show({
message: 'the_category_has_been_submit'
message: 'the_category_has_been_submit',
});
})
.catch(error => {
.catch((error) => {
alert(error.message);
});
}
},
});
const fetchHook = useAsync(async () => {
@@ -71,10 +71,12 @@ function ItemFromDialog({
return (
<Dialog
name={name}
title={payload.action === 'new' ? 'New' : ' New Category'}
title={
payload.action === 'new' ? <T id={'new'} /> : <T id={'new_category'} />
}
className={{
'dialog--loading': state.isLoading,
'dialog--item-form': true
'dialog--item-form': true,
}}
isOpen={isOpen}
onClosed={onDialogClosed}
@@ -84,7 +86,7 @@ function ItemFromDialog({
<form onSubmit={formik.handleSubmit}>
<div className={Classes.DIALOG_BODY}>
<FormGroup
label={'Category Name'}
label={<T id={'category_name'} />}
className={'form-group--category-name'}
intent={formik.errors.name && Intent.DANGER}
helperText={formik.errors.name && formik.errors.name}
@@ -97,7 +99,7 @@ function ItemFromDialog({
/>
</FormGroup>
<FormGroup
label={'Description'}
label={<T id={'description'} />}
className={'form-group--description'}
intent={formik.errors.description && Intent.DANGER}
helperText={formik.errors.description && formik.errors.credential}
@@ -112,9 +114,15 @@ function ItemFromDialog({
</div>
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button onClick={handleClose}>Close</Button>
<Button onClick={handleClose}>
<T id={'close'} />
</Button>
<Button intent={Intent.PRIMARY} type='submit'>
{payload.action === 'new' ? 'New' : 'Submit'}
{payload.action === 'new' ? (
<T id={'new'} />
) : (
<T id={'submit'} />
)}
</Button>
</div>
</div>

View File

@@ -1,5 +1,5 @@
import React, { useMemo, useCallback } from 'react';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import {
@@ -87,7 +87,13 @@ function UserFormDialog({
return (
<Dialog
name={name}
title={payload.action === 'edit' ? 'Edit invite' : 'invite User'}
title={
payload.action === 'edit' ? (
<T id={'edit_invite'} />
) : (
<T id={'invite_user'} />
)
}
className={classNames({
'dialog--loading': fetchHook.pending,
'dialog--invite-form': true,
@@ -101,18 +107,20 @@ function UserFormDialog({
>
<form onSubmit={handleSubmit}>
<div className={Classes.DIALOG_BODY}>
<p class="mb2">Your teammate will get an email that gives them access to your team.</p>
<p class='mb2'>
<T id={'your_access_to_your_team'} />
</p>
<FormGroup
label={'Email'}
label={<T id={'email'} />}
className={classNames('form-group--email', Classes.FILL)}
intent={(errors.email && touched.email) && Intent.DANGER}
helperText={<ErrorMessage name='email' {...{errors, touched}} />}
intent={errors.email && touched.email && Intent.DANGER}
helperText={<ErrorMessage name='email' {...{ errors, touched }} />}
inline={true}
>
<InputGroup
medium={true}
intent={(errors.email && touched.email) && Intent.DANGER}
intent={errors.email && touched.email && Intent.DANGER}
{...getFieldProps('email')}
/>
</FormGroup>
@@ -120,9 +128,9 @@ function UserFormDialog({
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button onClick={handleClose}>Close</Button>
<Button onClick={handleClose}><T id={'cancel'} /></Button>
<Button intent={Intent.PRIMARY} type='submit' disabled={isSubmitting}>
{payload.action === 'edit' ? 'Edit' : 'invite'}
{payload.action === 'edit' ? <T id={'edit'} /> : <T id={'invite'} />}
</Button>
</div>
</div>

View File

@@ -0,0 +1,132 @@
import React, { useEffect, useState, useCallback } from 'react';
import { useQuery } from 'react-query';
import { useParams } from 'react-router-dom';
import { Alert, Intent } from '@blueprintjs/core';
import AppToaster from 'components/AppToaster';
import DashboardPageContent from 'components/Dashboard/DashboardPageContent';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import ExchangeRateTable from './ExchangeRateTable';
import ExchangeRateActionsBar from './ExchangeRateActionsBar';
import withDashboardActions from 'containers/Dashboard/withDashboard';
import withResourceActions from 'containers/Resources/withResourcesActions';
import withExchangeRatesActions from 'containers/ExchangeRates/withExchangeRatesActions';
import { compose } from 'utils';
import { FormattedMessage as T, useIntl } from 'react-intl';
function ExchangeRate({
// #withDashboard
changePageTitle,
//#withResourceActions
requestFetchResourceFields,
// #withExchangeRatesActions
requestFetchExchangeRates,
requestDeleteExchangeRate,
addExchangeRatesTableQueries,
}) {
const { id } = useParams();
const [deleteExchangeRate, setDeleteExchangeRate] = useState(false);
const [selectedRows, setSelectedRows] = useState([]);
const { formatMessage } = useIntl();
// const fetchExchangeRates = useQuery('exchange-rates-table', () => {
// return Promise.all([requestFetchExchangeRates()]);
// });
const fetchExchangeRates = useQuery('exchange-rates-table',
() => requestFetchExchangeRates(),
{ refetchInterval: 3000 });
useEffect(() => {
id
? changePageTitle(formatMessage({id:'exchange_rate_details'}))
: changePageTitle(formatMessage({id:'exchange_rate_list'}));
}, [id, changePageTitle]);
const handelDeleteExchangeRate = useCallback(
(exchange_rate) => {
setDeleteExchangeRate(exchange_rate);
},
[setDeleteExchangeRate]
);
const handelEditExchangeRate = (exchange_rate) => {};
const handelCancelExchangeRateDelete = useCallback(() => {
setDeleteExchangeRate(false);
}, [setDeleteExchangeRate]);
const handelConfirmExchangeRateDelete = useCallback(() => {
requestDeleteExchangeRate(deleteExchangeRate.id).then(() => {
setDeleteExchangeRate(false);
AppToaster.show({
message: 'the_exchange_rate_has_been_delete',
});
});
}, [deleteExchangeRate, requestDeleteExchangeRate]);
// Handle fetch data of Exchange_rates datatable.
const handleFetchData = useCallback(
({ pageIndex, pageSize, sortBy }) => {
addExchangeRatesTableQueries({
...(sortBy.length > 0
? {
column_sort_by: sortBy[0].id,
sort_order: sortBy[0].desc ? 'desc' : 'asc',
}
: {}),
});
},
[addExchangeRatesTableQueries]
);
const handleSelectedRowsChange = useCallback(
(exchange_rates) => {
setSelectedRows(exchange_rates);
},
[setSelectedRows]
);
return (
<DashboardInsider>
<ExchangeRateActionsBar
onDeleteExchangeRate={handelDeleteExchangeRate}
selectedRows={selectedRows}
/>
<DashboardPageContent>
<ExchangeRateTable
onDeleteExchangeRate={handelDeleteExchangeRate}
onEditExchangeRate={handelEditExchangeRate}
onFetchData={handleFetchData}
onSelectedRowsChange={handleSelectedRowsChange}
/>
<Alert
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={<T id={'move_to_trash'} />}
icon='trash'
intent={Intent.DANGER}
isOpen={deleteExchangeRate}
onCancel={handelCancelExchangeRateDelete}
onConfirm={handelConfirmExchangeRateDelete}
>
<p>
Are you sure you want to move <b>filename</b> to Trash? You will be
able to restore it later, but it will become private to you.
</p>
</Alert>
</DashboardPageContent>
</DashboardInsider>
);
}
export default compose(
withExchangeRatesActions,
withResourceActions,
withDashboardActions
)(ExchangeRate);

View File

@@ -0,0 +1,125 @@
import React, { useCallback, useState, useMemo } from 'react';
import {
NavbarGroup,
Button,
Classes,
Intent,
Popover,
Position,
PopoverInteractionKind,
} from '@blueprintjs/core';
import classNames from 'classnames';
import Icon from 'components/Icon';
import { connect } from 'react-redux';
import DashboardActionsBar from 'components/Dashboard/DashboardActionsBar';
import DialogConnect from 'connectors/Dialog.connector';
import FilterDropdown from 'components/FilterDropdown';
import withResourceDetail from 'containers/Resources/withResourceDetails';
import { compose } from 'utils';
import { FormattedMessage as T } from 'react-intl';
function ExchangeRateActionsBar({
// #withDialog.
openDialog,
// #withResourceDetail
resourceFields,
selectedRows = [],
onDeleteExchangeRate,
onFilterChanged,
}) {
const [filterCount, setFilterCount] = useState(0);
const onClickNewExchangeRate = () => {
openDialog('exchangeRate-form', {});
};
const filterDropdown = FilterDropdown({
fields: resourceFields,
onFilterChange: (filterConditions) => {
setFilterCount(filterConditions.length || 0);
onFilterChanged && onFilterChanged(filterConditions);
},
});
const handelDeleteExchangeRate = useCallback(
(exchangeRate) => {
onDeleteExchangeRate(exchangeRate);
},
[selectedRows, onDeleteExchangeRate]
);
const hasSelectedRows = useMemo(() => selectedRows.length > 0, [
selectedRows,
]);
return (
<DashboardActionsBar>
<NavbarGroup>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='plus' />}
text={<T id={'new_exchange_rate'} />}
onClick={onClickNewExchangeRate}
/>
<Popover
minimal={true}
content={filterDropdown}
interactionKind={PopoverInteractionKind.CLICK}
position={Position.BOTTOM_LEFT}
>
<Button
className={classNames(Classes.MINIMAL, 'button--filter')}
text={
filterCount <= 0 ? (
<T id={'filter'} />
) : (
`${filterCount} filters applied`
)
}
icon={<Icon icon='filter' />}
/>
</Popover>
{hasSelectedRows && (
<Button
className={Classes.MINIMAL}
icon={<Icon icon='trash' iconSize={15} />}
text={<T id={'delete'} />}
intent={Intent.DANGER}
onClick={handelDeleteExchangeRate}
/>
)}
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-import' />}
text={<T id={'import'} />}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-export' />}
text={<T id={'export'} />}
/>
</NavbarGroup>
</DashboardActionsBar>
);
}
const mapStateToProps = (state, props) => ({
resourceName: 'exchange_rates',
});
const withExchangeRateActionBar = connect(mapStateToProps);
export default compose(
withExchangeRateActionBar,
DialogConnect,
withResourceDetail(({ resourceFields }) => ({
resourceFields,
}))
)(ExchangeRateActionsBar);

View File

@@ -0,0 +1,136 @@
import React, { useCallback, useMemo,useState } from 'react';
import Icon from 'components/Icon';
import DialogConnect from 'connectors/Dialog.connector';
import LoadingIndicator from 'components/LoadingIndicator';
import DataTable from 'components/DataTable';
import { Button, Popover, Menu, MenuItem, Position } from '@blueprintjs/core';
import withExchangeRatesActions from 'containers/ExchangeRates/withExchangeRatesActions';
import withExchangeRates from 'containers/ExchangeRates/withExchangeRates';
import { compose } from 'utils';
import { FormattedMessage as T, useIntl } from 'react-intl';
function ExchangeRateTable({
// #withExchangeRates
exchangeRatesList,
exchangeRatesLoading,
// #withDialog.
openDialog,
// own properties
loading,
onFetchData,
onDeleteExchangeRate,
onEditExchangeRate,
onSelectedRowsChange,
}) {
const [initialMount, setInitialMount] = useState(false);
const { formatMessage } = useIntl();
const handelEditExchangeRate = (exchange_rate) => () => {
openDialog('exchangeRate-form', { action: 'edit', id: exchange_rate.id });
onEditExchangeRate(exchange_rate.id);
};
const handleDeleteExchangeRate = (exchange_rate) => () => {
onDeleteExchangeRate(exchange_rate);
};
const actionMenuList = useCallback(
(ExchangeRate) => (
<Menu>
<MenuItem
text={<T id={'edit_exchange_rate'} />}
onClick={handelEditExchangeRate(ExchangeRate)}
/>
<MenuItem
text={<T id={'delete_exchange_rate'} />}
onClick={handleDeleteExchangeRate(ExchangeRate)}
/>
</Menu>
),
[handelEditExchangeRate, handleDeleteExchangeRate]
);
const columns = useMemo(() => [
{
id: 'date',
Header: formatMessage({ id: 'date' }),
// accessor: 'date',
width: 150,
},
{
id: 'currency_code',
Header: formatMessage({ id: 'currency_code' }),
accessor: 'currency_code',
className: 'currency_code',
width: 150,
},
{
id: 'exchange_rate',
Header: formatMessage({ id: 'exchange_rate' }),
accessor: 'exchange_rate',
className: 'exchange_rate',
width: 150,
},
{
id: 'actions',
Header: '',
Cell: ({ cell }) => (
<Popover
content={actionMenuList(cell.row.original)}
position={Position.RIGHT_BOTTOM}
>
<Button icon={<Icon icon='ellipsis-h' />} />
</Popover>
),
className: 'actions',
width: 50,
disableResizing: false,
},
], [actionMenuList]);
const selectionColumn = useMemo(() => ({
minWidth: 42,
width: 42,
maxWidth: 42,
}), []);
const handelFetchData = useCallback(
(...params) => {
onFetchData && onFetchData(...params);
},
[onFetchData]
);
const handelSelectedRowsChange = useCallback((selectRows) => {
onSelectedRowsChange && onSelectedRowsChange(selectRows.map((c) => c.original));
}, [onSelectedRowsChange]);
return (
<DataTable
columns={columns}
data={exchangeRatesList}
onFetchData={handelFetchData}
loading={exchangeRatesLoading && !initialMount}
manualSortBy={true}
selectionColumn={selectionColumn}
expandable={true}
treeGraph={true}
onSelectedRowsChange={handelSelectedRowsChange}
spinnerProps={{ size: 30 }}
/>
);
}
export default compose(
DialogConnect,
withExchangeRatesActions,
withExchangeRates(({ exchangeRatesList ,exchangeRatesLoading }) => ({
exchangeRatesList,
exchangeRatesLoading
}))
)(ExchangeRateTable);

View File

@@ -0,0 +1,14 @@
import { connect } from 'react-redux';
import { getResourceViews } from 'store/customViews/customViews.selectors';
export default (mapState) => {
const mapStateToProps = (state, props) => {
const mapped = {
exchangeRatesList: Object.values(state.exchangeRates.exchangeRates),
exchangeRatesLoading: state.exchangeRates.loading,
};
return mapState ? mapState(mapped, state, props) : mapped;
};
return connect(mapStateToProps);
};

View File

@@ -0,0 +1,21 @@
import { connect } from 'react-redux';
import {
submitExchangeRate,
fetchExchangeRates,
deleteExchangeRate,
editExchangeRate,
} from 'store/ExchangeRate/exchange.actions';
const mapActionsToProps = (dispatch) => ({
requestSubmitExchangeRate: (form) => dispatch(submitExchangeRate({ form })),
requestFetchExchangeRates: () => dispatch(fetchExchangeRates()),
requestDeleteExchangeRate: (id) => dispatch(deleteExchangeRate(id)),
requestEditExchangeRate: (id, form) => dispatch(editExchangeRate(id, form)),
addExchangeRatesTableQueries: (queries) =>
dispatch({
type: 'ExchangeRates_TABLE_QUERIES_ADD',
queries,
}),
});
export default connect(null, mapActionsToProps);

View File

@@ -4,6 +4,7 @@ import {useParams} from 'react-router-dom';
import Connector from 'connectors/ExpenseForm.connector';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import ExpenseForm from 'components/Expenses/ExpenseForm';
import { FormattedMessage as T, useIntl } from 'react-intl';
function ExpenseFormContainer({
fetchAccounts,
@@ -15,12 +16,12 @@ function ExpenseFormContainer({
currencies,
}) {
const { id } = useParams();
const { formatMessage } = useIntl();
useEffect(() => {
if (id) {
changePageTitle('Edit Expense Details');
changePageTitle(formatMessage({id:'edit_expense_details'}));
} else {
changePageTitle('New Expense');
changePageTitle(formatMessage({id:'new_expense'}));
}
}, []);

View File

@@ -8,6 +8,7 @@ import ExpensesViewsTabs from 'components/Expenses/ExpensesViewsTabs';
import ExpensesTable from 'components/Expenses/ExpensesTable';
import connector from 'connectors/ExpensesList.connector';
import AppToaster from 'components/AppToaster';
import { FormattedMessage as T, useIntl } from 'react-intl';
function ExpensesList({
fetchExpenses,
@@ -17,8 +18,9 @@ function ExpensesList({
getResourceViews,
changePageTitle
}) {
const {formatMessage} =useIntl()
useEffect(() => {
changePageTitle('Expenses List');
changePageTitle(formatMessage({id:'expenses_list'}));
}, []);
const [deleteExpenseState, setDeleteExpense] = useState();
@@ -59,8 +61,8 @@ function ExpensesList({
</DashboardPageContent>
<Alert
cancelButtonText='Cancel'
confirmButtonText='Move to Trash'
cancelButtonText={<T id={'cancel'}/>}
confirmButtonText={<T id={'move_to_trash'}/>}
icon='trash'
intent={Intent.DANGER}
isOpen={deleteExpenseState}

View File

@@ -9,6 +9,7 @@ import ItemsCategoryActionsBar from 'containers/Items/ItemsCategoryActionsBar';
import withDashboardActions from 'containers/Dashboard/withDashboard';
import withItemCategoriesActions from 'containers/Items/withItemCategoriesActions';
import { compose } from 'utils';
import { FormattedMessage as T, useIntl } from 'react-intl';
const ItemCategoryList = ({
@@ -20,11 +21,11 @@ const ItemCategoryList = ({
}) => {
const { id } = useParams();
const [selectedRows, setSelectedRows] = useState([]);
const {formatMessage} =useIntl()
useEffect(() => {
id
? changePageTitle('Edit Category Details')
: changePageTitle('Category List');
? changePageTitle(formatMessage({id:'edit_category_details'}))
: changePageTitle(formatMessage({id:'category_list'}));
}, []);
const fetchCategories = useQuery('items-categories-table',

View File

@@ -6,6 +6,8 @@ import {
MenuItem,
Position,
} from '@blueprintjs/core';
import { FormattedMessage as T, useIntl } from 'react-intl';
import Icon from 'components/Icon';
import LoadingIndicator from 'components/LoadingIndicator';
import { compose } from 'utils';
@@ -19,13 +21,15 @@ const ItemsCategoryList = ({
// #withItemCategories
categoriesList,
// #ownProps
onFetchData,
onDeleteCategory,
onEditCategory,
openDialog,
count,
onSelectedRowsChange,
}) => {
const {formatMessage} = useIntl();
const handelEditCategory = (category) => () => {
openDialog('item-form', { action: 'edit', id: category.id });
onEditCategory(category.id);
@@ -37,9 +41,9 @@ const ItemsCategoryList = ({
const actionMenuList = (category) => (
<Menu>
<MenuItem text='Edit Category' onClick={handelEditCategory(category)} />
<MenuItem text={<T id={'edit_category'} />} onClick={handelEditCategory(category)} />
<MenuItem
text='Delete Category'
text={<T id={'delete_category'}/>}
onClick={handleDeleteCategory(category)}
/>
</Menu>
@@ -48,20 +52,20 @@ const ItemsCategoryList = ({
const columns = useMemo(() => [
{
id: 'name',
Header: 'Category Name',
Header: formatMessage({ id:'category_name' }),
accessor: 'name',
width: 150,
},
{
id: 'description',
Header: 'Description',
Header: formatMessage({ id:'description' }),
accessor: 'description',
className: 'description',
width: 150,
},
{
id: 'count',
Header: 'Count',
Header: formatMessage({ id:'count' }),
accessor: (r) => r.count || '',
className: 'count',
width: 50,

View File

@@ -12,18 +12,19 @@ import {
Checkbox,
} from '@blueprintjs/core';
import { Row, Col } from 'react-grid-system';
import { useIntl } from 'react-intl';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { Select } from '@blueprintjs/select';
import AppToaster from 'components/AppToaster';
import AccountsConnect from 'connectors/Accounts.connector';
import ItemsConnect from 'connectors/Items.connect';
import {compose} from 'utils';
import { compose } from 'utils';
import ErrorMessage from 'components/ErrorMessage';
import classNames from 'classnames';
import Icon from 'components/Icon';
import ItemCategoryConnect from 'connectors/ItemsCategory.connect';
import MoneyInputGroup from 'components/MoneyInputGroup';
import {useHistory} from 'react-router-dom';
import { useHistory } from 'react-router-dom';
import Dragzone from 'components/Dragzone';
import MediaConnect from 'connectors/Media.connect';
import useMedia from 'hooks/useMedia';
@@ -31,7 +32,7 @@ import useMedia from 'hooks/useMedia';
const ItemForm = ({
requestSubmitItem,
accounts,
categories,
@@ -54,12 +55,15 @@ const ItemForm = ({
deleteCallback: requestDeleteMedia,
});
const ItemTypeDisplay = useMemo(() => ([
{ value: null, label: 'Select Item Type' },
{ value: 'service', label: 'Service' },
{ value: 'inventory', label: 'Inventory' },
{ value: 'non-inventory', label: 'Non-Inventory' }
]), []);
const ItemTypeDisplay = useMemo(
() => [
{ value: null, label: 'Select Item Type' },
{ value: 'service', label: 'Service' },
{ value: 'inventory', label: 'Inventory' },
{ value: 'non-inventory', label: 'Non-Inventory' },
],
[]
);
const validationSchema = Yup.object().shape({
active: Yup.boolean(),
@@ -76,22 +80,25 @@ const ItemForm = ({
otherwise: Yup.number().nullable(),
}),
category_id: Yup.number().nullable(),
stock: Yup.string() || Yup.boolean()
stock: Yup.string() || Yup.boolean(),
});
const initialValues = useMemo(() => ({
active: true,
name: '',
type: '',
sku: '',
cost_price: 0,
sell_price: 0,
cost_account_id: null,
sell_account_id: null,
inventory_account_id: null,
category_id: null,
note: '',
}), []);
const initialValues = useMemo(
() => ({
active: true,
name: '',
type: '',
sku: '',
cost_price: 0,
sell_price: 0,
cost_account_id: null,
sell_account_id: null,
inventory_account_id: null,
category_id: null,
note: '',
}),
[]
);
const {
getFieldProps,
@@ -121,27 +128,29 @@ const ItemForm = ({
}),
intent: Intent.SUCCESS,
});
setSubmitting(false);
history.push('/dashboard/items');
})
.catch((error) => {
setSubmitting(false);
});
};
Promise.all([
saveMedia(),
deleteMedia(),
]).then(([savedMediaResponses]) => {
const mediaIds = savedMediaResponses.map(res => res.data.media.id);
return saveItem(mediaIds);
});
}
Promise.all([saveMedia(), deleteMedia()]).then(
([savedMediaResponses]) => {
const mediaIds = savedMediaResponses.map((res) => res.data.media.id);
return saveItem(mediaIds);
}
);
},
});
const accountItem = useCallback((item, { handleClick }) => (
<MenuItem key={item.id} text={item.name} label={item.code} onClick={handleClick} />
), []);
const accountItem = useCallback(
(item, { handleClick }) => (
<MenuItem
key={item.id}
text={item.name}
label={item.code}
onClick={handleClick}
/>
),
[]
);
// Filter Account Items
const filterAccounts = (query, account, _index, exactMatch) => {
@@ -154,27 +163,37 @@ const ItemForm = ({
}
};
const onItemAccountSelect = useCallback((filedName) => {
return (account) => {
setSelectedAccounts({
...selectedAccounts,
[filedName]: account
});
setFieldValue(filedName, account.id);
};
}, [setFieldValue, selectedAccounts]);
const onItemAccountSelect = useCallback(
(filedName) => {
return (account) => {
setSelectedAccounts({
...selectedAccounts,
[filedName]: account,
});
setFieldValue(filedName, account.id);
};
},
[setFieldValue, selectedAccounts]
);
const categoryItem = useCallback((item, { handleClick }) => (
<MenuItem text={item.name} onClick={handleClick} />
), []);
const categoryItem = useCallback(
(item, { handleClick }) => (
<MenuItem text={item.name} onClick={handleClick} />
),
[]
);
const getSelectedAccountLabel = useCallback((fieldName, defaultLabel) => {
return typeof selectedAccounts[fieldName] !== 'undefined'
? selectedAccounts[fieldName].name : defaultLabel;
}, [selectedAccounts]);
const getSelectedAccountLabel = useCallback(
(fieldName, defaultLabel) => {
return typeof selectedAccounts[fieldName] !== 'undefined'
? selectedAccounts[fieldName].name
: defaultLabel;
},
[selectedAccounts]
);
const requiredSpan = useMemo(() => (<span class="required">*</span>), []);
const infoIcon = useMemo(() => (<Icon icon="info-circle" iconSize={12} />), []);
const requiredSpan = useMemo(() => <span class='required'>*</span>, []);
const infoIcon = useMemo(() => <Icon icon='info-circle' iconSize={12} />, []);
const handleMoneyInputChange = (fieldKey) => (e, value) => {
setFieldValue(fieldKey, value);
@@ -188,31 +207,36 @@ const ItemForm = ({
setFiles(_files.filter((file) => file.uploaded === false));
}, []);
const handleDeleteFile = useCallback((_deletedFiles) => {
_deletedFiles.forEach((deletedFile) => {
if (deletedFile.uploaded && deletedFile.metadata.id) {
setDeletedFiles([
...deletedFiles, deletedFile.metadata.id,
]);
}
});
}, [setDeletedFiles, deletedFiles]);
const handleDeleteFile = useCallback(
(_deletedFiles) => {
_deletedFiles.forEach((deletedFile) => {
if (deletedFile.uploaded && deletedFile.metadata.id) {
setDeletedFiles([...deletedFiles, deletedFile.metadata.id]);
}
});
},
[setDeletedFiles, deletedFiles]
);
const handleCancelClickBtn = () => { history.goBack(); };
const handleCancelClickBtn = () => {
history.goBack();
};
return (
<div class='item-form'>
<form onSubmit={handleSubmit}>
<div class="item-form__primary-section">
<div class='item-form__primary-section'>
<Row>
<Col xs={7}>
<FormGroup
medium={true}
label={'Item Type'}
label={<T id={'item_type'} />}
labelInfo={requiredSpan}
className={'form-group--item-type'}
intent={(errors.type && touched.type) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name="type" />}
intent={errors.type && touched.type && Intent.DANGER}
helperText={
<ErrorMessage {...{ errors, touched }} name='type' />
}
inline={true}
>
<HTMLSelect
@@ -223,45 +247,53 @@ const ItemForm = ({
</FormGroup>
<FormGroup
label={'Item Name'}
label={<T id={'item_name'} />}
labelInfo={requiredSpan}
className={'form-group--item-name'}
intent={(errors.name && touched.name) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name="name" />}
intent={errors.name && touched.name && Intent.DANGER}
helperText={
<ErrorMessage {...{ errors, touched }} name='name' />
}
inline={true}
>
<InputGroup
medium={true}
intent={(errors.name && touched.name) && Intent.DANGER}
intent={errors.name && touched.name && Intent.DANGER}
{...getFieldProps('name')}
/>
</FormGroup>
<FormGroup
label={'SKU'}
label={<T id={'sku'} />}
labelInfo={infoIcon}
className={'form-group--item-sku'}
intent={(errors.sku && touched.sku) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name="sku" />}
intent={errors.sku && touched.sku && Intent.DANGER}
helperText={
<ErrorMessage {...{ errors, touched }} name='sku' />
}
inline={true}
>
<InputGroup
medium={true}
intent={(errors.sku && touched.sku) && Intent.DANGER}
intent={errors.sku && touched.sku && Intent.DANGER}
{...getFieldProps('sku')}
/>
</FormGroup>
<FormGroup
label={'Category'}
label={<T id={'category'} />}
labelInfo={infoIcon}
inline={true}
intent={(errors.category_id && touched.category_id) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name="category" />}
intent={
errors.category_id && touched.category_id && Intent.DANGER
}
helperText={
<ErrorMessage {...{ errors, touched }} name='category' />
}
className={classNames(
'form-group--select-list',
'form-group--category',
Classes.FILL,
Classes.FILL
)}
>
<Select
@@ -274,7 +306,10 @@ const ItemForm = ({
<Button
fill={true}
rightIcon='caret-down'
text={getSelectedAccountLabel('category_id', 'Select category')}
text={getSelectedAccountLabel(
'category_id',
'Select category'
)}
/>
</Select>
</FormGroup>
@@ -286,7 +321,7 @@ const ItemForm = ({
>
<Checkbox
inline={true}
label={'Active'}
label={<T id={'active'}/>}
defaultChecked={values.active}
{...getFieldProps('active')}
/>
@@ -299,20 +334,25 @@ const ItemForm = ({
onDrop={handleDropFiles}
onDeleteFile={handleDeleteFile}
hint={'Attachments: Maxiumum size: 20MB'}
className={'mt2'} />
className={'mt2'}
/>
</Col>
</Row>
</div>
<Row gutterWidth={16} className={'item-form__accounts-section'}>
<Col width={404}>
<h4>Purchase Information</h4>
<h4><T id={'purchase_information'}/></h4>
<FormGroup
label={'Selling Price'}
label={<T id={'selling_price'}/>}
className={'form-group--item-selling-price'}
intent={(errors.selling_price && touched.selling_price) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name="selling_price" />}
intent={
errors.selling_price && touched.selling_price && Intent.DANGER
}
helperText={
<ErrorMessage {...{ errors, touched }} name='selling_price' />
}
inline={true}
>
<MoneyInputGroup
@@ -321,19 +361,31 @@ const ItemForm = ({
onChange={handleMoneyInputChange('selling_price')}
inputGroupProps={{
medium: true,
intent: (errors.selling_price && touched.selling_price) && Intent.DANGER,
}} />
intent:
errors.selling_price &&
touched.selling_price &&
Intent.DANGER,
}}
/>
</FormGroup>
<FormGroup
label={'Account'}
label={<T id={'account'} />}
labelInfo={infoIcon}
inline={true}
intent={(errors.sell_account_id && touched.sell_account_id) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name="sell_account_id" />}
intent={
errors.sell_account_id &&
touched.sell_account_id &&
Intent.DANGER
}
helperText={
<ErrorMessage {...{ errors, touched }} name='sell_account_id' />
}
className={classNames(
'form-group--sell-account', 'form-group--select-list',
Classes.FILL)}
'form-group--sell-account',
'form-group--select-list',
Classes.FILL
)}
>
<Select
items={accounts}
@@ -345,7 +397,10 @@ const ItemForm = ({
<Button
fill={true}
rightIcon='caret-down'
text={getSelectedAccountLabel('sell_account_id', 'Select account')}
text={getSelectedAccountLabel(
'sell_account_id',
'Select account'
)}
/>
</Select>
</FormGroup>
@@ -353,14 +408,16 @@ const ItemForm = ({
<Col width={404}>
<h4>
Sales Information
<T id={'sales_information'} />
</h4>
<FormGroup
label={'Cost Price'}
label={<T id={'cost_price'} />}
className={'form-group--item-cost-price'}
intent={(errors.cost_price && touched.cost_price) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name="cost_price" />}
intent={errors.cost_price && touched.cost_price && Intent.DANGER}
helperText={
<ErrorMessage {...{ errors, touched }} name='cost_price' />
}
inline={true}
>
<MoneyInputGroup
@@ -369,21 +426,30 @@ const ItemForm = ({
onChange={handleMoneyInputChange('cost_price')}
inputGroupProps={{
medium: true,
intent: (errors.cost_price && touched.cost_price) && Intent.DANGER,
}} />
intent:
errors.cost_price && touched.cost_price && Intent.DANGER,
}}
/>
</FormGroup>
<FormGroup
label={'Account'}
label={<T id={'account'} />}
labelInfo={infoIcon}
inline={true}
intent={(errors.cost_account_id && touched.cost_account_id) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name="cost_account_id" />}
intent={
errors.cost_account_id &&
touched.cost_account_id &&
Intent.DANGER
}
helperText={
<ErrorMessage {...{ errors, touched }} name='cost_account_id' />
}
className={classNames(
'form-group--cost-account',
'form-group--select-list',
Classes.FILL)}
>
Classes.FILL
)}
>
<Select
items={accounts}
itemRenderer={accountItem}
@@ -394,7 +460,10 @@ const ItemForm = ({
<Button
fill={true}
rightIcon='caret-down'
text={getSelectedAccountLabel('cost_account_id', 'Select account')}
text={getSelectedAccountLabel(
'cost_account_id',
'Select account'
)}
/>
</Select>
</FormGroup>
@@ -404,19 +473,29 @@ const ItemForm = ({
<Row className={'item-form__accounts-section mt2'}>
<Col width={404}>
<h4>
Inventory Information
<T id={'inventory_information'} />
</h4>
<FormGroup
label={'Inventory Account'}
label={<T id={'inventory_account'}/>}
inline={true}
intent={(errors.inventory_account_id && touched.inventory_account_id) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name="inventory_account_id" />}
intent={
errors.inventory_account_id &&
touched.inventory_account_id &&
Intent.DANGER
}
helperText={
<ErrorMessage
{...{ errors, touched }}
name='inventory_account_id'
/>
}
className={classNames(
'form-group--item-inventory_account',
'form-group--select-list',
Classes.FILL)}
>
Classes.FILL
)}
>
<Select
items={accounts}
itemRenderer={accountItem}
@@ -427,16 +506,17 @@ const ItemForm = ({
<Button
fill={true}
rightIcon='caret-down'
text={getSelectedAccountLabel('inventory_account_id','Select account')}
text={getSelectedAccountLabel(
'inventory_account_id',
'Select account'
)}
/>
</Select>
</FormGroup>
<FormGroup
label={'Opening Stock'}
label={<T id={'opening_stock'}/>}
className={'form-group--item-stock'}
// intent={errors.cost_price && Intent.DANGER}
// helperText={formik.errors.stock && formik.errors.stock}
inline={true}
>
<InputGroup
@@ -450,11 +530,16 @@ const ItemForm = ({
<div class='form__floating-footer'>
<Button intent={Intent.PRIMARY} disabled={isSubmitting} type='submit'>
Save
<T id={'save'}/>
</Button>
<Button className={'ml1'} disabled={isSubmitting}>Save as Draft</Button>
<Button className={'ml1'} onClick={handleCancelClickBtn}>Close</Button>
<Button className={'ml1'} disabled={isSubmitting}>
<T id={'save_as_draft'}/>
</Button>
<Button className={'ml1'} onClick={handleCancelClickBtn}>
<T id={'close'} />
</Button>
</div>
</form>
</div>
@@ -465,5 +550,5 @@ export default compose(
AccountsConnect,
ItemsConnect,
ItemCategoryConnect,
MediaConnect,
)(ItemForm);
MediaConnect
)(ItemForm);

View File

@@ -10,6 +10,7 @@ import withAccountsActions from 'containers/Accounts/withAccountsActions';
import withItemCategoriesActions from 'containers/Items/withItemCategoriesActions';
import { compose } from 'utils';
import { FormattedMessage as T, useIntl } from 'react-intl';
const ItemFormContainer = ({
@@ -23,11 +24,11 @@ const ItemFormContainer = ({
requestFetchItemCategories,
}) => {
const { id } = useParams();
const {formatMessage} =useIntl()
useEffect(() => {
id ?
changePageTitle('Edit Item Details') :
changePageTitle('New Item');
changePageTitle(formatMessage({id:'edit_item_details'})) :
changePageTitle(formatMessage({id:'new_item'}));
}, [id, changePageTitle]);
const fetchAccounts = useQuery('accounts-list',

View File

@@ -21,6 +21,7 @@ import DialogConnect from 'connectors/Dialog.connector';
import withResourceDetail from 'containers/Resources/withResourceDetails';
import withItems from 'containers/Items/withItems';
import { If } from 'components';
import { FormattedMessage as T, useIntl } from 'react-intl';
const ItemsActionsBar = ({
openDialog,
@@ -70,7 +71,7 @@ const ItemsActionsBar = ({
<Button
className={classNames(Classes.MINIMAL, 'button--table-views')}
icon={<Icon icon='table' />}
text='Table Views'
text={<T id={'table_views'}/>}
rightIcon={'caret-down'}
/>
</Popover>
@@ -80,14 +81,14 @@ const ItemsActionsBar = ({
<Button
className={Classes.MINIMAL}
icon={<Icon icon='plus' />}
text='New Item'
text={<T id={'new_item'}/>}
onClick={onClickNewItem}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='plus' />}
text='New Category'
text={<T id={'new_category'}/>}
onClick={onClickNewCategory}
/>
@@ -98,7 +99,7 @@ const ItemsActionsBar = ({
>
<Button
className={classNames(Classes.MINIMAL, 'button--filter')}
text={filterCount <= 0 ? 'Filter' : `${filterCount} filters applied`}
text={filterCount <= 0 ? <T id={'filter'}/> : `${filterCount} filters applied`}
icon={<Icon icon='filter' />}
/>
</Popover>
@@ -108,19 +109,19 @@ const ItemsActionsBar = ({
className={Classes.MINIMAL}
intent={Intent.DANGER}
icon={<Icon icon='trash' />}
text='Delete'
text={<T id={'delete'}/>}
/>
</If>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-import' />}
text='Import'
text={<T id={'import'}/>}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-export' />}
text='Export'
text={<T id={'export'}/>}
/>
</NavbarGroup>
</DashboardActionsBar>

View File

@@ -21,6 +21,7 @@ import FilterDropdown from 'components/FilterDropdown';
import withResourceDetail from 'containers/Resources/withResourceDetails';
import withDashboard from 'containers/Dashboard/withDashboard';
import { FormattedMessage as T, useIntl } from 'react-intl';
const ItemsCategoryActionsBar = ({
// #withResourceDetail
@@ -57,7 +58,7 @@ const ItemsCategoryActionsBar = ({
<Button
className={Classes.MINIMAL}
icon={<Icon icon='plus' />}
text='New Category'
text={<T id={'new_category'}/>}
onClick={onClickNewCategory}
/>
<Popover
@@ -68,7 +69,7 @@ const ItemsCategoryActionsBar = ({
>
<Button
className={classNames(Classes.MINIMAL, 'button--filter')}
text='Filter'
text={<T id={'filter'}/>}
icon={<Icon icon='filter' />}
/>
</Popover>
@@ -77,7 +78,7 @@ const ItemsCategoryActionsBar = ({
<Button
className={Classes.MINIMAL}
icon={<Icon icon='trash' iconSize={15} />}
text='Delete'
text={<T id={'delete'}/>}
intent={Intent.DANGER}
onClick={handleDeleteCategory}
/>
@@ -86,12 +87,12 @@ const ItemsCategoryActionsBar = ({
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-import' />}
text='Import'
text={<T id={'import'}/>}
/>
<Button
className={Classes.MINIMAL}
icon={<Icon icon='file-export' />}
text='Export'
text={<T id={'export'}/>}
/>
</NavbarGroup>
</DashboardActionsBar>

View File

@@ -7,6 +7,8 @@ import {
MenuDivider,
Position,
} from '@blueprintjs/core'
import { FormattedMessage as T, useIntl } from 'react-intl';
import {compose} from 'utils';
import DataTable from 'components/DataTable';
import Icon from 'components/Icon';
@@ -29,6 +31,8 @@ const ItemsDataTable = ({
onFetchData,
onSelectedRowsChange,
}) => {
const {formatMessage} = useIntl();
const [initialMount, setInitialMount] = useState(false);
useEffect(() => {
@@ -42,35 +46,35 @@ const ItemsDataTable = ({
const actionMenuList = useCallback((item) =>
(<Menu>
<MenuItem text="View Details" />
<MenuItem text={<T id={'view_details'}/>} />
<MenuDivider />
<MenuItem text="Edit Item" onClick={handleEditItem(item)} />
<MenuItem text="Delete Item" onClick={handleDeleteItem(item)} />
<MenuItem text={<T id={'edit_item'}/>} onClick={handleEditItem(item)} />
<MenuItem text={<T id={'delete_item'}/>} onClick={handleDeleteItem(item)} />
</Menu>), [handleEditItem, handleDeleteItem]);
const columns = useMemo(() => [
{
Header: 'Item Name',
Header: formatMessage({ id:'item_name' }),
accessor: 'name',
className: "actions",
},
{
Header: 'SKU',
Header: formatMessage({ id:'sku' }),
accessor: 'sku',
className: "sku",
},
{
Header: 'Category',
Header: formatMessage({ id:'category' }),
accessor: 'category.name',
className: 'category',
},
{
Header: 'Sell Price',
Header: formatMessage({ id: 'sell_price' }),
accessor: row => (<Money amount={row.sell_price} currency={'USD'} />),
className: 'sell-price',
},
{
Header: 'Cost Price',
Header: formatMessage({ id: 'cost_price' }),
accessor: row => (<Money amount={row.cost_price} currency={'USD'} />),
className: 'cost-price',
},

View File

@@ -8,7 +8,7 @@ import {
Alert,
} from '@blueprintjs/core';
import { useQuery } from 'react-query';
import { FormattedHTMLMessage, useIntl } from 'react-intl';
import { FormattedMessage as T, FormattedHTMLMessage, useIntl } from 'react-intl';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import ItemsActionsBar from 'containers/Items/ItemsActionsBar';
@@ -27,7 +27,6 @@ import withItemsActions from 'containers/Items/withItemsActions';
import withViewsActions from 'containers/Views/withViewsActions';
function ItemsList({
// #withDashboard
changePageTitle,
@@ -150,8 +149,8 @@ function ItemsList({
onSelectedRowsChange={handleSelectedRowsChange} />
<Alert
cancelButtonText="Cancel"
confirmButtonText="Delete"
cancelButtonText={<T id={'cancel'}/>}
confirmButtonText={<T id={'delete'}/>}
icon="trash"
intent={Intent.DANGER}
isOpen={deleteItem}

View File

@@ -1,6 +1,7 @@
import React, {useState, useEffect, useCallback, useMemo} from 'react';
import { useFormik } from "formik";
import {useIntl} from 'react-intl';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useFormik } from 'formik';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { useParams, useHistory } from 'react-router-dom';
import {
InputGroup,
@@ -13,19 +14,18 @@ import {
Menu,
H5,
H6,
} from "@blueprintjs/core";
import {Row, Col} from 'react-grid-system';
} from '@blueprintjs/core';
import { Row, Col } from 'react-grid-system';
import { ReactSortable } from 'react-sortablejs';
import * as Yup from 'yup';
import {pick, get} from 'lodash';
import { pick, get } from 'lodash';
import Icon from 'components/Icon';
import ErrorMessage from 'components/ErrorMessage';
import AppToaster from 'components/AppToaster';
import { If } from 'components';
import ViewFormContainer from 'containers/Views/ViewForm.container.js';
function ViewForm({
function ViewForm({
requestSubmitView,
requestEditView,
onDelete,
@@ -51,20 +51,30 @@ function ViewForm({
}, []);
const [draggedColumns, setDraggedColumn] = useState([
...(viewMeta && viewMeta.columns) ? viewMeta.columns : []
...(viewMeta && viewMeta.columns ? viewMeta.columns : []),
]);
const draggedColumnsIds = useMemo(() => draggedColumns.map((c) => c.id), [
draggedColumns,
]);
const draggedColumnsIds = useMemo(() => draggedColumns.map(c => c.id), [draggedColumns]);
const [availableColumns, setAvailableColumns] = useState([
...(viewMeta && viewMeta.columns) ? resourceColumns.filter((column) =>
draggedColumnsIds.indexOf(column.id) === -1
) : resourceColumns,
...(viewMeta && viewMeta.columns
? resourceColumns.filter(
(column) => draggedColumnsIds.indexOf(column.id) === -1
)
: resourceColumns),
]);
const defaultViewRole = useMemo(() => ({
field_key: '', comparator: '', value: '', index: 1,
}), []);
const defaultViewRole = useMemo(
() => ({
field_key: '',
comparator: '',
value: '',
index: 1,
}),
[]
);
const validationSchema = Yup.object().shape({
resource_name: Yup.string().required(),
@@ -82,27 +92,33 @@ function ViewForm({
Yup.object().shape({
key: Yup.string().required(),
index: Yup.string().required(),
}),
})
),
});
const initialEmptyForm = useMemo(() => ({
resource_name: resourceName || '',
name: '',
logic_expression: '',
roles: [
defaultViewRole,
],
columns: [],
}), [defaultViewRole, resourceName]);
const initialEmptyForm = useMemo(
() => ({
resource_name: resourceName || '',
name: '',
logic_expression: '',
roles: [defaultViewRole],
columns: [],
}),
[defaultViewRole, resourceName]
);
const initialForm = useMemo(() => ({
...initialEmptyForm,
...viewMeta ? {
...viewMeta,
resource_name: viewMeta.resource?.name || resourceName,
} : {},
}), [initialEmptyForm, viewMeta, resourceName]);
const initialForm = useMemo(
() => ({
...initialEmptyForm,
...(viewMeta
? {
...viewMeta,
resource_name: viewMeta.resource?.name || resourceName,
}
: {}),
}),
[initialEmptyForm, viewMeta, resourceName]
);
const {
values,
@@ -135,7 +151,9 @@ function ViewForm({
message: 'the_view_has_been_edited',
intent: Intent.SUCCESS,
});
history.push(`${resourceMetadata.baseRoute}/${viewMeta.id}/custom_view`);
history.push(
`${resourceMetadata.baseRoute}/${viewMeta.id}/custom_view`
);
setSubmitting(false);
});
} else {
@@ -144,7 +162,9 @@ function ViewForm({
message: 'the_view_has_been_submit',
intent: Intent.SUCCESS,
});
history.push(`${resourceMetadata.baseRoute}/${viewMeta.id}/custom_view`);
history.push(
`${resourceMetadata.baseRoute}/${viewMeta.id}/custom_view`
);
setSubmitting(false);
});
}
@@ -152,39 +172,55 @@ function ViewForm({
});
useEffect(() => {
setFieldValue('columns',
setFieldValue(
'columns',
draggedColumns.map((column, index) => ({
index, key: column.key,
})));
index,
key: column.key,
}))
);
}, [setFieldValue, draggedColumns]);
const conditionalsItems = useMemo(() => ([
{ value: 'and', label: 'AND' },
{ value: 'or', label: 'OR' },
]), []);
const conditionalsItems = useMemo(
() => [
{ value: 'and', label: 'AND' },
{ value: 'or', label: 'OR' },
],
[]
);
const whenConditionalsItems = useMemo(() => ([
{ value: '', label: 'When' },
]), []);
const whenConditionalsItems = useMemo(
() => [{ value: '', label: 'When' }],
[]
);
// Compatotors items.
const compatatorsItems = useMemo(() => ([
{value: '', label: 'Compatator'},
{value: 'equals', label: 'Equals'},
{value: 'not_equal', label: 'Not Equal'},
{value: 'contain', label: 'Contain'},
{value: 'not_contain', label: 'Not Contain'},
]), []);
const compatatorsItems = useMemo(
() => [
{ value: '', label: 'Compatator' },
{ value: 'equals', label: 'Equals' },
{ value: 'not_equal', label: 'Not Equal' },
{ value: 'contain', label: 'Contain' },
{ value: 'not_contain', label: 'Not Contain' },
],
[]
);
// Resource fields.
const resourceFieldsOptions = useMemo(() => ([
{value: '', label: 'Select a field'},
...resourceFields.map((field) => ({ value: field.key, label: field.label_name, })),
]), [resourceFields]);
const resourceFieldsOptions = useMemo(
() => [
{ value: '', label: 'Select a field' },
...resourceFields.map((field) => ({
value: field.key,
label: field.label_name,
})),
],
[resourceFields]
);
// Account item of select accounts field.
const selectItem = (item, { handleClick, modifiers, query }) => {
return (<MenuItem text={item.label} key={item.key} onClick={handleClick} />)
return <MenuItem text={item.label} key={item.key} onClick={handleClick} />;
};
// Handle click new condition button.
const onClickNewRole = useCallback(() => {
@@ -193,219 +229,273 @@ function ViewForm({
{
...defaultViewRole,
index: values.roles.length + 1,
}
},
]);
}, [defaultViewRole, setFieldValue, values]);
// Handle click remove view role button.
const onClickRemoveRole = useCallback((viewRole, index) => {
let viewRoles = [...values.roles];
const onClickRemoveRole = useCallback(
(viewRole, index) => {
let viewRoles = [...values.roles];
// Can't continue if view roles equals or less than 1.
if (viewRoles.length > 1) {
viewRoles.splice(index, 1);
// Can't continue if view roles equals or less than 1.
if (viewRoles.length > 1) {
viewRoles.splice(index, 1);
setFieldValue(
'roles',
viewRoles.map((role) => {
return role;
})
);
}
},
[values, setFieldValue]
);
setFieldValue('roles', viewRoles.map((role) => {
return role;
}));
}
}, [values, setFieldValue]);
const onClickDeleteView = useCallback(() => {
onDelete && onDelete(viewMeta);
}, [onDelete, viewMeta]);
const hasError = (path) => get(errors, path) && get(touched, path);
const hasError = (path) => get(errors, path) && get(touched, path);
const handleClickCancelBtn = () => {
history.goBack();
};
return (
<div class="view-form">
<div class='view-form'>
<form onSubmit={handleSubmit}>
<div class="view-form--name-section">
<div class='view-form--name-section'>
<Row>
<Col sm={8}>
<FormGroup
label={intl.formatMessage({'id': 'View Name'})}
label={<T id={'view_name'} />}
className={'form-group--name'}
intent={(errors.name && touched.name) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name={'name'} />}
intent={errors.name && touched.name && Intent.DANGER}
helperText={
<ErrorMessage {...{ errors, touched }} name={'name'} />
}
inline={true}
fill={true}>
fill={true}
>
<InputGroup
intent={(errors.name && touched.name) && Intent.DANGER}
intent={errors.name && touched.name && Intent.DANGER}
fill={true}
{...getFieldProps('name')} />
{...getFieldProps('name')}
/>
</FormGroup>
</Col>
</Row>
</div>
<H5 className="mb2">Define the conditionals</H5>
<H5 className='mb2'>Define the conditionals</H5>
{values.roles.map((role, index) => (
<Row class="view-form__role-conditional">
<Col sm={2} class="flex">
<div class="mr2 pt1 condition-number">{ index + 1 }</div>
{(index === 0) ? (
<HTMLSelect options={whenConditionalsItems} className={Classes.FILL} />
<Row class='view-form__role-conditional'>
<Col sm={2} class='flex'>
<div class='mr2 pt1 condition-number'>{index + 1}</div>
{index === 0 ? (
<HTMLSelect
options={whenConditionalsItems}
className={Classes.FILL}
/>
) : (
<HTMLSelect options={conditionalsItems} className={Classes.FILL} />
<HTMLSelect
options={conditionalsItems}
className={Classes.FILL}
/>
)}
</Col>
<Col sm={2}>
<FormGroup
intent={hasError(`roles[${index}].field_key`) && Intent.DANGER}>
intent={hasError(`roles[${index}].field_key`) && Intent.DANGER}
>
<HTMLSelect
options={resourceFieldsOptions}
value={role.field_key}
className={Classes.FILL}
{...getFieldProps(`roles[${index}].field_key`)} />
{...getFieldProps(`roles[${index}].field_key`)}
/>
</FormGroup>
</Col>
<Col sm={2}>
<FormGroup
intent={hasError(`roles[${index}].comparator`) && Intent.DANGER}>
intent={hasError(`roles[${index}].comparator`) && Intent.DANGER}
>
<HTMLSelect
options={compatatorsItems}
value={role.comparator}
className={Classes.FILL}
{...getFieldProps(`roles[${index}].comparator`)} />
{...getFieldProps(`roles[${index}].comparator`)}
/>
</FormGroup>
</Col>
<Col sm={5} class="flex">
<Col sm={5} class='flex'>
<FormGroup
intent={hasError(`roles[${index}].value`) && Intent.DANGER}>
intent={hasError(`roles[${index}].value`) && Intent.DANGER}
>
<InputGroup
placeholder={intl.formatMessage({'id': 'value'})}
{...getFieldProps(`roles[${index}].value`)} />
placeholder={intl.formatMessage({ id: 'value' })}
{...getFieldProps(`roles[${index}].value`)}
/>
</FormGroup>
<Button
icon={<Icon icon="times-circle" iconSize={14} />}
<Button
icon={<Icon icon='times-circle' iconSize={14} />}
iconSize={14}
className="ml2"
minimal={true}
className='ml2'
minimal={true}
intent={Intent.DANGER}
onClick={() => onClickRemoveRole(role, index)} />
onClick={() => onClickRemoveRole(role, index)}
/>
</Col>
</Row>
))}
<div className={'view-form__role-conditions-actions'}>
<Button
minimal={true}
intent={Intent.PRIMARY}
onClick={onClickNewRole}>
New Conditional
</Button>
</div>
<div className={'view-form__role-conditions-actions'}>
<Button
minimal={true}
intent={Intent.PRIMARY}
onClick={onClickNewRole}
>
<T id={'new_conditional'} />
</Button>
</div>
<div class="view-form--logic-expression-section">
<Row>
<Col sm={8}>
<FormGroup
label={intl.formatMessage({'id': 'Logic Expression'})}
className={'form-group--logic-expression'}
intent={(errors.logic_expression && touched.logic_expression) && Intent.DANGER}
helperText={<ErrorMessage {...{errors, touched}} name='logic_expression' />}
inline={true}
fill={true}>
<div class='view-form--logic-expression-section'>
<Row>
<Col sm={8}>
<FormGroup
label={intl.formatMessage({ id: 'Logic Expression' })}
className={'form-group--logic-expression'}
intent={
errors.logic_expression &&
touched.logic_expression &&
Intent.DANGER
}
helperText={
<ErrorMessage
{...{ errors, touched }}
name='logic_expression'
/>
}
inline={true}
fill={true}
>
<InputGroup
intent={
errors.logic_expression &&
touched.logic_expression &&
Intent.DANGER
}
fill={true}
{...getFieldProps('logic_expression')}
/>
</FormGroup>
</Col>
</Row>
</div>
<H5 className={'mb2'}>Columns Preferences</H5>
<div class='dragable-columns'>
<Row gutterWidth={14}>
<Col sm={4} className='dragable-columns__column'>
<H6 className='dragable-columns__title'>Available Columns</H6>
<InputGroup
intent={(errors.logic_expression && touched.logic_expression) && Intent.DANGER}
fill={true}
{...getFieldProps('logic_expression')} />
</FormGroup>
</Col>
</Row>
</div>
placeholder={intl.formatMessage({ id: 'search' })}
leftIcon='search'
/>
<H5 className={'mb2'}>Columns Preferences</H5>
<div class="dragable-columns">
<Row gutterWidth={14}>
<Col sm={4} className="dragable-columns__column">
<H6 className="dragable-columns__title">Available Columns</H6>
<div class='dragable-columns__items'>
<Menu>
<ReactSortable
list={availableColumns}
setList={setAvailableColumns}
group='shared-group-name'
>
{availableColumns.map((field) => (
<MenuItem key={field.id} text={field.label} />
))}
</ReactSortable>
</Menu>
</div>
</Col>
<InputGroup
placeholder={intl.formatMessage({id: 'search'})}
leftIcon="search" />
<Col sm={1}>
<div class='dragable-columns__arrows'>
<div>
<Icon
icon='arrow-circle-left'
iconSize={30}
color='#cecece'
/>
</div>
<div class='mt2'>
<Icon
icon='arrow-circle-right'
iconSize={30}
color='#cecece'
/>
</div>
</div>
</Col>
<div class="dragable-columns__items">
<Menu>
<ReactSortable
list={availableColumns}
setList={setAvailableColumns}
group="shared-group-name">
{availableColumns.map((field) => (
<MenuItem key={field.id} text={field.label} />
))}
</ReactSortable>
</Menu>
</div>
</Col>
<Col sm={4} className='dragable-columns__column'>
<H6 className='dragable-columns__title'>Selected Columns</H6>
<InputGroup
placeholder={intl.formatMessage({ id: 'search' })}
leftIcon='search'
/>
<Col sm={1}>
<div class="dragable-columns__arrows">
<div><Icon icon="arrow-circle-left" iconSize={30} color="#cecece" /></div>
<div class="mt2"><Icon icon="arrow-circle-right" iconSize={30} color="#cecece" /></div>
</div>
</Col>
<div class='dragable-columns__items'>
<Menu>
<ReactSortable
list={draggedColumns}
setList={setDraggedColumn}
group='shared-group-name'
>
{draggedColumns.map((field) => (
<MenuItem key={field.id} text={field.label} />
))}
</ReactSortable>
</Menu>
</div>
</Col>
</Row>
</div>
<Col sm={4} className="dragable-columns__column">
<H6 className="dragable-columns__title">Selected Columns</H6>
<InputGroup placeholder={intl.formatMessage({id: 'search'})} leftIcon="search" />
<div class="dragable-columns__items">
<Menu>
<ReactSortable
list={draggedColumns}
setList={setDraggedColumn}
group="shared-group-name">
{draggedColumns.map((field) => (
<MenuItem key={field.id} text={field.label} />
))}
</ReactSortable>
</Menu>
</div>
</Col>
</Row>
</div>
<div class="form__floating-footer">
<Button
intent={Intent.PRIMARY}
type="submit"
disabled={isSubmitting}>
Submit
</Button>
<Button
intent={Intent.NONE}
className="ml1"
onClick={handleClickCancelBtn}>
Cancel
</Button>
<If condition={viewMeta && viewMeta.id}>
<Button
intent={Intent.DANGER}
onClick={onClickDeleteView}
className={"right mr2"}>
Delete
<div class='form__floating-footer'>
<Button intent={Intent.PRIMARY} type='submit' disabled={isSubmitting}>
<T id={'submit'} />
</Button>
</If>
</div>
</form>
</div>
<Button
intent={Intent.NONE}
className='ml1'
onClick={handleClickCancelBtn}
>
<T id={'cancel'} />
</Button>
<If condition={viewMeta && viewMeta.id}>
<Button
intent={Intent.DANGER}
onClick={onClickDeleteView}
className={'right mr2'}
>
<T id={'delete'} />
</Button>
</If>
</div>
</form>
</div>
);
}
export default ViewFormContainer(ViewForm);
export default ViewFormContainer(ViewForm);

View File

@@ -2,7 +2,7 @@ import React, {useEffect, useState, useMemo, useCallback} from 'react';
import { useAsync } from 'react-use';
import { useParams } from 'react-router-dom';
import { Intent, Alert } from '@blueprintjs/core';
import { FormattedHTMLMessage, useIntl } from 'react-intl';
import { FormattedMessage as T, FormattedHTMLMessage, useIntl } from 'react-intl';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import DashboardPageContent from 'components/Dashboard/DashboardPageContent';
@@ -50,23 +50,27 @@ function ViewFormPage({
useEffect(() => {
if (viewId) {
changePageTitle('Edit Custom View');
changePageTitle(formatMessage({id:'edit_custom_view'}));
} else {
changePageTitle('New Custom View');
changePageTitle(formatMessage({id:'new_custom_view'}));
}
return () => {
changePageTitle('');
};
}, [viewId, changePageTitle]);
// Handle delete view button click.
const handleDeleteView = useCallback((view) => {
setStateDeleteView(view);
}, []);
// Handle cancel delete button click.
const handleCancelDeleteView = useCallback(() => {
setStateDeleteView(null);
}, []);
// Handle confirm delete custom view.
const handleConfirmDeleteView = useCallback(() => {
requestDeleteView(stateDeleteView.id).then((response) => {
setStateDeleteView(null);
@@ -92,8 +96,8 @@ function ViewFormPage({
onDelete={handleDeleteView} />
<Alert
cancelButtonText="Cancel"
confirmButtonText="Delete"
cancelButtonText={<T id={'cancel'}/>}
confirmButtonText={<T id={'delete'}/>}
icon="trash"
intent={Intent.DANGER}
isOpen={stateDeleteView}
@@ -107,7 +111,7 @@ function ViewFormPage({
</If>
<If condition={fetchHook.error}>
<h4>Something wrong</h4>
<h4><T id={'something_wrong'}/></h4>
</If>
</DashboardPageContent>
</DashboardInsider>

View File

@@ -1,32 +1,169 @@
export default {
'hello_world': 'Hello World',
'email_or_phone_number': 'Email or phone number',
'password': 'Password',
'login': 'Login',
'invalid_email_or_phone_numner': 'Invalid email or phone number.',
'required': 'Required',
'reset_password': 'Reset Password',
'the_user_has_been_suspended_from_admin': 'The user has been suspended from the administrator.',
'email_and_password_entered_did_not_match': 'The email and password you entered did not match our records.',
'field_name_must_be_number': 'field_name_must_be_number',
'name': 'Name',
"search": "Search",
'reference': 'Reference',
'date': 'Date',
'description': 'Description',
'from_date': 'From date',
'to_date': 'To date',
'accounting_basis': 'Accounting basis',
'report_date_range': 'Report date range',
'log_in': 'Log in',
'forget_my_password': 'Forget my password',
'keep_me_logged_in': 'Keep me logged in',
'create_an_account': 'Create an account',
'need_bigcapital_account?': 'Need a Bigcapital account ?',
'show': 'Show',
'hide': 'Hide',
hello_world: 'Hello World',
email_or_phone_number: 'Email or phone number',
password: 'Password',
login: 'Login',
invalid_email_or_phone_numner: 'Invalid email or phone number.',
required: 'Required',
reset_password: 'Reset Password',
the_user_has_been_suspended_from_admin: 'The user has been suspended from the administrator.',
email_and_password_entered_did_not_match:
'The email and password you entered did not match our records.',
field_name_must_be_number: 'field_name_must_be_number',
name: 'Name',
search: 'Search',
reference: 'Reference',
date: 'Date',
description: 'Description',
from_date: 'From date',
to_date: 'To date',
accounting_basis: 'Accounting basis',
report_date_range: 'Report date range',
log_in: 'Log in',
forget_my_password: 'Forget my password',
keep_me_logged_in: 'Keep me logged in',
create_an_account: 'Create an account',
need_bigcapital_account: 'Need a Bigcapital account ?',
show: 'Show',
hide: 'Hide',
an_unexpected_error_occurred: 'An unexpected error occurred',
welcome_to_bigcapital: 'Welcome to Bigcapital',
enter_your_personal_information: ' Enter your personal information',
first_name: 'First Name',
last_name: 'Last Name',
phone_number: 'Phone Number',
you_email_address_is: 'You email address is',
you_will_use_this_address_to_sign_in_to_bigcapital:
'You will use this address to sign in to Bigcapital.',
signing_in_or_creating:
'By signing in or creating an account, you agree with our',
terms_conditions: 'Terms & Conditions',
and: 'and',
privacy_statement: 'Privacy Statement',
create_account: 'Create Account',
success: 'Success',
register_a_new_organization: 'Register a New Organization.',
you_have_a_bigcapital_account: 'You have a bigcapital account ?',
organization_name: 'Organization Name',
email: 'Email',
register: 'Register',
password_successfully_updated: 'The Password for your account was successfully updated.',
choose_a_new_password: 'Choose a new password',
you_remembered_your_password: 'You remembered your password ?',
new_password: 'New Password',
submit_new_password: 'Submit new password',
reset_your_password: 'Reset Your Password',
we_ll_send_you_a_link_to_reset_your_password: 'Enter your email address and well send you a link to reset your password.',
send_password_reset_link: 'Send password reset link',
return_to_log_in: 'Return to log in',
sub_account: 'Sub account?',
account_type: 'Account Type',
account_name: 'Account Name',
account_code: 'Account Code',
parent_account: 'Parent Account',
edit: 'Edit',
submit: 'Submit',
close: 'Close',
edit_account: 'Edit Account',
new_account: 'New Account',
edit_currency: 'Edit Currency',
new_currency: 'New Currency',
currency_name: 'Currency Name',
currency_code: 'Currency Code',
edit_exchange_rate: 'Edit Exchange Rate',
new_exchange_rate: 'New Exchange Rate',
delete_exchange_rate: 'Delete Exchange Rate',
exchange_rate: 'Exchange Rate',
currency_code: 'Currency Code',
edit_invite: 'Edit invite',
edit_category: 'Edit Category',
delete_category: 'Delete Category',
new_category: 'New Category',
category_name: 'Category Name',
parent_category: 'Parent Category',
new: 'New',
new_category: 'New Category',
invite_user: 'invite User',
your_access_to_your_team: 'Your teammate will get an email that gives them access to your team.',
invite: 'invite',
count: 'Count',
item_type: 'Item Type',
item_name: 'Item Name',
sku: 'SKU',
category: 'Category',
account: 'Account',
sales_information: 'Sales Information',
purchase_information: 'Purchase Information',
selling_price: 'Selling Price',
cost_price: 'Cost Price',
inventory_information: 'Inventory Information',
inventory_account: 'Inventory Account',
opening_stock: 'Opening Stock',
save: 'Save',
save_as_draft: 'Save as Draft',
active: 'Active',
new_item: 'New Item',
table_views: 'Table Views',
delete: 'Delete',
import: 'Import',
export: 'Export',
filter: 'Filter',
view_details: 'View Details',
edit_item: 'Edit Item',
delete_item: 'Delete Item',
sell_price: 'Sell Price',
cancel: 'Cancel',
move_to_trash: 'Move to Trash',
save_new: 'Save & New',
journal_number: 'Journal number',
credit_currency: 'Credit ({currency})',
debit_currency: 'Debit ({currency})',
note: 'Note',
new_lines: 'New lines',
clear_all_lines: 'Clear all lines',
new_journal: 'New Journal',
publish_journal: 'Publish Journal',
edit_journal: 'Edit Journal',
delete_journal: 'Delete Journal',
amount: 'Amount',
journal_no: 'Journal No.',
status: 'Status',
transaction_type: 'Transaction type',
created_at: 'Created At',
archive: 'Archive',
inactivate: 'Inactivate',
activate: 'Activate',
inactivate_account: 'Inactivate Account',
delete_account: 'Delete Account',
code: 'Code',
type: 'Type',
normal: 'Normal',
balance: 'Balance',
something_wrong: 'Something wrong',
filters: 'Filters',
add_order: 'Add order',
expense_account: 'Expense Account',
payment_account: 'Payment Account',
new_expense: 'New Expense',
bulk_update: 'Bulk Update',
all_accounts: 'All accounts',
go_to_bigcapital_com: '← Go to bigcapital.com',
currency: 'Currency',
new_conditional: '+ New Conditional',
chart_of_accounts: 'Chart of Accounts',
exchange_rate_details: 'Exchange Rate Details',
exchange_rate_list: 'Exchange Rate List',
manual_journals: 'Manual Journals',
edit_expense_details: 'Edit Expense Details',
expenses_list: 'Expenses List',
edit_category_details: 'Edit Category Details',
category_list: 'Category List',
edit_item_details: 'Edit Item Details',
items_list: 'Items List',
edit_custom_view: 'Edit Custom View',
new_custom_view: 'New Custom View',
view_name: 'View Name',
new_conditional: 'New Conditional',
'item': 'Item',
'account': 'Account',
'service_has_been_successful_created': '{service} {name} has been successfully created.',
@@ -42,22 +179,17 @@ export default {
'the_accounts_has_been_successfully_deleted': 'The accounts have been successfully deleted.',
'are_sure_to_inactive_this_account': 'Are you sure you want to inactive this account? You will be able to activate it later',
'are_sure_to_activate_this_account': 'Are you sure you want to activate this account? You will be able to inactivate it later',
'once_delete_this_account_you_will_able_to_restore_it': `Once you delete this account, you won\'t be able to restore it later. Are you sure you want to delete this account?<br /><br />If you're not sure, you can inactivate this account instead.`,
'the_journal_has_been_successfully_created': 'The journal #{number} has been successfully created.',
'the_journal_has_been_successfully_edited': 'The journal #{number} has been successfully edited.',
'credit': 'Credit',
'debit': 'Debit',
'once_delete_this_item_you_will_able_to_restore_it': `Once you delete this item, you won\'t be able to restore the item later. Are you sure you want to delete ?<br /><br />If you're not sure, you can inactivate it instead.`,
'the_item_has_been_successfully_deleted': 'The item has been successfully deleted.',
'the_item_category_has_been_successfully_created': 'The item category has been successfully created.',
'the_item_category_has_been_successfully_edited': 'The item category has been successfully edited.',
'once_delete_these_views_you_will_not_able_restore_them': 'Once you delete the custom view, you won\'t be able to restore it later. Are you sure you want to delete this view?',
'the_custom_view_has_been_successfully_deleted': 'The custom view has been successfully deleted.',
'teammate_invited_to_organization_account': 'Your teammate has been invited to the organization account.'
};
'teammate_invited_to_organization_account': 'Your teammate has been invited to the organization account.',
'select_account_type': 'Select account type',
};

View File

@@ -7,7 +7,7 @@ export default [
{
path: `${BASE_URL}/homepage`,
component: LazyLoader({
loader: () => import('containers/Homepage/Homepage')
loader: () => import('containers/Homepage/Homepage'),
}),
},
@@ -15,79 +15,76 @@ export default [
{
path: `${BASE_URL}/accounts`,
component: LazyLoader({
loader: () => import('containers/Accounts/AccountsChart')
})
loader: () => import('containers/Accounts/AccountsChart'),
}),
},
// Custom views.
{
path: `${BASE_URL}/custom_views/:resource_slug/new`,
component: LazyLoader({
loader: () => import('containers/Views/ViewFormPage')
})
loader: () => import('containers/Views/ViewFormPage'),
}),
},
{
path: `${BASE_URL}/custom_views/:view_id/edit`,
component: LazyLoader({
loader: () => import('containers/Views/ViewFormPage')
})
loader: () => import('containers/Views/ViewFormPage'),
}),
},
// Expenses.
{
path: `${BASE_URL}/expenses/new`,
component: LazyLoader({
loader: () => import('containers/Expenses/ExpenseForm')
loader: () => import('containers/Expenses/ExpenseForm'),
}),
},
{
path: `${BASE_URL}/expenses`,
component: LazyLoader({
loader: () => import('containers/Expenses/ExpensesList')
})
loader: () => import('containers/Expenses/ExpensesList'),
}),
},
// Accounting
{
path: `${BASE_URL}/accounting/make-journal-entry`,
component: LazyLoader({
loader: () =>
import('containers/Accounting/MakeJournalEntriesPage')
loader: () => import('containers/Accounting/MakeJournalEntriesPage'),
}),
},
{
path: `${BASE_URL}/accounting/manual-journals/:id/edit`,
component: LazyLoader({
loader: () =>
import('containers/Accounting/MakeJournalEntriesPage')
loader: () => import('containers/Accounting/MakeJournalEntriesPage'),
}),
},
{
path: `${BASE_URL}/accounting/manual-journals`,
component: LazyLoader({
loader: () =>
import('containers/Accounting/ManualJournalsList')
loader: () => import('containers/Accounting/ManualJournalsList'),
}),
},
{
path: `${BASE_URL}/items/categories`,
component: LazyLoader({
loader: () => import('containers/Items/ItemCategoriesList')
})
},
loader: () => import('containers/Items/ItemCategoriesList'),
}),
},
{
path: `${BASE_URL}/items/new`,
component: LazyLoader({
loader: () => import('containers/Items/ItemFormPage')
})
loader: () => import('containers/Items/ItemFormPage'),
}),
},
// Items
{
path: `${BASE_URL}/items`,
component: LazyLoader({
loader: () => import('containers/Items/ItemsList')
})
loader: () => import('containers/Items/ItemsList'),
}),
},
// Financial Reports.
@@ -95,19 +92,15 @@ export default [
path: `${BASE_URL}/accounting/general-ledger`,
component: LazyLoader({
loader: () =>
import(
'containers/FinancialStatements/GeneralLedger/GeneralLedger'
)
})
import('containers/FinancialStatements/GeneralLedger/GeneralLedger'),
}),
},
{
path: `${BASE_URL}/accounting/balance-sheet`,
component: LazyLoader({
loader: () =>
import(
'containers/FinancialStatements/BalanceSheet/BalanceSheet'
)
})
import('containers/FinancialStatements/BalanceSheet/BalanceSheet'),
}),
},
{
path: `${BASE_URL}/accounting/trial-balance-sheet`,
@@ -115,8 +108,8 @@ export default [
loader: () =>
import(
'containers/FinancialStatements/TrialBalanceSheet/TrialBalanceSheet'
)
})
),
}),
},
{
path: `${BASE_URL}/accounting/profit-loss-sheet`,
@@ -124,14 +117,20 @@ export default [
loader: () =>
import(
'containers/FinancialStatements/ProfitLossSheet/ProfitLossSheet'
)
})
),
}),
},
{
path: `${BASE_URL}/accounting/journal-sheet`,
component: LazyLoader({
loader: () => import('containers/FinancialStatements/Journal/Journal'),
}),
},
{
path: `${BASE_URL}/ExchangeRates`,
component: LazyLoader({
loader: () =>
import('containers/FinancialStatements/Journal/Journal')
})
import('containers/ExchangeRates/ExchangeRate'),
}),
},
];

View File

@@ -0,0 +1,65 @@
import ApiService from 'services/ApiService';
import t from 'store/types';
export const fetchExchangeRates = () => {
return (dispatch) =>
new Promise((resolve, reject) => {
dispatch({
type: t.SET_DASHBOARD_REQUEST_LOADING,
});
dispatch({
type: t.EXCHANGE_RATE_TABLE_LOADING,
loading: true,
});
ApiService.get('exchange_rates')
.then((response) => {
dispatch({
type: t.EXCHANGE_RATE_LIST_SET,
exchange_rates: response.data.exchange_rates.results,
});
dispatch({
type: t.SET_DASHBOARD_REQUEST_COMPLETED,
});
dispatch({
type: t.EXCHANGE_RATE_TABLE_LOADING,
loading: false,
});
resolve(response);
})
.catch((error) => {
reject(error);
});
});
};
export const submitExchangeRate = ({ form }) => {
return (dispatch) => {
return ApiService.post('exchange_rates', form);
};
};
export const deleteExchangeRate = (id) => {
return (dispatch) => ApiService.delete(`exchange_rates/${id}`);
};
export const editExchangeRate = (id, form) => {
return (dispatch) =>
new Promise((resolve, reject) => {
ApiService.post(`exchange_rates/${id}`, form)
.then((response) => {
dispatch({ type: t.CLEAR_EXCHANGE_RATE_FORM_ERRORS });
resolve(response);
})
.catch((error) => {
const { response } = error;
const { data } = response;
const { errors } = data;
dispatch({ type: t.CLEAR_EXCHANGE_RATE_FORM_ERRORS });
if (errors) {
dispatch({ type: t.CLEAR_EXCHANGE_RATE_FORM_ERRORS, errors });
}
reject(error);
});
});
};

View File

@@ -0,0 +1,23 @@
import { createReducer } from '@reduxjs/toolkit';
import t from 'store/types';
const initialState = {
exchangeRates: {},
};
export default createReducer(initialState, {
[t.EXCHANGE_RATE_LIST_SET]: (state, action) => {
const _exchangeRates = {};
action.exchange_rates.forEach((exchange_rate) => {
_exchangeRates[exchange_rate.id] = exchange_rate;
});
state.exchangeRates = {
...state.exchangeRates,
..._exchangeRates,
};
},
[t.EXCHANGE_RATE_TABLE_LOADING]: (state, action) => {
state.loading = action.loading;
},
});

View File

@@ -0,0 +1,8 @@
export default {
EXCHANGE_RATE_DATA_TABLE: 'EXCHANGE_RATE_DATA_TABLE',
EXCHANGE_RATE_DELETE: 'EXCHANGE_RATE_DELETE',
EXCHANGE_RATE_LIST_SET: 'EXCHANGE_RATE_LIST_SET',
CLEAR_EXCHANGE_RATE_FORM_ERRORS: 'CLEAR_EXCHANGE_RATE_FORM_ERRORS',
ExchangeRates_TABLE_QUERIES_ADD: 'ExchangeRates_TABLE_QUERIES_ADD',
EXCHANGE_RATE_TABLE_LOADING:'EXCHANGE_RATE_TABLE_LOADING'
};

View File

@@ -15,6 +15,7 @@ import itemCategories from './itemCategories/itemsCategory.reducer';
import settings from './settings/settings.reducer';
import manualJournals from './manualJournals/manualJournals.reducers';
import globalSearch from './search/search.reducer';
import exchangeRates from './ExchangeRate/exchange.reducer'
export default combineReducers({
authentication,
@@ -32,4 +33,6 @@ export default combineReducers({
itemCategories,
settings,
globalSearch,
exchangeRates
});

View File

@@ -15,6 +15,7 @@ import itemCategories from './itemCategories/itemsCategory.type';
import settings from './settings/settings.type';
import search from './search/search.type';
import register from './registers/register.type';
import exchangeRate from './ExchangeRate/exchange.type';
export default {
...authentication,
@@ -34,4 +35,6 @@ export default {
...accounting,
...search,
...register,
...exchangeRate,
};

View File

@@ -49,6 +49,7 @@ $pt-font-family: Noto Sans, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
@import 'pages/invite-form.scss';
@import "pages/currency";
@import "pages/invite-user.scss";
@import 'pages/exchange-rate.scss';
// Views
@import 'views/filter-dropdown';

View File

@@ -0,0 +1,23 @@
.exchangeRate{
&-menu {
width: 240px;
}
}
.dialog--exchangeRate-form {
.bp3-dialog-body {
.bp3-form-group.bp3-inline {
.bp3-label {
min-width: 140px;
}
.bp3-form-content {
width: 250px;
}
}
}
}

View File

@@ -2,7 +2,6 @@ import bcrypt from 'bcryptjs';
import { Model } from 'objection';
import TenantModel from '@/models/TenantModel';
export default class ExchangeRate extends TenantModel {
/**
* Table name.