feat: expand sidebar once open form editor page.

feat: rounding money amount.
feat: optimize page form structure.
feat: refactoring make journal and expense form with FastField component.
This commit is contained in:
Ahmed Bouhuolia
2020-11-29 00:06:59 +02:00
parent 53dd447540
commit 011542e2a3
118 changed files with 3883 additions and 2660 deletions

View File

@@ -0,0 +1,39 @@
import * as Yup from 'yup';
import { formatMessage } from 'services/intl';
const Schema = Yup.object().shape({
journal_number: Yup.string()
.required()
.min(1)
.max(255)
.label(formatMessage({ id: 'journal_number_' })),
journal_type: Yup.string()
.required()
.min(1)
.max(255)
.label(formatMessage({ id: 'journal_type' })),
date: Yup.date()
.required()
.label(formatMessage({ id: 'date' })),
currency_code: Yup.string(),
reference: Yup.string().min(1).max(255),
description: Yup.string().min(1).max(1024),
entries: Yup.array().of(
Yup.object().shape({
credit: Yup.number().nullable(),
debit: Yup.number().nullable(),
account_id: Yup.number()
.nullable()
.when(['credit', 'debit'], {
is: (credit, debit) => credit || debit,
then: Yup.number().required(),
}),
contact_id: Yup.number().nullable(),
contact_type: Yup.string().nullable(),
note: Yup.string().max(255).nullable(),
}),
),
});
export const CreateJournalSchema = Schema;
export const EditJournalSchema = Schema;

View File

@@ -0,0 +1,37 @@
import React from 'react';
import { FastField } from 'formik';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import MakeJournalEntriesTable from './MakeJournalEntriesTable';
import { orderingLinesIndexes, repeatValue } from 'utils';
export default function MakeJournalEntriesField({
defaultRow,
linesNumber = 4,
}) {
return (
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
<FastField name={'entries'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<MakeJournalEntriesTable
onChange={(entries) => {
form.setFieldValue('entries', entries);
}}
entries={value}
error={error}
onClickAddNewRow={() => {
form.setFieldValue('entries', [...value, defaultRow]);
}}
onClickClearAllLines={() => {
form.setFieldValue(
'entries',
orderingLinesIndexes([...repeatValue(defaultRow, linesNumber)])
);
}}
/>
)}
</FastField>
</div>
);
}

View File

@@ -1,58 +0,0 @@
import React from 'react';
import { Intent, Button } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
export default function MakeJournalEntriesFooter({
isSubmitting,
onSubmitClick,
onCancelClick,
manualJournalId,
}) {
return (
<div>
<div class="form__floating-footer">
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
name={'save'}
onClick={() => {
onSubmitClick({ publish: true, redirect: true });
}}
>
{manualJournalId ? <T id={'edit'} /> : <T id={'save'} />}
</Button>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
className={'ml1'}
name={'save_and_new'}
onClick={() => {
onSubmitClick({ publish: true, redirect: false });
}}
>
<T id={'save_new'} />
</Button>
<Button
disabled={isSubmitting}
className={'button-secondary ml1'}
onClick={() => {
onSubmitClick({ publish: false, redirect: true });
}}
>
<T id={'save_as_draft'} />
</Button>
<Button
className={'button-secondary ml1'}
onClick={() => {
onCancelClick && onCancelClick();
}}
>
<T id={'cancel'} />
</Button>
</div>
</div>
);
}

View File

@@ -1,20 +1,21 @@
import React, {
useMemo,
useState,
useEffect,
useRef,
useCallback,
} from 'react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import React, { useMemo, useEffect, useCallback } from 'react';
import { Formik, Form } from 'formik';
import moment from 'moment';
import { Intent } from '@blueprintjs/core';
import { useIntl } from 'react-intl';
import { pick, setWith } from 'lodash';
import { pick } from 'lodash';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import {
CreateJournalSchema,
EditJournalSchema,
} from './MakeJournalEntries.schema';
import MakeJournalEntriesHeader from './MakeJournalEntriesHeader';
import MakeJournalEntriesFooter from './MakeJournalEntriesFooter';
import MakeJournalEntriesTable from './MakeJournalEntriesTable';
import MakeJournalFormFloatingActions from './MakeJournalFormFloatingActions';
import MakeJournalEntriesField from './MakeJournalEntriesField';
import MakeJournalNumberWatcher from './MakeJournalNumberWatcher';
import MakeJournalFormFooter from './MakeJournalFormFooter';
import withJournalsActions from 'containers/Accounting/withJournalsActions';
import withManualJournalDetail from 'containers/Accounting/withManualJournalDetail';
@@ -25,25 +26,31 @@ import withSettings from 'containers/Settings/withSettings';
import AppToaster from 'components/AppToaster';
import Dragzone from 'components/Dragzone';
import withMediaActions from 'containers/Media/withMediaActions';
import useMedia from 'hooks/useMedia';
import {
compose,
repeatValue,
orderingLinesIndexes,
defaultToTransform,
} from 'utils';
import { transformErrors } from './utils';
import withManualJournalsActions from './withManualJournalsActions';
import withManualJournals from './withManualJournals';
const ERROR = {
JOURNAL_NUMBER_ALREADY_EXISTS: 'JOURNAL.NUMBER.ALREADY.EXISTS',
CUSTOMERS_NOT_WITH_RECEVIABLE_ACC: 'CUSTOMERS.NOT.WITH.RECEIVABLE.ACCOUNT',
VENDORS_NOT_WITH_PAYABLE_ACCOUNT: 'VENDORS.NOT.WITH.PAYABLE.ACCOUNT',
PAYABLE_ENTRIES_HAS_NO_VENDORS: 'PAYABLE.ENTRIES.HAS.NO.VENDORS',
RECEIVABLE_ENTRIES_HAS_NO_CUSTOMERS: 'RECEIVABLE.ENTRIES.HAS.NO.CUSTOMERS',
CREDIT_DEBIT_SUMATION_SHOULD_NOT_EQUAL_ZERO:
'CREDIT.DEBIT.SUMATION.SHOULD.NOT.EQUAL.ZERO',
const defaultEntry = {
index: 0,
account_id: '',
credit: '',
debit: '',
contact_id: '',
note: '',
};
const defaultInitialValues = {
journal_number: '',
journal_type: 'Journal',
date: moment(new Date()).format('YYYY-MM-DD'),
description: '',
reference: '',
currency_code: '',
entries: [...repeatValue(defaultEntry, 4)],
};
/**
@@ -77,27 +84,9 @@ function MakeJournalEntriesForm({
onCancelForm,
}) {
const { formatMessage } = useIntl();
const {
setFiles,
saveMedia,
deletedFiles,
setDeletedFiles,
deleteMedia,
} = useMedia({
saveCallback: requestSubmitMedia,
deleteCallback: requestDeleteMedia,
});
const isNewMode = manualJournalId;
const handleDropFiles = useCallback((_files) => {
setFiles(_files.filter((file) => file.uploaded === false));
}, []);
const savedMediaIds = useRef([]);
const clearSavedMediaIds = () => {
savedMediaIds.current = [];
};
const journalNumber = journalNumberPrefix
const journalNumber = isNewMode
? `${journalNumberPrefix}-${journalNextNumber}`
: journalNextNumber;
@@ -122,73 +111,6 @@ function MakeJournalEntriesForm({
formatMessage,
]);
const validationSchema = Yup.object().shape({
journal_number: Yup.string()
.required()
.min(1)
.max(255)
.label(formatMessage({ id: 'journal_number_' })),
journal_type: Yup.string()
.required()
.min(1)
.max(255)
.label(formatMessage({ id: 'journal_type' })),
date: Yup.date()
.required()
.label(formatMessage({ id: 'date' })),
currency_code: Yup.string(),
reference: Yup.string().min(1).max(255),
description: Yup.string().min(1).max(1024),
entries: Yup.array().of(
Yup.object().shape({
credit: Yup.number().decimalScale(13).nullable(),
debit: Yup.number().decimalScale(13).nullable(),
account_id: Yup.number()
.nullable()
.when(['credit', 'debit'], {
is: (credit, debit) => credit || debit,
then: Yup.number().required(),
}),
contact_id: Yup.number().nullable(),
contact_type: Yup.string().nullable(),
note: Yup.string().max(255).nullable(),
}),
),
});
const saveInvokeSubmit = useCallback(
(payload) => {
onFormSubmit && onFormSubmit(payload);
},
[onFormSubmit],
);
const [payload, setPayload] = useState({});
const defaultEntry = useMemo(
() => ({
index: 0,
account_id: null,
credit: 0,
debit: 0,
contact_id: null,
note: '',
}),
[],
);
const defaultInitialValues = useMemo(
() => ({
journal_number: journalNumber,
journal_type: 'Journal',
date: moment(new Date()).format('YYYY-MM-DD'),
description: '',
reference: '',
currency_code: '',
entries: [...repeatValue(defaultEntry, 4)],
}),
[defaultEntry, journalNumber],
);
const initialValues = useMemo(
() => ({
...(manualJournal
@@ -198,300 +120,124 @@ function MakeJournalEntriesForm({
...pick(entry, Object.keys(defaultEntry)),
})),
}
: {
: {
...defaultInitialValues,
journal_number: journalNumber,
entries: orderingLinesIndexes(defaultInitialValues.entries),
}),
}),
[manualJournal, defaultInitialValues, defaultEntry],
[manualJournal, journalNumber],
);
const initialAttachmentFiles = useMemo(() => {
return manualJournal && manualJournal.media
? manualJournal.media.map((attach) => ({
preview: attach.attachment_file,
uploaded: true,
metadata: { ...attach },
}))
: [];
}, [manualJournal]);
// Transform API errors in toasts messages.
const transformErrors = (resErrors, { setErrors, errors }) => {
const getError = (errorType) => resErrors.find((e) => e.type === errorType);
const toastMessages = [];
let error;
let newErrors = { ...errors, entries: [] };
const setEntriesErrors = (indexes, prop, message) =>
indexes.forEach((i) => {
const index = Math.max(i - 1, 0);
newErrors = setWith(newErrors, `entries.[${index}].${prop}`, message);
});
if ((error = getError(ERROR.PAYABLE_ENTRIES_HAS_NO_VENDORS))) {
toastMessages.push(
formatMessage({
id: 'vendors_should_selected_with_payable_account_only',
}),
);
setEntriesErrors(error.indexes, 'contact_id', 'error');
}
if ((error = getError(ERROR.RECEIVABLE_ENTRIES_HAS_NO_CUSTOMERS))) {
toastMessages.push(
formatMessage({
id: 'should_select_customers_with_entries_have_receivable_account',
}),
);
setEntriesErrors(error.indexes, 'contact_id', 'error');
}
if ((error = getError(ERROR.CUSTOMERS_NOT_WITH_RECEVIABLE_ACC))) {
toastMessages.push(
formatMessage({
id: 'customers_should_selected_with_receivable_account_only',
}),
);
setEntriesErrors(error.indexes, 'account_id', 'error');
}
if ((error = getError(ERROR.VENDORS_NOT_WITH_PAYABLE_ACCOUNT))) {
toastMessages.push(
formatMessage({
id: 'vendors_should_selected_with_payable_account_only',
}),
);
setEntriesErrors(error.indexes, 'account_id', 'error');
}
if ((error = getError(ERROR.JOURNAL_NUMBER_ALREADY_EXISTS))) {
newErrors = setWith(
newErrors,
'journal_number',
formatMessage({
id: 'journal_number_is_already_used',
}),
);
}
setErrors({ ...newErrors });
if (toastMessages.length > 0) {
AppToaster.show({
message: toastMessages.map((message) => {
return <div>- {message}</div>;
}),
intent: Intent.DANGER,
});
}
};
const {
values,
errors,
setFieldError,
setFieldValue,
handleSubmit,
getFieldProps,
touched,
isSubmitting,
} = useFormik({
validationSchema,
initialValues,
onSubmit: (values, { setErrors, setSubmitting, resetForm }) => {
setSubmitting(true);
const entries = values.entries.filter(
(entry) => entry.debit || entry.credit,
);
const getTotal = (type = 'credit') => {
return entries.reduce((total, item) => {
return item[type] ? item[type] + total : total;
}, 0);
};
const totalCredit = getTotal('credit');
const totalDebit = getTotal('debit');
// Validate the total credit should be eqials total debit.
if (totalCredit !== totalDebit) {
AppToaster.show({
message: formatMessage({
id: 'should_total_of_credit_and_debit_be_equal',
}),
intent: Intent.DANGER,
});
setSubmitting(false);
return;
} else if (totalCredit === 0 || totalDebit === 0) {
AppToaster.show({
message: formatMessage({
id: 'amount_cannot_be_zero_or_empty',
}),
intent: Intent.DANGER,
});
setSubmitting(false);
return;
}
const form = { ...values, status: payload.publish, entries };
const saveJournal = (mediaIds) =>
new Promise((resolve, reject) => {
const requestForm = { ...form, media_ids: mediaIds };
if (manualJournal && manualJournal.id) {
requestEditManualJournal(manualJournal.id, requestForm)
.then((response) => {
AppToaster.show({
message: formatMessage(
{ id: 'the_journal_has_been_successfully_edited' },
{ number: values.journal_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
saveInvokeSubmit({ action: 'update', ...payload });
clearSavedMediaIds([]);
resetForm();
resolve(response);
})
.catch((errors) => {
transformErrors(errors, { setErrors });
setSubmitting(false);
});
} else {
requestMakeJournalEntries(requestForm)
.then((response) => {
AppToaster.show({
message: formatMessage(
{ id: 'the_journal_has_been_successfully_created' },
{ number: values.journal_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
saveInvokeSubmit({ action: 'new', ...payload });
clearSavedMediaIds();
resetForm();
resolve(response);
})
.catch((errors) => {
transformErrors(errors, { setErrors });
setSubmitting(false);
});
}
});
Promise.all([saveMedia(), deleteMedia()])
.then(([savedMediaResponses]) => {
const mediaIds = savedMediaResponses.map((res) => res.data.media.id);
savedMediaIds.current = mediaIds;
return savedMediaResponses;
})
.then(() => {
return saveJournal(savedMediaIds.current);
});
},
});
// Observes journal number settings changes.
useEffect(() => {
if (journalNumberChanged) {
setFieldValue('journal_number', journalNumber);
changePageSubtitle(
defaultToTransform(journalNumber, `No. ${journalNumber}`, ''),
);
setJournalNumberChanged(false);
}
}, [
journalNumber,
journalNumberChanged,
setJournalNumberChanged,
setFieldValue,
changePageSubtitle,
]);
const handleSubmitClick = useCallback(
(payload) => {
setPayload(payload);
// formik.resetForm();
handleSubmit();
},
[setPayload, handleSubmit],
);
const handleCancelClick = useCallback(
(payload) => {
onCancelForm && onCancelForm(payload);
},
[onCancelForm],
);
const handleDeleteFile = useCallback(
(_deletedFiles) => {
_deletedFiles.forEach((deletedFile) => {
if (deletedFile.uploaded && deletedFile.metadata.id) {
setDeletedFiles([...deletedFiles, deletedFile.metadata.id]);
}
});
},
[setDeletedFiles, deletedFiles],
);
// Handle click on add a new line/row.
const handleClickAddNewRow = useCallback(() => {
setFieldValue(
'entries',
orderingLinesIndexes([...values.entries, defaultEntry]),
);
}, [values.entries, defaultEntry, setFieldValue]);
// Handle click `Clear all lines` button.
const handleClickClearLines = useCallback(() => {
setFieldValue(
'entries',
orderingLinesIndexes([...repeatValue(defaultEntry, 4)]),
);
}, [defaultEntry, setFieldValue]);
// Handle journal number field change.
const handleJournalNumberChanged = useCallback(
(journalNumber) => {
changePageSubtitle(
defaultToTransform(journalNumber, `No. ${journalNumber}`, '')
defaultToTransform(journalNumber, `No. ${journalNumber}`, ''),
);
},
[changePageSubtitle],
);
return (
<div class="make-journal-entries">
<form onSubmit={handleSubmit}>
<MakeJournalEntriesHeader
manualJournal={manualJournalId}
errors={errors}
touched={touched}
values={values}
setFieldValue={setFieldValue}
getFieldProps={getFieldProps}
onJournalNumberChanged={handleJournalNumberChanged}
/>
<MakeJournalEntriesTable
values={values.entries}
errors={errors}
setFieldValue={setFieldValue}
defaultRow={defaultEntry}
onClickClearAllLines={handleClickClearLines}
onClickAddNewRow={handleClickAddNewRow}
/>
<MakeJournalEntriesFooter
isSubmitting={isSubmitting}
onSubmitClick={handleSubmitClick}
onCancelClick={handleCancelClick}
manualJournal={manualJournalId}
/>
</form>
<Dragzone
const handleSubmit = (values, { setErrors, setSubmitting, resetForm }) => {
setSubmitting(true);
const entries = values.entries.filter(
(entry) => entry.debit || entry.credit,
);
const getTotal = (type = 'credit') => {
return entries.reduce((total, item) => {
return item[type] ? item[type] + total : total;
}, 0);
};
const totalCredit = getTotal('credit');
const totalDebit = getTotal('debit');
// Validate the total credit should be eqials total debit.
if (totalCredit !== totalDebit) {
AppToaster.show({
message: formatMessage({
id: 'should_total_of_credit_and_debit_be_equal',
}),
intent: Intent.DANGER,
});
setSubmitting(false);
return;
} else if (totalCredit === 0 || totalDebit === 0) {
AppToaster.show({
message: formatMessage({
id: 'amount_cannot_be_zero_or_empty',
}),
intent: Intent.DANGER,
});
setSubmitting(false);
return;
}
const form = { ...values, entries };
const handleError = (error) => {
transformErrors(error, { setErrors });
setSubmitting(false);
};
const handleSuccess = (errors) => {
AppToaster.show({
message: formatMessage(
{
id: isNewMode
? 'the_journal_has_been_successfully_created'
: 'the_journal_has_been_successfully_edited',
},
{ number: values.journal_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
resetForm();
};
if (isNewMode) {
requestEditManualJournal(manualJournal.id, form)
.then(handleSuccess)
.catch(handleError);
} else {
requestMakeJournalEntries(form).then(handleSuccess).catch(handleError);
}
};
return (
<div
className={classNames(
CLASSES.PAGE_FORM,
CLASSES.PAGE_FORM_STRIP_STYLE,
CLASSES.PAGE_FORM_MAKE_JOURNAL
)}
>
<Formik
initialValues={initialValues}
validationSchema={isNewMode ? CreateJournalSchema : EditJournalSchema}
onSubmit={handleSubmit}
>
{({ isSubmitting, values }) => (
<Form>
<MakeJournalEntriesHeader
manualJournal={manualJournalId}
onJournalNumberChanged={handleJournalNumberChanged}
/>
<MakeJournalNumberWatcher journalNumber={journalNumber} />
<MakeJournalEntriesField defaultRow={defaultEntry} />
<MakeJournalFormFooter />
<MakeJournalFormFloatingActions
isSubmitting={isSubmitting}
manualJournal={manualJournalId}
/>
</Form>
)}
</Formik>
{/* <Dragzone
initialFiles={initialAttachmentFiles}
onDrop={handleDropFiles}
onDeleteFile={handleDeleteFile}
hint={'Attachments: Maxiumum size: 20MB'}
/>
/> */}
</div>
);
}
@@ -503,11 +249,8 @@ export default compose(
withDashboardActions,
withMediaActions,
withSettings(({ manualJournalsSettings }) => ({
journalNextNumber: manualJournalsSettings.nextNumber,
journalNumberPrefix: manualJournalsSettings.numberPrefix,
journalNextNumber: parseInt(manualJournalsSettings?.nextNumber, 10),
journalNumberPrefix: manualJournalsSettings?.numberPrefix,
})),
withManualJournalsActions,
withManualJournals(({ journalNumberChanged }) => ({
journalNumberChanged,
})),
)(MakeJournalEntriesForm);

View File

@@ -1,238 +1,12 @@
import React, { useMemo, useState, useCallback } from 'react';
import {
InputGroup,
FormGroup,
Intent,
Position,
ControlGroup,
} from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FormattedMessage as T } from 'react-intl';
import { Row, Col } from 'react-grid-system';
import moment from 'moment';
import React from 'react';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import { momentFormatter, tansformDateValue, saveInvoke } from 'utils';
import {
ErrorMessage,
Hint,
FieldHint,
FieldRequiredHint,
Icon,
InputPrependButton,
CurrencySelectList,
} from 'components';
import withDialogActions from 'containers/Dialog/withDialogActions';
import withCurrencies from 'containers/Currencies/withCurrencies';
import { compose } from 'utils';
function MakeJournalEntriesHeader({
errors,
touched,
values,
setFieldValue,
getFieldProps,
// #ownProps
manualJournal,
onJournalNumberChanged,
// #withCurrencies
currenciesList,
// #withDialog
openDialog,
}) {
const [selectedItems, setSelectedItems] = useState({});
const handleDateChange = useCallback(
(date) => {
const formatted = moment(date).format('YYYY-MM-DD');
setFieldValue('date', formatted);
},
[setFieldValue],
);
const handleJournalNumberChange = useCallback(() => {
openDialog('journal-number-form', {});
}, [openDialog]);
// Handle journal number field blur event.
const handleJournalNumberChanged = (event) => {
saveInvoke(onJournalNumberChanged, event.currentTarget.value);
};
const onItemsSelect = useCallback(
(filedName) => {
return (filed) => {
setSelectedItems({
...selectedItems,
[filedName]: filed,
});
setFieldValue(filedName, filed.currency_code);
};
},
[setFieldValue, selectedItems],
);
import MakeJournalEntriesHeaderFields from "./MakeJournalEntriesHeaderFields";
export default function MakeJournalEntriesHeader() {
return (
<div class="make-journal-entries__header">
<Row>
<Col width={260}>
<FormGroup
label={<T id={'journal_number'} />}
labelInfo={
<>
<FieldRequiredHint />
<FieldHint />
</>
}
className={'form-group--journal-number'}
intent={
errors.journal_number && touched.journal_number && Intent.DANGER
}
helperText={
<ErrorMessage name="journal_number" {...{ errors, touched }} />
}
fill={true}
>
<ControlGroup fill={true}>
<InputGroup
intent={
errors.journal_number &&
touched.journal_number &&
Intent.DANGER
}
fill={true}
{...getFieldProps('journal_number')}
onBlur={handleJournalNumberChanged}
/>
<InputPrependButton
buttonProps={{
onClick: handleJournalNumberChange,
icon: <Icon icon={'settings-18'} />,
}}
tooltip={true}
tooltipProps={{
content: 'Setting your auto-generated journal number',
position: Position.BOTTOM_LEFT,
}}
/>
</ControlGroup>
</FormGroup>
</Col>
<Col width={220}>
<FormGroup
label={<T id={'date'} />}
labelInfo={<FieldRequiredHint />}
intent={errors.date && touched.date && Intent.DANGER}
helperText={<ErrorMessage name="date" {...{ errors, touched }} />}
minimal={true}
className={classNames(CLASSES.FILL)}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
onChange={handleDateChange}
value={tansformDateValue(values.date)}
popoverProps={{
position: Position.BOTTOM,
minimal: true,
}}
/>
</FormGroup>
</Col>
<Col width={400}>
<FormGroup
label={<T id={'description'} />}
className={'form-group--description'}
intent={errors.name && touched.name && Intent.DANGER}
helperText={
<ErrorMessage name="description" {...{ errors, touched }} />
}
fill={true}
>
<InputGroup
intent={errors.name && touched.name && Intent.DANGER}
fill={true}
{...getFieldProps('description')}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col width={260}>
<FormGroup
label={<T id={'reference'} />}
labelInfo={
<Hint
content={<T id={'journal_reference_hint'} />}
position={Position.RIGHT}
/>
}
className={'form-group--reference'}
intent={errors.reference && touched.reference && Intent.DANGER}
helperText={
<ErrorMessage name="reference" {...{ errors, touched }} />
}
fill={true}
>
<InputGroup
intent={errors.reference && touched.reference && Intent.DANGER}
fill={true}
{...getFieldProps('reference')}
/>
</FormGroup>
</Col>
<Col width={220}>
<FormGroup
label={<T id={'journal_type'} />}
className={classNames(
'form-group--account-type',
'form-group--select-list',
CLASSES.FILL,
)}
>
<InputGroup
intent={
errors.journal_type && touched.journal_type && Intent.DANGER
}
fill={true}
{...getFieldProps('journal_type')}
/>
</FormGroup>
</Col>
<Col width={230}>
<FormGroup
label={<T id={'currency'} />}
className={classNames(
'form-group--select-list',
'form-group--currency',
CLASSES.FILL,
)}
>
<CurrencySelectList
currenciesList={currenciesList}
selectedCurrencyCode={values.currency_code}
onCurrencySelected={onItemsSelect('currency_code')}
defaultSelectText={values.currency_code}
/>
</FormGroup>
</Col>
</Row>
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<MakeJournalEntriesHeaderFields />
</div>
);
}
export default compose(
withDialogActions,
withCurrencies(({ currenciesList }) => ({
currenciesList,
})),
)(MakeJournalEntriesHeader);
)
}

View File

@@ -0,0 +1,188 @@
import React, { useCallback } from 'react';
import {
InputGroup,
FormGroup,
Position,
ControlGroup,
} from '@blueprintjs/core';
import { FastField, ErrorMessage } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import { FormattedMessage as T } from 'react-intl';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import { momentFormatter, tansformDateValue, saveInvoke } from 'utils';
import {
Hint,
FieldHint,
FieldRequiredHint,
Icon,
InputPrependButton,
CurrencySelectList,
} from 'components';
import withDialogActions from 'containers/Dialog/withDialogActions';
import withCurrencies from 'containers/Currencies/withCurrencies';
import { compose, inputIntent, handleDateChange } from 'utils';
function MakeJournalEntriesHeader({
// #ownProps
manualJournal,
onJournalNumberChanged,
// #withCurrencies
currenciesList,
// #withDialog
openDialog,
}) {
const handleJournalNumberChange = useCallback(() => {
openDialog('journal-number-form', {});
}, [openDialog]);
// Handle journal number field blur event.
const handleJournalNumberChanged = (event) => {
saveInvoke(onJournalNumberChanged, event.currentTarget.value);
};
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
<FastField name={'date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'posting_date'} />}
labelInfo={<FieldRequiredHint />}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="date" />}
minimal={true}
inline={true}
className={classNames(CLASSES.FILL)}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('date', formattedDate);
})}
value={tansformDateValue(value)}
popoverProps={{
position: Position.BOTTOM,
minimal: true,
}}
inputProps={{
leftIcon: <Icon icon={'date-range'} />,
}}
/>
</FormGroup>
)}
</FastField>
<FastField name={'journal_number'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'journal_no'} />}
labelInfo={
<>
<FieldRequiredHint />
<FieldHint />
</>
}
className={'form-group--journal-number'}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="journal_number" />}
fill={true}
inline={true}
>
<ControlGroup fill={true}>
<InputGroup
fill={true}
{...field}
onBlur={handleJournalNumberChanged}
/>
<InputPrependButton
buttonProps={{
onClick: handleJournalNumberChange,
icon: <Icon icon={'settings-18'} />,
}}
tooltip={true}
tooltipProps={{
content: 'Setting your auto-generated journal number',
position: Position.BOTTOM_LEFT,
}}
/>
</ControlGroup>
</FormGroup>
)}
</FastField>
<FastField name={'reference'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'reference'} />}
labelInfo={
<Hint
content={<T id={'journal_reference_hint'} />}
position={Position.RIGHT}
/>
}
className={'form-group--reference'}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="reference" />}
fill={true}
inline={true}
>
<InputGroup fill={true} {...field} />
</FormGroup>
)}
</FastField>
<FastField name={'journal_type'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'journal_type'} />}
className={classNames(
'form-group--account-type',
CLASSES.FILL,
)}
inline={true}
>
<InputGroup
intent={inputIntent({ error, touched })}
fill={true}
{...field}
/>
</FormGroup>
)}
</FastField>
<FastField name={'currency'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'currency'} />}
className={classNames(
'form-group--currency',
CLASSES.FILL,
)}
inline={true}
>
<CurrencySelectList
currenciesList={currenciesList}
selectedCurrencyCode={value}
onCurrencySelected={(currencyItem) => {
form.setFieldValue('currency_code', currencyItem.currency_code);
}}
defaultSelectText={value}
/>
</FormGroup>
)}
</FastField>
</div>
);
}
export default compose(
withDialogActions,
withCurrencies(({ currenciesList }) => ({
currenciesList,
})),
)(MakeJournalEntriesHeader);

View File

@@ -1,4 +1,4 @@
import React, { useCallback } from 'react';
import React, { useCallback, useEffect } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
@@ -10,6 +10,7 @@ import withAccountsActions from 'containers/Accounts/withAccountsActions';
import withManualJournalsActions from 'containers/Accounting/withManualJournalsActions';
import withCurrenciesActions from 'containers/Currencies/withCurrenciesActions';
import withSettingsActions from 'containers/Settings/withSettingsActions';
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import { compose } from 'utils';
@@ -28,10 +29,24 @@ function MakeJournalEntriesPage({
// #withSettingsActions
requestFetchOptions,
// #withDashboardActions
setSidebarShrink,
resetSidebarPreviousExpand
}) {
const history = useHistory();
const { id } = useParams();
useEffect(() => {
// Shrink the sidebar by foce.
setSidebarShrink();
return () => {
// Reset the sidebar to the previous status.
resetSidebarPreviousExpand();
};
}, [resetSidebarPreviousExpand, setSidebarShrink]);
const fetchAccounts = useQuery('accounts-list', (key) =>
requestFetchAccounts(),
);
@@ -88,4 +103,5 @@ export default compose(
withManualJournalsActions,
withCurrenciesActions,
withSettingsActions,
withDashboardActions,
)(MakeJournalEntriesPage);

View File

@@ -2,91 +2,32 @@ import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { Button, Tooltip, Position, Intent } from '@blueprintjs/core';
import { FormattedMessage as T, useIntl } from 'react-intl';
import { omit } from 'lodash';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import DataTable from 'components/DataTable';
import Icon from 'components/Icon';
import { Hint } from 'components';
import { compose, formattedAmount, transformUpdatedRows } from 'utils';
import {
compose,
formattedAmount,
transformUpdatedRows,
saveInvoke,
} from 'utils';
import {
AccountsListFieldCell,
MoneyFieldCell,
InputGroupCell,
ContactsListFieldCell,
} from 'components/DataTableCells';
import {
ContactHeaderCell,
ActionsCellRenderer,
TotalAccountCellRenderer,
TotalCreditDebitCellRenderer,
NoteCellRenderer,
} from './components';
import withAccounts from 'containers/Accounts/withAccounts';
import withCustomers from 'containers/Customers/withCustomers';
// Contact header cell.
function ContactHeaderCell() {
return (
<>
<T id={'contact'} />
<Hint
content={<T id={'contact_column_hint'} />}
position={Position.LEFT_BOTTOM}
/>
</>
);
}
// Actions cell renderer.
const ActionsCellRenderer = ({
row: { index },
column: { id },
cell: { value: initialValue },
data,
payload,
}) => {
if (data.length <= index + 2) {
return '';
}
const onClickRemoveRole = () => {
payload.removeRow(index);
};
return (
<Tooltip content={<T id={'remove_the_line'} />} position={Position.LEFT}>
<Button
icon={<Icon icon="times-circle" iconSize={14} />}
iconSize={14}
className="ml2"
minimal={true}
intent={Intent.DANGER}
onClick={onClickRemoveRole}
/>
</Tooltip>
);
};
// Total text cell renderer.
const TotalAccountCellRenderer = (chainedComponent) => (props) => {
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) => {
const amount = parseInt(entry[type], 10);
const computed = amount ? total + amount : total;
return computed;
}, 0);
return <span>{formattedAmount(total, 'USD')}</span>;
}
return chainedComponent(props);
};
const NoteCellRenderer = (chainedComponent) => (props) => {
if (props.data.length === props.row.index + 2) {
return '';
}
return chainedComponent(props);
};
/**
* Make journal entries table component.
*/
@@ -101,22 +42,19 @@ function MakeJournalEntriesTable({
onClickRemoveRow,
onClickAddNewRow,
onClickClearAllLines,
defaultRow,
values,
errors, setFieldValue,
onChange,
entries,
error,
}) {
const [rows, setRows] = useState([]);
const { formatMessage } = useIntl();
useEffect(() => {
setRows([...values.map((e) => ({ ...e, rowType: 'editor' }))]);
}, [values, setRows]);
setRows([...entries.map((e) => ({ ...e, rowType: 'editor' }))]);
}, [entries, setRows]);
// Final table rows editor rows and total and final blank row.
const tableRows = useMemo(
() => [...rows, { rowType: 'total' }, { rowType: 'final_space' }],
[rows],
);
const tableRows = useMemo(() => [...rows, { rowType: 'total' }], [rows]);
// Memorized data table columns.
const columns = useMemo(
@@ -138,8 +76,7 @@ function MakeJournalEntriesTable({
Cell: TotalAccountCellRenderer(AccountsListFieldCell),
className: 'account',
disableSortBy: true,
disableResizing: true,
width: 250,
width: 140,
},
{
Header: formatMessage({ id: 'credit_currency' }, { currency: 'USD' }),
@@ -147,8 +84,7 @@ function MakeJournalEntriesTable({
Cell: TotalCreditDebitCellRenderer(MoneyFieldCell, 'credit'),
className: 'credit',
disableSortBy: true,
disableResizing: true,
width: 150,
width: 100,
},
{
Header: formatMessage({ id: 'debit_currency' }, { currency: 'USD' }),
@@ -156,8 +92,7 @@ function MakeJournalEntriesTable({
Cell: TotalCreditDebitCellRenderer(MoneyFieldCell, 'debit'),
className: 'debit',
disableSortBy: true,
disableResizing: true,
width: 150,
width: 100,
},
{
Header: ContactHeaderCell,
@@ -165,9 +100,8 @@ function MakeJournalEntriesTable({
accessor: 'contact_id',
Cell: NoteCellRenderer(ContactsListFieldCell),
className: 'contact',
disableResizing: true,
disableSortBy: true,
width: 200,
width: 120,
},
{
Header: formatMessage({ id: 'note' }),
@@ -175,6 +109,7 @@ function MakeJournalEntriesTable({
Cell: NoteCellRenderer(InputGroupCell),
disableSortBy: true,
className: 'note',
width: 200,
},
{
Header: '',
@@ -190,9 +125,9 @@ function MakeJournalEntriesTable({
);
// Handles click new line.
const onClickNewRow = useCallback(() => {
onClickAddNewRow && onClickAddNewRow();
}, [defaultRow, rows, onClickAddNewRow]);
const onClickNewRow = () => {
saveInvoke(onClickAddNewRow);
};
// Handles update datatable data.
const handleUpdateData = useCallback(
@@ -203,8 +138,8 @@ function MakeJournalEntriesTable({
columnIdOrObj,
value,
);
setFieldValue(
'entries',
saveInvoke(
onChange,
newRows
.filter((row) => row.rowType === 'editor')
.map((row) => ({
@@ -212,26 +147,27 @@ function MakeJournalEntriesTable({
})),
);
},
[rows, setFieldValue],
[rows, onChange],
);
const handleRemoveRow = useCallback(
(rowIndex) => {
// Can't continue if there is just one row line or less.
if (rows.length <= 2) { return; }
if (rows.length <= 2) {
return;
}
const removeIndex = parseInt(rowIndex, 10);
const newRows = rows.filter((row, index) => index !== removeIndex);
setFieldValue(
'entries',
saveInvoke(
onChange,
newRows
.filter((row) => row.rowType === 'editor')
.map((row) => ({ ...omit(row, ['rowType']) })),
);
onClickRemoveRow && onClickRemoveRow(removeIndex);
saveInvoke(onClickRemoveRow, removeIndex);
},
[rows, setFieldValue, onClickRemoveRow],
[rows, onChange, onClickRemoveRow],
);
// Rows class names callback.
@@ -243,11 +179,16 @@ function MakeJournalEntriesTable({
);
const handleClickClearAllLines = () => {
onClickClearAllLines && onClickClearAllLines();
saveInvoke(onClickClearAllLines);
};
return (
<div class="make-journal-entries__table datatable-editor">
<div
className={classNames(
CLASSES.DATATABLE_EDITOR,
CLASSES.DATATABLE_EDITOR_HAS_TOTAL_ROW,
)}
>
<DataTable
columns={columns}
data={tableRows}
@@ -255,7 +196,7 @@ function MakeJournalEntriesTable({
sticky={true}
payload={{
accounts: accountsList,
errors: errors.entries || [],
errors: error,
updateData: handleUpdateData,
removeRow: handleRemoveRow,
contacts: [
@@ -266,8 +207,7 @@ function MakeJournalEntriesTable({
],
}}
/>
<div class="mt1">
<div className={classNames(CLASSES.DATATABLE_EDITOR_ACTIONS)}>
<Button
small={true}
className={'button--secondary button--new-line'}

View File

@@ -0,0 +1,59 @@
import React from 'react';
import { Intent, Button } from '@blueprintjs/core';
import classNames from 'classnames';
import { FormattedMessage as T } from 'react-intl';
import { saveInvoke } from 'utils';
import { CLASSES } from 'common/classes';
export default function MakeJournalFloatingAction({
isSubmitting,
onSubmitClick,
onCancelClick,
manualJournalId,
}) {
return (
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
name={'save'}
onClick={() => {
saveInvoke(onSubmitClick, { publish: true, redirect: true });
}}
>
{manualJournalId ? <T id={'edit'} /> : <T id={'save'} />}
</Button>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
className={'ml1'}
name={'save_and_new'}
onClick={() => {
saveInvoke(onSubmitClick, { publish: true, redirect: false });
}}
>
<T id={'save_new'} />
</Button>
<Button
disabled={isSubmitting}
className={'button-secondary ml1'}
onClick={() => {
saveInvoke(onSubmitClick, { publish: false, redirect: true });
}}
>
<T id={'save_as_draft'} />
</Button>
<Button
className={'button-secondary ml1'}
onClick={() => {
saveInvoke(onCancelClick);
}}
>
<T id={'cancel'} />
</Button>
</div>
);
}

View File

@@ -0,0 +1,42 @@
import React from 'react';
import { FastField } from 'formik';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import { FormGroup, TextArea } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
import { ErrorMessage, Row, Col } from 'components';
import Dragzone from 'components/Dragzone';
import { inputIntent } from 'utils';
export default function MakeJournalFormFooter() {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Row>
<Col md={8}>
<FastField name={'description'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'description'} />}
className={'form-group--description'}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="description" />}
fill={true}
>
<TextArea fill={true} {...field} />
</FormGroup>
)}
</FastField>
</Col>
<Col md={4}>
<Dragzone
initialFiles={[]}
// onDrop={handleDropFiles}
// onDeleteFile={handleDeleteFile}
hint={'Attachments: Maxiumum size: 20MB'}
/>
</Col>
</Row>
</div>
);
}

View File

@@ -0,0 +1,48 @@
import { useEffect } from 'react';
import { compose } from 'redux';
import { useFormikContext } from 'formik';
import withManualJournalsActions from './withManualJournalsActions';
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withManualJournals from './withManualJournals';
import { defaultToTransform } from 'utils';
/**
*
*/
function MakeJournalNumberChangingWatcher({
journalNumber,
journalNumberChanged,
setJournalNumberChanged,
changePageSubtitle
}) {
const { setFieldValue } = useFormikContext();
// Observes journal number settings changes.
useEffect(() => {
if (journalNumberChanged) {
setFieldValue('journal_number', journalNumber);
changePageSubtitle(
defaultToTransform(journalNumber, `No. ${journalNumber}`, ''),
);
setJournalNumberChanged(false);
}
}, [
journalNumber,
journalNumberChanged,
setJournalNumberChanged,
setFieldValue,
changePageSubtitle,
]);
return null;
}
export default compose(
withManualJournals(({ journalNumberChanged }) => ({
journalNumberChanged,
})),
withManualJournalsActions,
withDashboardActions,
)(MakeJournalNumberChangingWatcher);

View File

@@ -1,13 +1,7 @@
import React from 'react';
import {
Intent,
Classes,
Tooltip,
Position,
Tag,
} from '@blueprintjs/core';
import { Intent, Classes, Tooltip, Position, Tag, Button } from '@blueprintjs/core';
import { FormattedMessage as T } from 'react-intl';
import { Choose, Money, If, Icon } from 'components';
import { Choose, Money, If, Icon, Hint } from 'components';
import withAccountDetails from 'containers/Accounts/withAccountDetail';
import { compose } from 'utils';
@@ -99,4 +93,77 @@ export function NoteAccessor(row) {
</Tooltip>
</If>
);
}
}
// Contact header cell.
export function ContactHeaderCell() {
return (
<>
<T id={'contact'} />
<Hint
content={<T id={'contact_column_hint'} />}
position={Position.LEFT_BOTTOM}
/>
</>
);
}
// Actions cell renderer.
export const ActionsCellRenderer = ({
row: { index },
column: { id },
cell: { value: initialValue },
data,
payload,
}) => {
if (data.length <= index + 1) {
return '';
}
const onClickRemoveRole = () => {
payload.removeRow(index);
};
return (
<Tooltip content={<T id={'remove_the_line'} />} position={Position.LEFT}>
<Button
icon={<Icon icon="times-circle" iconSize={14} />}
iconSize={14}
className="ml2"
minimal={true}
intent={Intent.DANGER}
onClick={onClickRemoveRole}
/>
</Tooltip>
);
};
// Total text cell renderer.
export const TotalAccountCellRenderer = (chainedComponent) => (props) => {
if (props.data.length === props.row.index + 1) {
return <span>{'Total USD'}</span>;
}
return chainedComponent(props);
};
// Total credit/debit cell renderer.
export const TotalCreditDebitCellRenderer = (chainedComponent, type) => (
props,
) => {
if (props.data.length === props.row.index + 1) {
const total = props.data.reduce((total, entry) => {
const amount = parseInt(entry[type], 10);
const computed = amount ? total + amount : total;
return computed;
}, 0);
return <span><Money amount={total} currency={'USD'} /></span>;
}
return chainedComponent(props);
};
export const NoteCellRenderer = (chainedComponent) => (props) => {
if (props.data.length === props.row.index + 1) {
return '';
}
return chainedComponent(props);
};

View File

@@ -0,0 +1,81 @@
import React from 'react';
import { Intent } from '@blueprintjs/core';
import { AppToaster } from 'components';
import { formatMessage } from 'services/intl';
import { setWith } from 'lodash';
const ERROR = {
JOURNAL_NUMBER_ALREADY_EXISTS: 'JOURNAL.NUMBER.ALREADY.EXISTS',
CUSTOMERS_NOT_WITH_RECEVIABLE_ACC: 'CUSTOMERS.NOT.WITH.RECEIVABLE.ACCOUNT',
VENDORS_NOT_WITH_PAYABLE_ACCOUNT: 'VENDORS.NOT.WITH.PAYABLE.ACCOUNT',
PAYABLE_ENTRIES_HAS_NO_VENDORS: 'PAYABLE.ENTRIES.HAS.NO.VENDORS',
RECEIVABLE_ENTRIES_HAS_NO_CUSTOMERS: 'RECEIVABLE.ENTRIES.HAS.NO.CUSTOMERS',
CREDIT_DEBIT_SUMATION_SHOULD_NOT_EQUAL_ZERO:
'CREDIT.DEBIT.SUMATION.SHOULD.NOT.EQUAL.ZERO',
};
// Transform API errors in toasts messages.
export const transformErrors = (resErrors, { setErrors, errors }) => {
const getError = (errorType) => resErrors.find((e) => e.type === errorType);
const toastMessages = [];
let error;
let newErrors = { ...errors, entries: [] };
const setEntriesErrors = (indexes, prop, message) =>
indexes.forEach((i) => {
const index = Math.max(i - 1, 0);
newErrors = setWith(newErrors, `entries.[${index}].${prop}`, message);
});
if ((error = getError(ERROR.PAYABLE_ENTRIES_HAS_NO_VENDORS))) {
toastMessages.push(
formatMessage({
id: 'vendors_should_selected_with_payable_account_only',
}),
);
setEntriesErrors(error.indexes, 'contact_id', 'error');
}
if ((error = getError(ERROR.RECEIVABLE_ENTRIES_HAS_NO_CUSTOMERS))) {
toastMessages.push(
formatMessage({
id: 'should_select_customers_with_entries_have_receivable_account',
}),
);
setEntriesErrors(error.indexes, 'contact_id', 'error');
}
if ((error = getError(ERROR.CUSTOMERS_NOT_WITH_RECEVIABLE_ACC))) {
toastMessages.push(
formatMessage({
id: 'customers_should_selected_with_receivable_account_only',
}),
);
setEntriesErrors(error.indexes, 'account_id', 'error');
}
if ((error = getError(ERROR.VENDORS_NOT_WITH_PAYABLE_ACCOUNT))) {
toastMessages.push(
formatMessage({
id: 'vendors_should_selected_with_payable_account_only',
}),
);
setEntriesErrors(error.indexes, 'account_id', 'error');
}
if ((error = getError(ERROR.JOURNAL_NUMBER_ALREADY_EXISTS))) {
newErrors = setWith(
newErrors,
'journal_number',
formatMessage({
id: 'journal_number_is_already_used',
}),
);
}
setErrors({ ...newErrors });
if (toastMessages.length > 0) {
AppToaster.show({
message: toastMessages.map((message) => {
return <div>- {message}</div>;
}),
intent: Intent.DANGER,
});
}
};