mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-16 21:00:31 +00:00
re-structure to monorepo.
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { useFormikContext } from 'formik';
|
||||
import {
|
||||
Intent,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
Popover,
|
||||
PopoverInteractionKind,
|
||||
Position,
|
||||
Menu,
|
||||
MenuItem,
|
||||
} from '@blueprintjs/core';
|
||||
import { If, Icon, FormattedMessage as T } from '@/components';
|
||||
import { CLASSES } from '@/constants/classes';
|
||||
import classNames from 'classnames';
|
||||
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
|
||||
|
||||
/**
|
||||
* Credit note floating actions.
|
||||
*/
|
||||
export default function CreditNoteFloatingActions() {
|
||||
const history = useHistory();
|
||||
|
||||
// Formik context.
|
||||
const { resetForm, submitForm, isSubmitting } = useFormikContext();
|
||||
|
||||
// Credit note form context.
|
||||
const { setSubmitPayload, creditNote } = useCreditNoteFormContext();
|
||||
|
||||
// Handle submit as open button click.
|
||||
const handleSubmitOpenBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, open: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit, open and anothe new button click.
|
||||
const handleSubmitOpenAndNewBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, open: true, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit as open & continue editing button click.
|
||||
const handleSubmitOpenContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, open: true });
|
||||
submitForm();
|
||||
};
|
||||
// Handle submit as draft button click.
|
||||
const handleSubmitDraftBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: true, open: false });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// handle submit as draft & new button click.
|
||||
const handleSubmitDraftAndNewBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, open: false, resetForm: true });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle submit as draft & continue editing button click.
|
||||
const handleSubmitDraftContinueEditingBtnClick = (event) => {
|
||||
setSubmitPayload({ redirect: false, open: false });
|
||||
submitForm();
|
||||
};
|
||||
|
||||
// Handle cancel button click.
|
||||
const handleCancelBtnClick = (event) => {
|
||||
history.goBack();
|
||||
};
|
||||
|
||||
const handleClearBtnClick = (event) => {
|
||||
resetForm();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
|
||||
{/* ----------- Save And Open ----------- */}
|
||||
<If condition={!creditNote || !creditNote?.is_open}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
onClick={handleSubmitOpenBtnClick}
|
||||
text={<T id={'save_open'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'open_and_new'} />}
|
||||
onClick={handleSubmitOpenAndNewBtnClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'open_continue_editing'} />}
|
||||
onClick={handleSubmitOpenContinueEditingBtnClick}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
minimal={true}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
|
||||
/>
|
||||
</Popover>
|
||||
</ButtonGroup>
|
||||
{/* ----------- Save As Draft ----------- */}
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
className={'ml1'}
|
||||
onClick={handleSubmitDraftBtnClick}
|
||||
text={<T id={'save_as_draft'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitDraftAndNewBtnClick}
|
||||
/>
|
||||
<MenuItem
|
||||
text={<T id={'save_continue_editing'} />}
|
||||
onClick={handleSubmitDraftContinueEditingBtnClick}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
minimal={true}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
|
||||
/>
|
||||
</Popover>
|
||||
</ButtonGroup>
|
||||
</If>
|
||||
{/* ----------- Save and New ----------- */}
|
||||
<If condition={creditNote && creditNote?.is_open}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
loading={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
onClick={handleSubmitOpenBtnClick}
|
||||
style={{ minWidth: '85px' }}
|
||||
text={<T id={'save'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={<T id={'save_and_new'} />}
|
||||
onClick={handleSubmitOpenAndNewBtnClick}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
minimal={true}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
>
|
||||
<Button
|
||||
disabled={isSubmitting}
|
||||
intent={Intent.PRIMARY}
|
||||
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
|
||||
/>
|
||||
</Popover>
|
||||
</ButtonGroup>
|
||||
</If>
|
||||
{/* ----------- Clear & Reset----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
disabled={isSubmitting}
|
||||
onClick={handleClearBtnClick}
|
||||
text={creditNote ? <T id={'reset'} /> : <T id={'clear'} />}
|
||||
/>
|
||||
{/* ----------- Cancel ----------- */}
|
||||
<Button
|
||||
className={'ml1'}
|
||||
disabled={isSubmitting}
|
||||
onClick={handleCancelBtnClick}
|
||||
text={<T id={'cancel'} />}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// @ts-nocheck
|
||||
import * as Yup from 'yup';
|
||||
import intl from 'react-intl-universal';
|
||||
import { DATATYPES_LENGTH } from '@/constants/dataTypes';
|
||||
import { isBlank } from '@/utils';
|
||||
|
||||
const getSchema = () =>
|
||||
Yup.object().shape({
|
||||
customer_id: Yup.string().label(intl.get('customer_name_')).required(),
|
||||
credit_note_date: Yup.date().required().label(intl.get('invoice_date_')),
|
||||
credit_note_number: Yup.string()
|
||||
.max(DATATYPES_LENGTH.STRING)
|
||||
.label(intl.get('invoice_no_')),
|
||||
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING),
|
||||
note: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(DATATYPES_LENGTH.TEXT)
|
||||
.label(intl.get('note')),
|
||||
open: Yup.boolean(),
|
||||
terms_conditions: Yup.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(DATATYPES_LENGTH.TEXT)
|
||||
.label(intl.get('note')),
|
||||
branch_id: Yup.string(),
|
||||
warehouse_id: Yup.string(),
|
||||
exchange_rate:Yup.number(),
|
||||
entries: Yup.array().of(
|
||||
Yup.object().shape({
|
||||
quantity: Yup.number()
|
||||
.nullable()
|
||||
.max(DATATYPES_LENGTH.INT_10)
|
||||
.when(['rate'], {
|
||||
is: (rate) => rate,
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
rate: Yup.number().nullable().max(DATATYPES_LENGTH.INT_10),
|
||||
item_id: Yup.number()
|
||||
.nullable()
|
||||
.when(['quantity', 'rate'], {
|
||||
is: (quantity, rate) => !isBlank(quantity) && !isBlank(rate),
|
||||
then: Yup.number().required(),
|
||||
}),
|
||||
discount: Yup.number().nullable().min(0).max(100),
|
||||
description: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export const CreateCreditNoteFormSchema = getSchema;
|
||||
export const EditCreditNoteFormSchema = getSchema;
|
||||
@@ -0,0 +1,177 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import classNames from 'classnames';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { Formik, Form } from 'formik';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import { isEmpty } from 'lodash';
|
||||
import { CLASSES } from '@/constants/classes';
|
||||
import {
|
||||
CreateCreditNoteFormSchema,
|
||||
EditCreditNoteFormSchema,
|
||||
} from './CreditNoteForm.schema';
|
||||
|
||||
import CreditNoteFormHeader from './CreditNoteFormHeader';
|
||||
import CreditNoteItemsEntriesEditorField from './CreditNoteItemsEntriesEditorField';
|
||||
import CreditNoteFormFooter from './CreditNoteFormFooter';
|
||||
import CreditNoteFloatingActions from './CreditNoteFloatingActions';
|
||||
import CreditNoteFormDialogs from './CreditNoteFormDialogs';
|
||||
import CreditNoteFormTopBar from './CreditNoteFormTopBar';
|
||||
|
||||
import { AppToaster } from '@/components';
|
||||
|
||||
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
|
||||
import {
|
||||
filterNonZeroEntries,
|
||||
transformToEditForm,
|
||||
transformFormValuesToRequest,
|
||||
defaultCreditNote,
|
||||
} from './utils';
|
||||
|
||||
import {
|
||||
compose,
|
||||
orderingLinesIndexes,
|
||||
transactionNumber,
|
||||
safeSumBy,
|
||||
} from '@/utils';
|
||||
|
||||
import withSettings from '@/containers/Settings/withSettings';
|
||||
import withCurrentOrganization from '@/containers/Organization/withCurrentOrganization';
|
||||
|
||||
/**
|
||||
* Credit note form.
|
||||
*/
|
||||
function CreditNoteForm({
|
||||
// #withSettings
|
||||
creditAutoIncrement,
|
||||
creditNumberPrefix,
|
||||
creditNextNumber,
|
||||
|
||||
// #withCurrentOrganization
|
||||
organization: { base_currency },
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Credit note form context.
|
||||
const {
|
||||
isNewMode,
|
||||
submitPayload,
|
||||
creditNote,
|
||||
newCreditNote,
|
||||
createCreditNoteMutate,
|
||||
editCreditNoteMutate,
|
||||
} = useCreditNoteFormContext();
|
||||
|
||||
// Credit number.
|
||||
const creditNumber = transactionNumber(creditNumberPrefix, creditNextNumber);
|
||||
|
||||
// Initial values.
|
||||
const initialValues = React.useMemo(
|
||||
() => ({
|
||||
...(!isEmpty(creditNote)
|
||||
? { ...transformToEditForm(creditNote) }
|
||||
: {
|
||||
...defaultCreditNote,
|
||||
...(creditAutoIncrement && {
|
||||
credit_note_number: creditNumber,
|
||||
}),
|
||||
entries: orderingLinesIndexes(defaultCreditNote.entries),
|
||||
currency_code: base_currency,
|
||||
...newCreditNote,
|
||||
}),
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
// Handles form submit.
|
||||
const handleFormSubmit = (
|
||||
values,
|
||||
{ setSubmitting, setErrors, resetForm },
|
||||
) => {
|
||||
const entries = filterNonZeroEntries(values.entries);
|
||||
const totalQuantity = safeSumBy(entries, 'quantity');
|
||||
|
||||
if (totalQuantity === 0) {
|
||||
AppToaster.show({
|
||||
message: intl.get('quantity_cannot_be_zero_or_empty'),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
const form = {
|
||||
...transformFormValuesToRequest(values),
|
||||
open: submitPayload.open,
|
||||
};
|
||||
// Handle the request success.
|
||||
const onSuccess = (response) => {
|
||||
AppToaster.show({
|
||||
message: intl.get(
|
||||
isNewMode
|
||||
? 'credit_note.success_message'
|
||||
: 'credit_note.edit_success_message',
|
||||
),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
setSubmitting(false);
|
||||
|
||||
if (submitPayload.redirect) {
|
||||
history.push('/credit-notes');
|
||||
}
|
||||
if (submitPayload.resetForm) {
|
||||
resetForm();
|
||||
}
|
||||
};
|
||||
// Handle the request error.
|
||||
const onError = ({
|
||||
response: {
|
||||
data: { errors },
|
||||
},
|
||||
}) => {
|
||||
setSubmitting(false);
|
||||
};
|
||||
if (isNewMode) {
|
||||
createCreditNoteMutate(form).then(onSuccess).catch(onError);
|
||||
} else {
|
||||
editCreditNoteMutate([creditNote.id, form])
|
||||
.then(onSuccess)
|
||||
.catch(onError);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
CLASSES.PAGE_FORM,
|
||||
CLASSES.PAGE_FORM_STRIP_STYLE,
|
||||
CLASSES.PAGE_FORM_CREDIT_NOTE,
|
||||
)}
|
||||
>
|
||||
<Formik
|
||||
validationSchema={
|
||||
isNewMode ? CreateCreditNoteFormSchema : EditCreditNoteFormSchema
|
||||
}
|
||||
initialValues={initialValues}
|
||||
onSubmit={handleFormSubmit}
|
||||
>
|
||||
<Form>
|
||||
<CreditNoteFormTopBar />
|
||||
<CreditNoteFormHeader />
|
||||
<CreditNoteItemsEntriesEditorField />
|
||||
<CreditNoteFormFooter />
|
||||
<CreditNoteFloatingActions />
|
||||
<CreditNoteFormDialogs />
|
||||
</Form>
|
||||
</Formik>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export default compose(
|
||||
withSettings(({ creditNoteSettings }) => ({
|
||||
creditAutoIncrement: creditNoteSettings?.autoIncrement,
|
||||
creditNextNumber: creditNoteSettings?.nextNumber,
|
||||
creditNumberPrefix: creditNoteSettings?.numberPrefix,
|
||||
})),
|
||||
withCurrentOrganization(),
|
||||
)(CreditNoteForm);
|
||||
@@ -0,0 +1,25 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import CreditNoteNumberDialog from '@/containers/Dialogs/CreditNoteNumberDialog';
|
||||
import { useFormikContext } from 'formik';
|
||||
|
||||
/**
|
||||
* Credit note form dialogs.
|
||||
*/
|
||||
export default function CreditNoteFormDialogs() {
|
||||
// Update the form once the credit number form submit confirm.
|
||||
const handleCreditNumberFormConfirm = ({ incrementNumber, manually }) => {
|
||||
setFieldValue('credit_note_number', incrementNumber || '');
|
||||
setFieldValue('credit_note_no_manually', manually);
|
||||
};
|
||||
|
||||
const { setFieldValue } = useFormikContext();
|
||||
return (
|
||||
<React.Fragment>
|
||||
<CreditNoteNumberDialog
|
||||
dialogName={'credit-number-form'}
|
||||
onConfirm={handleCreditNumberFormConfirm}
|
||||
/>
|
||||
</React.Fragment>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import classNames from 'classnames';
|
||||
import styled from 'styled-components';
|
||||
|
||||
import { CLASSES } from '@/constants/classes';
|
||||
import { Row, Col, Paper } from '@/components';
|
||||
import { CreditNoteFormFooterLeft } from './CreditNoteFormFooterLeft';
|
||||
import { CreditNoteFormFooterRight } from './CreditNoteFormFooterRight';
|
||||
|
||||
/**
|
||||
* Credit note form footer.
|
||||
*/
|
||||
export default function CreditNoteFormFooter() {
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
|
||||
<CreditNoteFooterPaper>
|
||||
<Row>
|
||||
<Col md={8}>
|
||||
<CreditNoteFormFooterLeft />
|
||||
</Col>
|
||||
|
||||
<Col md={4}>
|
||||
<CreditNoteFormFooterRight />
|
||||
</Col>
|
||||
</Row>
|
||||
</CreditNoteFooterPaper>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const CreditNoteFooterPaper = styled(Paper)`
|
||||
padding: 20px;
|
||||
`;
|
||||
@@ -0,0 +1,60 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import styled from 'styled-components';
|
||||
import { FFormGroup, FEditableText, FormattedMessage as T } from '@/components';
|
||||
|
||||
export function CreditNoteFormFooterLeft() {
|
||||
return (
|
||||
<React.Fragment>
|
||||
{/* --------- Customer notes --------- */}
|
||||
<CreditNoteMsgFormGroup
|
||||
name={'note'}
|
||||
label={<T id={'credit_note.label_customer_note'} />}
|
||||
>
|
||||
<FEditableText
|
||||
name={'note'}
|
||||
placeholder={intl.get('credit_note.label_customer_note.placeholder')}
|
||||
/>
|
||||
</CreditNoteMsgFormGroup>
|
||||
{/* --------- Terms and conditions --------- */}
|
||||
<TermsConditsFormGroup
|
||||
label={<T id={'credit_note.label_terms_conditions'} />}
|
||||
name={'terms_conditions'}
|
||||
>
|
||||
<FEditableText
|
||||
name={'terms_conditions'}
|
||||
placeholder={intl.get(
|
||||
'credit_note.label_terms_and_conditions.placeholder',
|
||||
)}
|
||||
/>
|
||||
</TermsConditsFormGroup>
|
||||
</React.Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
const CreditNoteMsgFormGroup = styled(FFormGroup)`
|
||||
&.bp3-form-group {
|
||||
margin-bottom: 40px;
|
||||
|
||||
.bp3-label {
|
||||
font-size: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.bp3-form-content {
|
||||
margin-left: 10px;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const TermsConditsFormGroup = styled(FFormGroup)`
|
||||
&.bp3-form-group {
|
||||
.bp3-label {
|
||||
font-size: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.bp3-form-content {
|
||||
margin-left: 10px;
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,35 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import styled from 'styled-components';
|
||||
import {
|
||||
T,
|
||||
TotalLines,
|
||||
TotalLine,
|
||||
TotalLineBorderStyle,
|
||||
TotalLineTextStyle,
|
||||
} from '@/components';
|
||||
import { useCreditNoteTotals } from './utils';
|
||||
|
||||
export function CreditNoteFormFooterRight() {
|
||||
const { formattedSubtotal, formattedTotal } = useCreditNoteTotals();
|
||||
|
||||
return (
|
||||
<CreditNoteTotalLines labelColWidth={'180px'} amountColWidth={'180px'}>
|
||||
<TotalLine
|
||||
title={<T id={'credit_note.label_subtotal'} />}
|
||||
value={formattedSubtotal}
|
||||
borderStyle={TotalLineBorderStyle.None}
|
||||
/>
|
||||
<TotalLine
|
||||
title={<T id={'credit_note.label_total'} />}
|
||||
value={formattedTotal}
|
||||
textStyle={TotalLineTextStyle.Bold}
|
||||
/>
|
||||
</CreditNoteTotalLines>
|
||||
);
|
||||
}
|
||||
|
||||
const CreditNoteTotalLines = styled(TotalLines)`
|
||||
width: 100%;
|
||||
color: #555555;
|
||||
`;
|
||||
@@ -0,0 +1,35 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import classNames from 'classnames';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { CLASSES } from '@/constants/classes';
|
||||
import CreditNoteFormHeaderFields from './CreditNoteFormHeaderFields';
|
||||
|
||||
import { getEntriesTotal } from '@/containers/Entries/utils';
|
||||
import { PageFormBigNumber } from '@/components';
|
||||
|
||||
/**
|
||||
* Credit note header.
|
||||
*/
|
||||
function CreditNoteFormHeader() {
|
||||
const {
|
||||
values: { entries, currency_code },
|
||||
} = useFormikContext();
|
||||
|
||||
// Calculate the total amount.
|
||||
const totalAmount = React.useMemo(() => getEntriesTotal(entries), [entries]);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
|
||||
<CreditNoteFormHeaderFields />
|
||||
<PageFormBigNumber
|
||||
label={intl.get('credit_note.label_amount_to_credit')}
|
||||
amount={totalAmount}
|
||||
currencyCode={currency_code}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreditNoteFormHeader;
|
||||
@@ -0,0 +1,215 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import classNames from 'classnames';
|
||||
import styled from 'styled-components';
|
||||
import {
|
||||
FormGroup,
|
||||
InputGroup,
|
||||
Position,
|
||||
ControlGroup,
|
||||
} from '@blueprintjs/core';
|
||||
import { DateInput } from '@blueprintjs/datetime';
|
||||
import { FastField, Field, ErrorMessage } from 'formik';
|
||||
import { CLASSES } from '@/constants/classes';
|
||||
import {
|
||||
CustomerSelectField,
|
||||
FieldRequiredHint,
|
||||
InputPrependButton,
|
||||
Icon,
|
||||
FormattedMessage as T,
|
||||
CustomerDrawerLink,
|
||||
} from '@/components';
|
||||
import {
|
||||
customerNameFieldShouldUpdate,
|
||||
useObserveCreditNoSettings,
|
||||
} from './utils';
|
||||
|
||||
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
|
||||
import withSettings from '@/containers/Settings/withSettings';
|
||||
import withDialogActions from '@/containers/Dialog/withDialogActions';
|
||||
import { CreditNoteExchangeRateInputField } from './components';
|
||||
import {
|
||||
momentFormatter,
|
||||
compose,
|
||||
tansformDateValue,
|
||||
inputIntent,
|
||||
handleDateChange,
|
||||
} from '@/utils';
|
||||
|
||||
/**
|
||||
* Credit note form header fields.
|
||||
*/
|
||||
function CreditNoteFormHeaderFields({
|
||||
// #withDialogActions
|
||||
openDialog,
|
||||
|
||||
// #withSettings
|
||||
creditAutoIncrement,
|
||||
creditNumberPrefix,
|
||||
creditNextNumber,
|
||||
}) {
|
||||
// Credit note form context.
|
||||
const { customers } = useCreditNoteFormContext();
|
||||
|
||||
// Handle credit number changing.
|
||||
const handleCreditNumberChange = () => {
|
||||
openDialog('credit-number-form');
|
||||
};
|
||||
|
||||
// Handle credit no. field blur.
|
||||
const handleCreditNoBlur = (form, field) => (event) => {
|
||||
const newValue = event.target.value;
|
||||
|
||||
if (field.value !== newValue && creditAutoIncrement) {
|
||||
openDialog('credit-number-form', {
|
||||
initialFormValues: {
|
||||
manualTransactionNo: newValue,
|
||||
incrementMode: 'manual-transaction',
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Syncs credit number settings with form.
|
||||
useObserveCreditNoSettings(creditNumberPrefix, creditNextNumber);
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
|
||||
{/* ----------- Customer name ----------- */}
|
||||
<FastField
|
||||
name={'customer_id'}
|
||||
customers={customers}
|
||||
shouldUpdate={customerNameFieldShouldUpdate}
|
||||
>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'customer_name'} />}
|
||||
inline={true}
|
||||
className={classNames(
|
||||
'form-group--customer-name',
|
||||
'form-group--select-list',
|
||||
CLASSES.FILL,
|
||||
)}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name={'customer_id'} />}
|
||||
>
|
||||
<CustomerSelectField
|
||||
contacts={customers}
|
||||
selectedContactId={value}
|
||||
defaultSelectText={<T id={'select_customer_account'} />}
|
||||
onContactSelected={(customer) => {
|
||||
form.setFieldValue('customer_id', customer.id);
|
||||
form.setFieldValue('currency_code', customer?.currency_code);
|
||||
}}
|
||||
popoverFill={true}
|
||||
allowCreate={true}
|
||||
/>
|
||||
{value && (
|
||||
<CustomerButtonLink customerId={value}>
|
||||
<T id={'view_customer_details'} />
|
||||
</CustomerButtonLink>
|
||||
)}
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
|
||||
{/* ----------- Exchange rate ----------- */}
|
||||
<CreditNoteExchangeRateInputField
|
||||
name={'exchange_rate'}
|
||||
formGroupProps={{ label: ' ', inline: true }}
|
||||
/>
|
||||
|
||||
{/* ----------- Credit note date ----------- */}
|
||||
<FastField name={'credit_note_date'}>
|
||||
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'credit_note.label_credit_note_date'} />}
|
||||
inline={true}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
className={classNames('form-group--credit_note_date', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="credit_note_date" />}
|
||||
>
|
||||
<DateInput
|
||||
{...momentFormatter('YYYY/MM/DD')}
|
||||
value={tansformDateValue(value)}
|
||||
onChange={handleDateChange((formattedDate) => {
|
||||
form.setFieldValue('credit_note_date', formattedDate);
|
||||
})}
|
||||
popoverProps={{ position: Position.BOTTOM_LEFT, minimal: true }}
|
||||
inputProps={{
|
||||
leftIcon: <Icon icon={'date-range'} />,
|
||||
}}
|
||||
/>
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
{/* ----------- Credit note # ----------- */}
|
||||
<Field name={'credit_note_number'}>
|
||||
{({ form, field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'credit_note.label_credit_note'} />}
|
||||
labelInfo={<FieldRequiredHint />}
|
||||
inline={true}
|
||||
className={classNames(
|
||||
'form-group--credit_note_number',
|
||||
CLASSES.FILL,
|
||||
)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="credit_note_number" />}
|
||||
>
|
||||
<ControlGroup fill={true}>
|
||||
<InputGroup
|
||||
minimal={true}
|
||||
value={field.value}
|
||||
asyncControl={true}
|
||||
onBlur={handleCreditNoBlur(form, field)}
|
||||
/>
|
||||
<InputPrependButton
|
||||
buttonProps={{
|
||||
onClick: handleCreditNumberChange,
|
||||
icon: <Icon icon={'settings-18'} />,
|
||||
}}
|
||||
tooltip={true}
|
||||
tooltipProps={{
|
||||
content: (
|
||||
<T id={'setting_your_auto_generated_credit_note_number'} />
|
||||
),
|
||||
position: Position.BOTTOM_LEFT,
|
||||
}}
|
||||
/>
|
||||
</ControlGroup>
|
||||
</FormGroup>
|
||||
)}
|
||||
</Field>
|
||||
{/* ----------- Reference ----------- */}
|
||||
<FastField name={'reference_no'}>
|
||||
{({ field, meta: { error, touched } }) => (
|
||||
<FormGroup
|
||||
label={<T id={'reference_no'} />}
|
||||
inline={true}
|
||||
className={classNames('form-group--reference', CLASSES.FILL)}
|
||||
intent={inputIntent({ error, touched })}
|
||||
helperText={<ErrorMessage name="reference_no" />}
|
||||
>
|
||||
<InputGroup minimal={true} {...field} />
|
||||
</FormGroup>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export default compose(
|
||||
withDialogActions,
|
||||
withSettings(({ creditNoteSettings }) => ({
|
||||
creditAutoIncrement: creditNoteSettings?.autoIncrement,
|
||||
creditNextNumber: creditNoteSettings?.nextNumber,
|
||||
creditNumberPrefix: creditNoteSettings?.numberPrefix,
|
||||
})),
|
||||
)(CreditNoteFormHeaderFields);
|
||||
|
||||
const CustomerButtonLink = styled(CustomerDrawerLink)`
|
||||
font-size: 11px;
|
||||
margin-top: 6px;
|
||||
`;
|
||||
@@ -0,0 +1,22 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
import '@/style/pages/CreditNote/PageForm.scss';
|
||||
|
||||
import CreditNoteForm from './CreditNoteForm';
|
||||
import { CreditNoteFormProvider } from './CreditNoteFormProvider';
|
||||
|
||||
/**
|
||||
* Credit note form page.
|
||||
*/
|
||||
export default function CreditNoteFormPage() {
|
||||
const { id } = useParams();
|
||||
const idAsInteger = parseInt(id, 10);
|
||||
|
||||
return (
|
||||
<CreditNoteFormProvider creditNoteId={idAsInteger}>
|
||||
<CreditNoteForm />
|
||||
</CreditNoteFormProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { isEmpty, pick } from 'lodash';
|
||||
import { DashboardInsider } from '@/components/Dashboard';
|
||||
import { transformToEditForm } from './utils';
|
||||
import { Features } from '@/constants';
|
||||
import { useFeatureCan } from '@/hooks/state';
|
||||
|
||||
import {
|
||||
useCreditNote,
|
||||
useCreateCreditNote,
|
||||
useEditCreditNote,
|
||||
useItems,
|
||||
useCustomers,
|
||||
useWarehouses,
|
||||
useBranches,
|
||||
useSettingsCreditNotes,
|
||||
useInvoice,
|
||||
} from '@/hooks/query';
|
||||
|
||||
const CreditNoteFormContext = React.createContext();
|
||||
|
||||
/**
|
||||
* Credit note data provider.
|
||||
*/
|
||||
function CreditNoteFormProvider({ creditNoteId, ...props }) {
|
||||
const { state } = useLocation();
|
||||
const invoiceId = state?.invoiceId;
|
||||
|
||||
// Features guard.
|
||||
const { featureCan } = useFeatureCan();
|
||||
const isWarehouseFeatureCan = featureCan(Features.Warehouses);
|
||||
const isBranchFeatureCan = featureCan(Features.Branches);
|
||||
|
||||
// Handle fetch customers data table or list
|
||||
const {
|
||||
data: { customers },
|
||||
isLoading: isCustomersLoading,
|
||||
} = useCustomers({ page_size: 10000 });
|
||||
|
||||
// Handle fetching the items table based on the given query.
|
||||
const {
|
||||
data: { items },
|
||||
isLoading: isItemsLoading,
|
||||
} = useItems({
|
||||
page_size: 10000,
|
||||
});
|
||||
|
||||
// Handle fetch credit details.
|
||||
const { data: creditNote, isLoading: isCreditNoteLoading } = useCreditNote(
|
||||
creditNoteId,
|
||||
{
|
||||
enabled: !!creditNoteId,
|
||||
},
|
||||
);
|
||||
// Handle fetch invoice detail.
|
||||
const { data: invoice, isLoading: isInvoiceLoading } = useInvoice(invoiceId, {
|
||||
enabled: !!invoiceId,
|
||||
});
|
||||
|
||||
// Fetch warehouses list.
|
||||
const {
|
||||
data: warehouses,
|
||||
isLoading: isWarehouesLoading,
|
||||
isSuccess: isWarehousesSuccess,
|
||||
} = useWarehouses({}, { enabled: isWarehouseFeatureCan });
|
||||
|
||||
// Fetches the branches list.
|
||||
const {
|
||||
data: branches,
|
||||
isLoading: isBranchesLoading,
|
||||
isSuccess: isBranchesSuccess,
|
||||
} = useBranches({}, { enabled: isBranchFeatureCan });
|
||||
|
||||
// Handle fetching settings.
|
||||
useSettingsCreditNotes();
|
||||
|
||||
// Create and edit credit note mutations.
|
||||
const { mutateAsync: createCreditNoteMutate } = useCreateCreditNote();
|
||||
const { mutateAsync: editCreditNoteMutate } = useEditCreditNote();
|
||||
|
||||
// Form submit payload.
|
||||
const [submitPayload, setSubmitPayload] = React.useState();
|
||||
|
||||
// Determines whether the form in new mode.
|
||||
const isNewMode = !creditNoteId;
|
||||
|
||||
// Determines whether the warehouse and branches are loading.
|
||||
const isFeatureLoading = isWarehouesLoading || isBranchesLoading;
|
||||
|
||||
const newCreditNote = !isEmpty(invoice)
|
||||
? transformToEditForm({
|
||||
...pick(invoice, ['customer_id', 'currency_code', 'entries']),
|
||||
})
|
||||
: [];
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
items,
|
||||
customers,
|
||||
creditNote,
|
||||
branches,
|
||||
warehouses,
|
||||
submitPayload,
|
||||
isNewMode,
|
||||
newCreditNote,
|
||||
|
||||
isItemsLoading,
|
||||
isCustomersLoading,
|
||||
isFeatureLoading,
|
||||
isBranchesSuccess,
|
||||
isWarehousesSuccess,
|
||||
|
||||
createCreditNoteMutate,
|
||||
editCreditNoteMutate,
|
||||
setSubmitPayload,
|
||||
};
|
||||
|
||||
const isLoading =
|
||||
isItemsLoading ||
|
||||
isCustomersLoading ||
|
||||
isCreditNoteLoading ||
|
||||
isInvoiceLoading;
|
||||
|
||||
return (
|
||||
<DashboardInsider loading={isLoading} name={'credit-note-form'}>
|
||||
<CreditNoteFormContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const useCreditNoteFormContext = () => React.useContext(CreditNoteFormContext);
|
||||
|
||||
export { CreditNoteFormProvider, useCreditNoteFormContext };
|
||||
@@ -0,0 +1,115 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import {
|
||||
Alignment,
|
||||
NavbarGroup,
|
||||
NavbarDivider,
|
||||
Button,
|
||||
Classes,
|
||||
} from '@blueprintjs/core';
|
||||
import {
|
||||
useSetPrimaryBranchToForm,
|
||||
useSetPrimaryWarehouseToForm,
|
||||
} from './utils';
|
||||
import { Features } from '@/constants';
|
||||
import { useFeatureCan } from '@/hooks/state';
|
||||
import {
|
||||
Icon,
|
||||
BranchSelect,
|
||||
FeatureCan,
|
||||
WarehouseSelect,
|
||||
FormTopbar,
|
||||
DetailsBarSkeletonBase,
|
||||
} from '@/components';
|
||||
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
|
||||
|
||||
/**
|
||||
* Credit note form topbar .
|
||||
* @returns {JSX.Element}
|
||||
*/
|
||||
export default function CreditNoteFormTopbar() {
|
||||
// Features guard.
|
||||
const { featureCan } = useFeatureCan();
|
||||
|
||||
// Sets the primary warehouse to form.
|
||||
useSetPrimaryWarehouseToForm();
|
||||
|
||||
// Sets the primary branch to form.
|
||||
useSetPrimaryBranchToForm();
|
||||
|
||||
// Can't display the navigation bar if warehouses or branches feature is not enabled.
|
||||
if (!featureCan(Features.Warehouses) && !featureCan(Features.Branches)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<FormTopbar>
|
||||
<NavbarGroup align={Alignment.LEFT}>
|
||||
<FeatureCan feature={Features.Branches}>
|
||||
<CreditNoteFormSelectBranch />
|
||||
</FeatureCan>
|
||||
{featureCan(Features.Warehouses) && featureCan(Features.Branches) && (
|
||||
<NavbarDivider />
|
||||
)}
|
||||
<FeatureCan feature={Features.Warehouses}>
|
||||
<CreditFormSelectWarehouse />
|
||||
</FeatureCan>
|
||||
</NavbarGroup>
|
||||
</FormTopbar>
|
||||
);
|
||||
}
|
||||
|
||||
function CreditNoteFormSelectBranch() {
|
||||
// Credit note form context.
|
||||
const { branches, isBranchesLoading } = useCreditNoteFormContext();
|
||||
|
||||
return isBranchesLoading ? (
|
||||
<DetailsBarSkeletonBase className={Classes.SKELETON} />
|
||||
) : (
|
||||
<BranchSelect
|
||||
name={'branch_id'}
|
||||
branches={branches}
|
||||
input={CreditNoteBranchSelectButton}
|
||||
popoverProps={{ minimal: true }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CreditFormSelectWarehouse() {
|
||||
// Credit note form context.
|
||||
const { warehouses, isWarehouesLoading } = useCreditNoteFormContext();
|
||||
|
||||
return isWarehouesLoading ? (
|
||||
<DetailsBarSkeletonBase className={Classes.SKELETON} />
|
||||
) : (
|
||||
<WarehouseSelect
|
||||
name={'warehouse_id'}
|
||||
warehouses={warehouses}
|
||||
input={CreditNoteWarehouseSelectButton}
|
||||
popoverProps={{ minimal: true }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CreditNoteWarehouseSelectButton({ label }) {
|
||||
return (
|
||||
<Button
|
||||
text={intl.get('credit_note.warehouse_button.label', { label })}
|
||||
minimal={true}
|
||||
small={true}
|
||||
icon={<Icon icon={'warehouse-16'} iconSize={16} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CreditNoteBranchSelectButton({ label }) {
|
||||
return (
|
||||
<Button
|
||||
text={intl.get('credit_note.branch_button.label', { label })}
|
||||
minimal={true}
|
||||
small={true}
|
||||
icon={<Icon icon={'branch-16'} iconSize={16} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { FastField } from 'formik';
|
||||
import { CLASSES } from '@/constants/classes';
|
||||
import ItemsEntriesTable from '@/containers/Entries/ItemsEntriesTable';
|
||||
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
|
||||
import { entriesFieldShouldUpdate } from './utils';
|
||||
|
||||
/**
|
||||
* Credit note items entries editor field.
|
||||
*/
|
||||
export default function CreditNoteItemsEntriesEditorField() {
|
||||
const { items } = useCreditNoteFormContext();
|
||||
|
||||
return (
|
||||
<div className={classNames(CLASSES.PAGE_FORM_BODY)}>
|
||||
<FastField
|
||||
name={'entries'}
|
||||
items={items}
|
||||
shouldUpdate={entriesFieldShouldUpdate}
|
||||
>
|
||||
{({
|
||||
form: { values, setFieldValue },
|
||||
field: { value },
|
||||
meta: { error, touched },
|
||||
}) => (
|
||||
<ItemsEntriesTable
|
||||
entries={value}
|
||||
onUpdateData={(entries) => {
|
||||
setFieldValue('entries', entries);
|
||||
}}
|
||||
items={items}
|
||||
errors={error}
|
||||
linesNumber={4}
|
||||
currencyCode={values.currency_code}
|
||||
/>
|
||||
)}
|
||||
</FastField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { BaseCurrency, BaseCurrencyRoot } from '@/components';
|
||||
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
|
||||
|
||||
/**
|
||||
* Credit note from currency tag.
|
||||
* @returns
|
||||
*/
|
||||
export default function CreditNotetFormCurrencyTag() {
|
||||
const { isForeignCustomer, selectCustomer } = useCreditNoteFormContext();
|
||||
|
||||
if (!isForeignCustomer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<BaseCurrencyRoot>
|
||||
<BaseCurrency currency={selectCustomer?.currency_code} />
|
||||
</BaseCurrencyRoot>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { ExchangeRateInputGroup } from '@/components';
|
||||
import { useCurrentOrganization } from '@/hooks/state';
|
||||
import { useCreditNoteIsForeignCustomer } from './utils';
|
||||
|
||||
|
||||
/**
|
||||
* credit exchange rate input field.
|
||||
* @returns {JSX.Element}
|
||||
*/
|
||||
export function CreditNoteExchangeRateInputField({ ...props }) {
|
||||
const currentOrganization = useCurrentOrganization();
|
||||
const { values } = useFormikContext();
|
||||
|
||||
const isForeignCustomer = useCreditNoteIsForeignCustomer();
|
||||
|
||||
// Can't continue if the customer is not foreign.
|
||||
if (!isForeignCustomer) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<ExchangeRateInputGroup
|
||||
fromCurrency={values.currency_code}
|
||||
toCurrency={currentOrganization.base_currency}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import moment from 'moment';
|
||||
import * as R from 'ramda';
|
||||
import { first } from 'lodash';
|
||||
|
||||
import {
|
||||
defaultFastFieldShouldUpdate,
|
||||
transformToForm,
|
||||
repeatValue,
|
||||
transactionNumber,
|
||||
formattedAmount,
|
||||
orderingLinesIndexes,
|
||||
} from '@/utils';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
|
||||
|
||||
import {
|
||||
updateItemsEntriesTotal,
|
||||
ensureEntriesHaveEmptyLine,
|
||||
} from '@/containers/Entries/utils';
|
||||
import { useCurrentOrganization } from '@/hooks/state';
|
||||
import { getEntriesTotal } from '@/containers/Entries/utils';
|
||||
|
||||
export const MIN_LINES_NUMBER = 1;
|
||||
|
||||
// Default entry object.
|
||||
export const defaultCreditNoteEntry = {
|
||||
index: 0,
|
||||
item_id: '',
|
||||
rate: '',
|
||||
discount: '',
|
||||
quantity: '',
|
||||
description: '',
|
||||
amount: '',
|
||||
};
|
||||
|
||||
// Default credit note object.
|
||||
export const defaultCreditNote = {
|
||||
customer_id: '',
|
||||
credit_note_date: moment(new Date()).format('YYYY-MM-DD'),
|
||||
credit_note_number: '',
|
||||
credit_note_no_manually: false,
|
||||
open: '',
|
||||
reference_no: '',
|
||||
note: '',
|
||||
terms_conditions: '',
|
||||
branch_id: '',
|
||||
warehouse_id: '',
|
||||
exchange_rate: 1,
|
||||
currency_code: '',
|
||||
entries: [...repeatValue(defaultCreditNoteEntry, MIN_LINES_NUMBER)],
|
||||
};
|
||||
|
||||
/**
|
||||
* Transform credit note to initial values in edit mode.
|
||||
*/
|
||||
export function transformToEditForm(creditNote) {
|
||||
const initialEntries = [
|
||||
...creditNote.entries.map((creditNote) => ({
|
||||
...transformToForm(creditNote, defaultCreditNoteEntry),
|
||||
})),
|
||||
...repeatValue(
|
||||
defaultCreditNoteEntry,
|
||||
Math.max(MIN_LINES_NUMBER - creditNote.entries.length, 0),
|
||||
),
|
||||
];
|
||||
const entries = R.compose(
|
||||
ensureEntriesHaveEmptyLine(defaultCreditNoteEntry),
|
||||
updateItemsEntriesTotal,
|
||||
)(initialEntries);
|
||||
|
||||
return {
|
||||
...transformToForm(creditNote, defaultCreditNote),
|
||||
entries,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformes credit note entries to submit request.
|
||||
*/
|
||||
export const transformEntriesToSubmit = (entries) => {
|
||||
const transformCreditNoteEntry = R.compose(
|
||||
R.omit(['amount']),
|
||||
R.curry(transformToForm)(R.__, defaultCreditNoteEntry),
|
||||
);
|
||||
return R.compose(
|
||||
orderingLinesIndexes,
|
||||
R.map(transformCreditNoteEntry),
|
||||
)(entries);
|
||||
};
|
||||
|
||||
/**
|
||||
* Filters the givne non-zero entries.
|
||||
*/
|
||||
export const filterNonZeroEntries = (entries) => {
|
||||
return entries.filter((item) => item.item_id && item.quantity);
|
||||
};
|
||||
|
||||
/**
|
||||
* Transformes form values to request body.
|
||||
*/
|
||||
export const transformFormValuesToRequest = (values) => {
|
||||
const entries = filterNonZeroEntries(values.entries);
|
||||
|
||||
return {
|
||||
...values,
|
||||
entries: transformEntriesToSubmit(entries),
|
||||
open: false,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines customer name field when should update.
|
||||
*/
|
||||
export const customerNameFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.customers !== oldProps.customers ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines invoice entries field when should update.
|
||||
*/
|
||||
export const entriesFieldShouldUpdate = (newProps, oldProps) => {
|
||||
return (
|
||||
newProps.items !== oldProps.items ||
|
||||
defaultFastFieldShouldUpdate(newProps, oldProps)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Syncs invoice no. settings with form.
|
||||
*/
|
||||
export const useObserveCreditNoSettings = (prefix, nextNumber) => {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
|
||||
React.useEffect(() => {
|
||||
const creditNo = transactionNumber(prefix, nextNumber);
|
||||
setFieldValue('credit_note_number', creditNo);
|
||||
}, [setFieldValue, prefix, nextNumber]);
|
||||
};
|
||||
|
||||
export const useSetPrimaryBranchToForm = () => {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
const { branches, isBranchesSuccess } = useCreditNoteFormContext();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isBranchesSuccess) {
|
||||
const primaryBranch = branches.find((b) => b.primary) || first(branches);
|
||||
|
||||
if (primaryBranch) {
|
||||
setFieldValue('branch_id', primaryBranch.id);
|
||||
}
|
||||
}
|
||||
}, [isBranchesSuccess, setFieldValue, branches]);
|
||||
};
|
||||
|
||||
export const useSetPrimaryWarehouseToForm = () => {
|
||||
const { setFieldValue } = useFormikContext();
|
||||
const { warehouses, isWarehousesSuccess } = useCreditNoteFormContext();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isWarehousesSuccess) {
|
||||
const primaryWarehouse =
|
||||
warehouses.find((b) => b.primary) || first(warehouses);
|
||||
|
||||
if (primaryWarehouse) {
|
||||
setFieldValue('warehouse_id', primaryWarehouse.id);
|
||||
}
|
||||
}
|
||||
}, [isWarehousesSuccess, setFieldValue, warehouses]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retreives the credit note totals.
|
||||
*/
|
||||
export const useCreditNoteTotals = () => {
|
||||
const {
|
||||
values: { entries, currency_code: currencyCode },
|
||||
} = useFormikContext();
|
||||
|
||||
// Retrieves the invoice entries total.
|
||||
const total = React.useMemo(() => getEntriesTotal(entries), [entries]);
|
||||
|
||||
// Retrieves the formatted total money.
|
||||
const formattedTotal = React.useMemo(
|
||||
() => formattedAmount(total, currencyCode),
|
||||
[total, currencyCode],
|
||||
);
|
||||
// Retrieves the formatted subtotal.
|
||||
const formattedSubtotal = React.useMemo(
|
||||
() => formattedAmount(total, currencyCode, { money: false }),
|
||||
[total, currencyCode],
|
||||
);
|
||||
|
||||
return {
|
||||
total,
|
||||
formattedTotal,
|
||||
formattedSubtotal,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Detarmines whether the receipt has foreign customer.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const useCreditNoteIsForeignCustomer = () => {
|
||||
const { values } = useFormikContext();
|
||||
const currentOrganization = useCurrentOrganization();
|
||||
|
||||
const isForeignCustomer = React.useMemo(
|
||||
() => values.currency_code !== currentOrganization.base_currency,
|
||||
[values.currency_code, currentOrganization.base_currency],
|
||||
);
|
||||
return isForeignCustomer;
|
||||
};
|
||||
@@ -0,0 +1,118 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import { MenuItem, Intent } from '@blueprintjs/core';
|
||||
|
||||
import { Icon, Choose, T, TextStatus } from '@/components';
|
||||
|
||||
import { RESOURCES_TYPES } from '@/constants/resourcesTypes';
|
||||
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
|
||||
import { AbilitySubject, CreditNoteAction } from '@/constants/abilityOption';
|
||||
import { DRAWERS } from '@/constants/drawers';
|
||||
|
||||
/**
|
||||
* Credit note universal search item select action.
|
||||
*/
|
||||
function CreditNoteUniversalSearchSelectComponent({
|
||||
// #ownProps
|
||||
resourceType,
|
||||
resourceId,
|
||||
onAction,
|
||||
|
||||
// #withDrawerActions
|
||||
openDrawer,
|
||||
}) {
|
||||
if (resourceType === RESOURCES_TYPES.CREDIT_NOTE) {
|
||||
openDrawer(DRAWERS.CREDIT_NOTE_DETAIL_DRAWER, { creditNoteId: resourceId });
|
||||
onAction && onAction();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const CreditNoteUniversalSearchSelect = withDrawerActions(
|
||||
CreditNoteUniversalSearchSelectComponent,
|
||||
);
|
||||
|
||||
/**
|
||||
* Status accessor.
|
||||
*/
|
||||
function CreditNoteUniversalSearchStatus({ receipt }) {
|
||||
return (
|
||||
<Choose>
|
||||
<Choose.When condition={receipt.is_closed}>
|
||||
<TextStatus intent={Intent.SUCCESS}>
|
||||
<T id={'closed'} />
|
||||
</TextStatus>
|
||||
</Choose.When>
|
||||
|
||||
<Choose.When condition={receipt.is_open}>
|
||||
<TextStatus intent={Intent.WARNING}>
|
||||
<T id={'open'} />
|
||||
</TextStatus>
|
||||
</Choose.When>
|
||||
|
||||
<Choose.Otherwise>
|
||||
<TextStatus intent={Intent.NONE}>
|
||||
<T id={'draft'} />
|
||||
</TextStatus>
|
||||
</Choose.Otherwise>
|
||||
</Choose>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Credit note universal search item.
|
||||
*/
|
||||
export function CreditNoteUniversalSearchItem(
|
||||
item,
|
||||
{ handleClick, modifiers, query },
|
||||
) {
|
||||
return (
|
||||
<MenuItem
|
||||
active={modifiers.active}
|
||||
text={
|
||||
<div>
|
||||
<div>{item.text}</div>
|
||||
<span class="bp3-text-muted">
|
||||
{item.reference.credit_note_number}{' '}
|
||||
<Icon icon={'caret-right-16'} iconSize={16} />
|
||||
{item.reference.formatted_credit_note_date}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
label={
|
||||
<>
|
||||
<div class="amount">${item.reference.amount}</div>
|
||||
<CreditNoteUniversalSearchStatus receipt={item.reference} />
|
||||
</>
|
||||
}
|
||||
onClick={handleClick}
|
||||
className={'universal-search__item--receipt'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformes receipt resource item to search item.
|
||||
*/
|
||||
const transformReceiptsToSearch = (creditNote) => ({
|
||||
id: creditNote.id,
|
||||
text: creditNote.customer.display_name,
|
||||
label: creditNote.formatted_amount,
|
||||
reference: creditNote,
|
||||
});
|
||||
|
||||
/**
|
||||
* Credit note universal search bind configuration.
|
||||
*/
|
||||
export const universalSearchCreditNoteBind = () => ({
|
||||
resourceType: RESOURCES_TYPES.CREDIT_NOTE,
|
||||
optionItemLabel: intl.get('credit_note.label'),
|
||||
selectItemAction: CreditNoteUniversalSearchSelect,
|
||||
itemRenderer: CreditNoteUniversalSearchItem,
|
||||
itemSelect: transformReceiptsToSearch,
|
||||
permission: {
|
||||
ability: CreditNoteAction.View,
|
||||
subject: AbilitySubject.CreditNote,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
|
||||
const CreditNoteDeleteAlert = React.lazy(
|
||||
() => import('@/containers/Alerts/CreditNotes/CreditNoteDeleteAlert'),
|
||||
);
|
||||
|
||||
const RefundCreditNoteDeleteAlert = React.lazy(
|
||||
() => import('@/containers/Alerts/CreditNotes/RefundCreditNoteDeleteAlert'),
|
||||
);
|
||||
|
||||
const OpenCreditNoteAlert = React.lazy(
|
||||
() => import('@/containers/Alerts/CreditNotes/CreditNoteOpenedAlert'),
|
||||
);
|
||||
|
||||
const ReconcileCreditDeleteAlert = React.lazy(
|
||||
() =>
|
||||
import('@/containers/Alerts/CreditNotes/ReconcileCreditNoteDeleteAlert'),
|
||||
);
|
||||
|
||||
/**
|
||||
* Credit notes alerts.
|
||||
*/
|
||||
export default [
|
||||
{
|
||||
name: 'credit-note-delete',
|
||||
component: CreditNoteDeleteAlert,
|
||||
},
|
||||
{
|
||||
name: 'credit-note-open',
|
||||
component: OpenCreditNoteAlert,
|
||||
},
|
||||
{
|
||||
name: 'refund-credit-delete',
|
||||
component: RefundCreditNoteDeleteAlert,
|
||||
},
|
||||
{
|
||||
name: 'reconcile-credit-delete',
|
||||
component: ReconcileCreditDeleteAlert,
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,147 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import {
|
||||
Button,
|
||||
Classes,
|
||||
NavbarDivider,
|
||||
NavbarGroup,
|
||||
Alignment,
|
||||
} from '@blueprintjs/core';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import {
|
||||
Icon,
|
||||
Can,
|
||||
FormattedMessage as T,
|
||||
DashboardActionViewsList,
|
||||
AdvancedFilterPopover,
|
||||
DashboardFilterButton,
|
||||
DashboardRowsHeightButton,
|
||||
DashboardActionsBar,
|
||||
} from '@/components';
|
||||
|
||||
import { useCreditNoteListContext } from './CreditNotesListProvider';
|
||||
import { CreditNoteAction, AbilitySubject } from '@/constants/abilityOption';
|
||||
import withCreditNotes from './withCreditNotes';
|
||||
import withCreditNotesActions from './withCreditNotesActions';
|
||||
import withSettings from '@/containers/Settings/withSettings';
|
||||
import withSettingsActions from '@/containers/Settings/withSettingsActions';
|
||||
|
||||
import { compose } from '@/utils';
|
||||
|
||||
/**
|
||||
* Credit note table actions bar.
|
||||
*/
|
||||
function CreditNotesActionsBar({
|
||||
// #withCreditNotes
|
||||
creditNoteFilterRoles,
|
||||
|
||||
// #withCreditNotesActions
|
||||
setCreditNotesTableState,
|
||||
|
||||
// #withSettings
|
||||
creditNoteTableSize,
|
||||
|
||||
// #withSettingsActions
|
||||
addSetting,
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// credit note list context.
|
||||
const { CreditNotesView, fields, refresh } = useCreditNoteListContext();
|
||||
|
||||
// Handle view tab change.
|
||||
const handleTabChange = (view) => {
|
||||
setCreditNotesTableState({ viewSlug: view ? view.slug : null });
|
||||
};
|
||||
|
||||
// Handle click a new Credit.
|
||||
const handleClickNewCreateNote = () => {
|
||||
history.push('/credit-notes/new');
|
||||
};
|
||||
|
||||
// Handle click a refresh credit note.
|
||||
const handleRefreshBtnClick = () => {
|
||||
refresh();
|
||||
};
|
||||
|
||||
// Handle table row size change.
|
||||
const handleTableRowSizeChange = (size) => {
|
||||
addSetting('creditNote', 'tableSize', size);
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardActionsBar>
|
||||
<NavbarGroup>
|
||||
<DashboardActionViewsList
|
||||
allMenuItem={true}
|
||||
resourceName={'credit_notes'}
|
||||
views={CreditNotesView}
|
||||
onChange={handleTabChange}
|
||||
/>
|
||||
<NavbarDivider />
|
||||
<Can I={CreditNoteAction.Create} a={AbilitySubject.CreditNote}>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'plus'} />}
|
||||
text={<T id={'credit_note.label.new_credit_note'} />}
|
||||
onClick={handleClickNewCreateNote}
|
||||
/>
|
||||
</Can>
|
||||
<AdvancedFilterPopover
|
||||
advancedFilterProps={{
|
||||
conditions: creditNoteFilterRoles,
|
||||
defaultFieldKey: 'created_at',
|
||||
fields: fields,
|
||||
onFilterChange: (filterConditions) => {
|
||||
setCreditNotesTableState({ filterRoles: filterConditions });
|
||||
},
|
||||
}}
|
||||
>
|
||||
<DashboardFilterButton
|
||||
conditionsCount={creditNoteFilterRoles.length}
|
||||
/>
|
||||
</AdvancedFilterPopover>
|
||||
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'print-16'} iconSize={'16'} />}
|
||||
text={<T id={'print'} />}
|
||||
/>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'file-import-16'} />}
|
||||
text={<T id={'import'} />}
|
||||
/>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon={'file-export-16'} iconSize={'16'} />}
|
||||
text={<T id={'export'} />}
|
||||
/>
|
||||
<NavbarDivider />
|
||||
<DashboardRowsHeightButton
|
||||
initialValue={creditNoteTableSize}
|
||||
onChange={handleTableRowSizeChange}
|
||||
/>
|
||||
<NavbarDivider />
|
||||
</NavbarGroup>
|
||||
<NavbarGroup align={Alignment.RIGHT}>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon="refresh-16" iconSize={14} />}
|
||||
onClick={handleRefreshBtnClick}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
</DashboardActionsBar>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withCreditNotesActions,
|
||||
withSettingsActions,
|
||||
withCreditNotes(({ creditNoteTableState }) => ({
|
||||
creditNoteFilterRoles: creditNoteTableState.filterRoles,
|
||||
})),
|
||||
withSettings(({ creditNoteSettings }) => ({
|
||||
creditNoteTableSize: creditNoteSettings?.tableSize,
|
||||
})),
|
||||
)(CreditNotesActionsBar);
|
||||
@@ -0,0 +1,161 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
import { TABLES } from '@/constants/tables';
|
||||
import {
|
||||
DataTable,
|
||||
DashboardContentTable,
|
||||
TableSkeletonRows,
|
||||
TableSkeletonHeader,
|
||||
} from '@/components';
|
||||
import { useMemorizedColumnsWidths } from '@/hooks';
|
||||
|
||||
import CreditNoteEmptyStatus from './CreditNotesEmptyStatus';
|
||||
|
||||
import withDashboardActions from '@/containers/Dashboard/withDashboardActions';
|
||||
import withCreditNotesActions from './withCreditNotesActions';
|
||||
import withAlertsActions from '@/containers/Alert/withAlertActions';
|
||||
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
|
||||
import withDialogActions from '@/containers/Dialog/withDialogActions';
|
||||
import withSettings from '@/containers/Settings/withSettings';
|
||||
|
||||
import { useCreditNoteTableColumns, ActionsMenu } from './components';
|
||||
import { useCreditNoteListContext } from './CreditNotesListProvider';
|
||||
|
||||
import { compose } from '@/utils';
|
||||
|
||||
/**
|
||||
* Credit note data table.
|
||||
*/
|
||||
function CreditNotesDataTable({
|
||||
// #withCreditNotesActions
|
||||
setCreditNotesTableState,
|
||||
|
||||
// #withAlertsActions
|
||||
openAlert,
|
||||
|
||||
// #withDrawerActions
|
||||
openDrawer,
|
||||
|
||||
// #withDialogAction
|
||||
openDialog,
|
||||
|
||||
// #withSettings
|
||||
creditNoteTableSize,
|
||||
}) {
|
||||
const history = useHistory();
|
||||
|
||||
// Credit note list context.
|
||||
const {
|
||||
creditNotes,
|
||||
pagination,
|
||||
isEmptyStatus,
|
||||
isCreditNotesFetching,
|
||||
isCreditNotesLoading,
|
||||
} = useCreditNoteListContext();
|
||||
|
||||
// Credit note table columns.
|
||||
const columns = useCreditNoteTableColumns();
|
||||
|
||||
// Local storage memorizing columns widths.
|
||||
const [initialColumnsWidths, , handleColumnResizing] =
|
||||
useMemorizedColumnsWidths(TABLES.CREDIT_NOTES);
|
||||
|
||||
// Handles fetch data once the table state change.
|
||||
const handleDataTableFetchData = React.useCallback(
|
||||
({ pageSize, pageIndex, sortBy }) => {
|
||||
setCreditNotesTableState({
|
||||
pageSize,
|
||||
pageIndex,
|
||||
sortBy,
|
||||
});
|
||||
},
|
||||
[setCreditNotesTableState],
|
||||
);
|
||||
|
||||
// Display create note empty status instead of the table.
|
||||
if (isEmptyStatus) {
|
||||
return <CreditNoteEmptyStatus />;
|
||||
}
|
||||
|
||||
const handleViewDetailCreditNote = ({ id }) => {
|
||||
openDrawer('credit-note-detail-drawer', { creditNoteId: id });
|
||||
};
|
||||
|
||||
// Handle delete credit note.
|
||||
const handleDeleteCreditNote = ({ id }) => {
|
||||
openAlert('credit-note-delete', { creditNoteId: id });
|
||||
};
|
||||
|
||||
// Handle edit credit note.
|
||||
const hanldeEditCreditNote = (creditNote) => {
|
||||
history.push(`/credit-notes/${creditNote.id}/edit`);
|
||||
};
|
||||
|
||||
// Handle cell click.
|
||||
const handleCellClick = (cell, event) => {
|
||||
openDrawer('credit-note-detail-drawer', {
|
||||
creditNoteId: cell.row.original.id,
|
||||
});
|
||||
};
|
||||
|
||||
const handleRefundCreditNote = ({ id }) => {
|
||||
openDialog('refund-credit-note', { creditNoteId: id });
|
||||
};
|
||||
|
||||
// Handle cancel/confirm crdit note open.
|
||||
const handleOpenCreditNote = ({ id }) => {
|
||||
openAlert('credit-note-open', { creditNoteId: id });
|
||||
};
|
||||
|
||||
// Handle reconcile credit note.
|
||||
const handleReconcileCreditNote = ({ id }) => {
|
||||
openDialog('reconcile-credit-note', { creditNoteId: id });
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardContentTable>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={creditNotes}
|
||||
loading={isCreditNotesLoading}
|
||||
headerLoading={isCreditNotesLoading}
|
||||
progressBarLoading={isCreditNotesFetching}
|
||||
onFetchData={handleDataTableFetchData}
|
||||
manualSortBy={true}
|
||||
selectionColumn={true}
|
||||
noInitialFetch={true}
|
||||
sticky={true}
|
||||
pagination={true}
|
||||
pagesCount={pagination.pagesCount}
|
||||
TableLoadingRenderer={TableSkeletonRows}
|
||||
TableHeaderSkeletonRenderer={TableSkeletonHeader}
|
||||
ContextMenu={ActionsMenu}
|
||||
onCellClick={handleCellClick}
|
||||
initialColumnsWidths={initialColumnsWidths}
|
||||
onColumnResizing={handleColumnResizing}
|
||||
size={creditNoteTableSize}
|
||||
payload={{
|
||||
onViewDetails: handleViewDetailCreditNote,
|
||||
onDelete: handleDeleteCreditNote,
|
||||
onEdit: hanldeEditCreditNote,
|
||||
onRefund: handleRefundCreditNote,
|
||||
onOpen: handleOpenCreditNote,
|
||||
onReconcile: handleReconcileCreditNote,
|
||||
}}
|
||||
/>
|
||||
</DashboardContentTable>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withDashboardActions,
|
||||
withCreditNotesActions,
|
||||
withDrawerActions,
|
||||
withAlertsActions,
|
||||
withDialogActions,
|
||||
withSettings(({ creditNoteSettings }) => ({
|
||||
creditNoteTableSize: creditNoteSettings?.tableSize,
|
||||
})),
|
||||
)(CreditNotesDataTable);
|
||||
@@ -0,0 +1,37 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { Button, Intent } from '@blueprintjs/core';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { EmptyStatus, Can, FormattedMessage as T } from '@/components';
|
||||
import { CreditNoteAction, AbilitySubject } from '@/constants/abilityOption';
|
||||
|
||||
export default function CreditNotesEmptyStatus() {
|
||||
const history = useHistory();
|
||||
return (
|
||||
<EmptyStatus
|
||||
title={<T id={'credit_note.empty_status.title'} />}
|
||||
description={
|
||||
<p>
|
||||
<T id={'credit_note.empty_status.description'} />
|
||||
</p>
|
||||
}
|
||||
action={
|
||||
<>
|
||||
<Can I={CreditNoteAction.Create} a={AbilitySubject.CreditNote}>
|
||||
<Button
|
||||
intent={Intent.PRIMARY}
|
||||
large={true}
|
||||
onClick={() => history.push('/credit-notes/new')}
|
||||
>
|
||||
<T id={'credit_note.label.new_credit_note'} />
|
||||
</Button>
|
||||
|
||||
<Button intent={Intent.NONE} large={true}>
|
||||
<T id={'learn_more'} />
|
||||
</Button>
|
||||
</Can>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
|
||||
import '@/style/pages/CreditNote/List.scss';
|
||||
|
||||
import { DashboardPageContent } from '@/components';
|
||||
import CreditNotesActionsBar from './CreditNotesActionsBar';
|
||||
import CreditNotesViewTabs from './CreditNotesViewTabs';
|
||||
import CreditNotesDataTable from './CreditNotesDataTable';
|
||||
|
||||
import withCreditNotes from './withCreditNotes';
|
||||
import withCreditNotesActions from './withCreditNotesActions';
|
||||
|
||||
import { CreditNotesListProvider } from './CreditNotesListProvider';
|
||||
import { transformTableStateToQuery, compose } from '@/utils';
|
||||
|
||||
function CreditNotesList({
|
||||
// #withCreditNotes
|
||||
creditNoteTableState,
|
||||
creditNoteTableStateChanged,
|
||||
|
||||
// #withCreditNotesActions
|
||||
resetCreditNotesTableState,
|
||||
}) {
|
||||
// Resets the credit note table state once the page unmount.
|
||||
React.useEffect(
|
||||
() => () => {
|
||||
resetCreditNotesTableState();
|
||||
},
|
||||
[resetCreditNotesTableState],
|
||||
);
|
||||
|
||||
return (
|
||||
<CreditNotesListProvider
|
||||
query={transformTableStateToQuery(creditNoteTableState)}
|
||||
tableStateChanged={creditNoteTableStateChanged}
|
||||
>
|
||||
<CreditNotesActionsBar />
|
||||
<DashboardPageContent>
|
||||
<CreditNotesViewTabs />
|
||||
<CreditNotesDataTable />
|
||||
</DashboardPageContent>
|
||||
</CreditNotesListProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withCreditNotesActions,
|
||||
withCreditNotes(({ creditNoteTableState, creditNoteTableStateChanged }) => ({
|
||||
creditNoteTableState,
|
||||
creditNoteTableStateChanged,
|
||||
})),
|
||||
)(CreditNotesList);
|
||||
@@ -0,0 +1,77 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { isEmpty } from 'lodash';
|
||||
|
||||
import { DashboardInsider } from '@/components/Dashboard';
|
||||
import {
|
||||
useResourceViews,
|
||||
useResourceMeta,
|
||||
useCreditNotes,
|
||||
useRefreshCreditNotes,
|
||||
} from '@/hooks/query';
|
||||
|
||||
import { getFieldsFromResourceMeta } from '@/utils';
|
||||
|
||||
const CreditNoteListContext = React.createContext();
|
||||
|
||||
/**
|
||||
* Credit note data provider.
|
||||
*/
|
||||
function CreditNotesListProvider({ query, tableStateChanged, ...props }) {
|
||||
// Credit notes refresh action.
|
||||
const { refresh } = useRefreshCreditNotes();
|
||||
|
||||
// Fetch create notes resource views and fields.
|
||||
const { data: CreditNotesView, isLoading: isViewsLoading } =
|
||||
useResourceViews('credit_notes');
|
||||
|
||||
// Fetch the accounts resource fields.
|
||||
const {
|
||||
data: resourceMeta,
|
||||
isLoading: isResourceLoading,
|
||||
isFetching: isResourceFetching,
|
||||
} = useResourceMeta('credit_notes');
|
||||
|
||||
// Fetch credit note list.
|
||||
const {
|
||||
data: { creditNotes, pagination, filterMeta },
|
||||
isFetching: isCreditNotesFetching,
|
||||
isLoading: isCreditNotesLoading,
|
||||
} = useCreditNotes(query, { keepPreviousData: true });
|
||||
|
||||
// Detarmines the datatable empty status.S
|
||||
const isEmptyStatus =
|
||||
isEmpty(creditNotes) && !isCreditNotesLoading && !tableStateChanged;
|
||||
|
||||
// Provider payload.
|
||||
const provider = {
|
||||
creditNotes,
|
||||
pagination,
|
||||
|
||||
CreditNotesView,
|
||||
refresh,
|
||||
|
||||
resourceMeta,
|
||||
fields: getFieldsFromResourceMeta(resourceMeta.fields),
|
||||
isResourceLoading,
|
||||
isResourceFetching,
|
||||
|
||||
isCreditNotesFetching,
|
||||
isCreditNotesLoading,
|
||||
isViewsLoading,
|
||||
isEmptyStatus,
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardInsider
|
||||
loading={isViewsLoading || isResourceLoading}
|
||||
name={'credit-notes-list'}
|
||||
>
|
||||
<CreditNoteListContext.Provider value={provider} {...props} />
|
||||
</DashboardInsider>
|
||||
);
|
||||
}
|
||||
|
||||
const useCreditNoteListContext = () => React.useContext(CreditNoteListContext);
|
||||
|
||||
export { CreditNotesListProvider, useCreditNoteListContext };
|
||||
@@ -0,0 +1,51 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { Alignment, Navbar, NavbarGroup } from '@blueprintjs/core';
|
||||
|
||||
import { DashboardViewsTabs } from '@/components';
|
||||
import { compose, transfromViewsToTabs } from '@/utils';
|
||||
import { useCreditNoteListContext } from './CreditNotesListProvider';
|
||||
|
||||
import withCreditNotes from './withCreditNotes';
|
||||
import withCreditNotesActions from './withCreditNotesActions';
|
||||
|
||||
/**
|
||||
* Credit Note views tabs.
|
||||
*/
|
||||
function CreditNotesViewTabs({
|
||||
// #withCreditNotes
|
||||
creditNoteCurrentView,
|
||||
|
||||
// #withCreditNotesActions
|
||||
setCreditNotesTableState,
|
||||
}) {
|
||||
// Credit note list context.
|
||||
const { CreditNotesView } = useCreditNoteListContext();
|
||||
|
||||
const tabs = transfromViewsToTabs(CreditNotesView);
|
||||
|
||||
// Handle tab change.
|
||||
const handleTabsChange = (viewSlug) => {
|
||||
setCreditNotesTableState({ viewSlug });
|
||||
};
|
||||
|
||||
return (
|
||||
<Navbar className={'navbar--dashboard-views'}>
|
||||
<NavbarGroup align={Alignment.LEFT}>
|
||||
<DashboardViewsTabs
|
||||
currentViewSlug={creditNoteCurrentView}
|
||||
resourceName={'credit_notes'}
|
||||
tabs={tabs}
|
||||
onChange={handleTabsChange}
|
||||
/>
|
||||
</NavbarGroup>
|
||||
</Navbar>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(
|
||||
withCreditNotesActions,
|
||||
withCreditNotes(({ creditNoteTableState }) => ({
|
||||
creditNoteCurrentView: creditNoteTableState.viewSlug,
|
||||
})),
|
||||
)(CreditNotesViewTabs);
|
||||
@@ -0,0 +1,180 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import clsx from 'classnames';
|
||||
import { Intent, Tag, Menu, MenuItem, MenuDivider } from '@blueprintjs/core';
|
||||
import { CLASSES } from '@/constants/classes';
|
||||
import {
|
||||
FormatDateCell,
|
||||
FormattedMessage as T,
|
||||
Choose,
|
||||
If,
|
||||
Icon,
|
||||
Can,
|
||||
} from '@/components';
|
||||
import { safeCallback } from '@/utils';
|
||||
import { CreditNoteAction, AbilitySubject } from '@/constants/abilityOption';
|
||||
|
||||
export function ActionsMenu({
|
||||
payload: { onEdit, onDelete, onRefund, onOpen, onReconcile, onViewDetails },
|
||||
row: { original },
|
||||
}) {
|
||||
return (
|
||||
<Menu>
|
||||
<MenuItem
|
||||
icon={<Icon icon="reader-18" />}
|
||||
text={intl.get('view_details')}
|
||||
onClick={safeCallback(onViewDetails, original)}
|
||||
/>
|
||||
<Can I={CreditNoteAction.Edit} a={AbilitySubject.CreditNote}>
|
||||
<MenuDivider />
|
||||
<MenuItem
|
||||
icon={<Icon icon="pen-18" />}
|
||||
text={intl.get('credit_note.action.edit_credit_note')}
|
||||
onClick={safeCallback(onEdit, original)}
|
||||
/>
|
||||
<If condition={original.is_draft}>
|
||||
<MenuItem
|
||||
icon={<Icon icon={'check'} iconSize={18} />}
|
||||
text={intl.get('credit_note.action.make_as_open')}
|
||||
onClick={safeCallback(onOpen, original)}
|
||||
/>
|
||||
</If>
|
||||
</Can>
|
||||
|
||||
<Can I={CreditNoteAction.Refund} a={AbilitySubject.CreditNote}>
|
||||
<If condition={!original.is_closed && original.is_published}>
|
||||
<MenuItem
|
||||
icon={<Icon icon="quick-payment-16" />}
|
||||
text={intl.get('credit_note.action.refund_credit_note')}
|
||||
onClick={safeCallback(onRefund, original)}
|
||||
/>
|
||||
</If>
|
||||
</Can>
|
||||
<Can I={CreditNoteAction.Edit} a={AbilitySubject.CreditNote}>
|
||||
<If condition={!original.is_closed && original.is_published}>
|
||||
<MenuItem
|
||||
text={intl.get('credit_note.action.reconcile_with_invoices')}
|
||||
icon={<Icon icon="receipt-24" iconSize={16} />}
|
||||
onClick={safeCallback(onReconcile, original)}
|
||||
/>
|
||||
</If>
|
||||
</Can>
|
||||
<Can I={CreditNoteAction.Delete} a={AbilitySubject.CreditNote}>
|
||||
<MenuDivider />
|
||||
<MenuItem
|
||||
text={intl.get('credit_note.action.delete_credit_note')}
|
||||
intent={Intent.DANGER}
|
||||
onClick={safeCallback(onDelete, original)}
|
||||
icon={<Icon icon="trash-16" iconSize={16} />}
|
||||
/>
|
||||
</Can>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Status accessor.
|
||||
*/
|
||||
export function StatusAccessor(creditNote) {
|
||||
return (
|
||||
<div>
|
||||
<Choose>
|
||||
<Choose.When condition={creditNote.is_open}>
|
||||
<Tag intent={Intent.WARNING} minimal={true} round={true}>
|
||||
<T id={'open'} />
|
||||
</Tag>
|
||||
</Choose.When>
|
||||
|
||||
<Choose.When condition={creditNote.is_closed}>
|
||||
<Tag intent={Intent.SUCCESS} minimal={true} round={true}>
|
||||
<T id={'closed'} />
|
||||
</Tag>
|
||||
</Choose.When>
|
||||
|
||||
<Choose.When condition={creditNote.is_draft}>
|
||||
<Tag intent={Intent.NONE} minimal={true} round={true}>
|
||||
<T id={'draft'} />
|
||||
</Tag>
|
||||
</Choose.When>
|
||||
</Choose>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve credit note table columns.
|
||||
*/
|
||||
export function useCreditNoteTableColumns() {
|
||||
return React.useMemo(
|
||||
() => [
|
||||
{
|
||||
id: 'credit_date',
|
||||
Header: intl.get('credit_note.column.credit_date'),
|
||||
accessor: 'formatted_credit_note_date',
|
||||
Cell: FormatDateCell,
|
||||
width: 110,
|
||||
className: 'credit_date',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'customer',
|
||||
Header: intl.get('customer_name'),
|
||||
accessor: 'customer.display_name',
|
||||
width: 180,
|
||||
className: 'customer',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'credit_number',
|
||||
Header: intl.get('credit_note.column.credit_note_no'),
|
||||
accessor: 'credit_note_number',
|
||||
width: 100,
|
||||
className: 'credit_number',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
id: 'amount',
|
||||
Header: intl.get('amount'),
|
||||
accessor: 'formatted_amount',
|
||||
width: 120,
|
||||
align: 'right',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
className: clsx(CLASSES.FONT_BOLD),
|
||||
},
|
||||
{
|
||||
id: 'balance',
|
||||
Header: intl.get('balance'),
|
||||
accessor: 'formatted_credits_remaining',
|
||||
width: 120,
|
||||
align: 'right',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
disableSortBy: true,
|
||||
className: clsx(CLASSES.FONT_BOLD),
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
Header: intl.get('status'),
|
||||
accessor: StatusAccessor,
|
||||
width: 160, // 160
|
||||
className: 'status',
|
||||
clickable: true,
|
||||
},
|
||||
{
|
||||
id: 'reference_no',
|
||||
Header: intl.get('reference_no'),
|
||||
accessor: 'reference_no', // or note
|
||||
width: 90,
|
||||
className: 'reference_no',
|
||||
clickable: true,
|
||||
textOverview: true,
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import { AppToaster } from '@/components';
|
||||
|
||||
export const handleDeleteErrors = (errors) => {
|
||||
if (
|
||||
errors.find((error) => error.type === 'CREDIT_NOTE_HAS_APPLIED_INVOICES')
|
||||
) {
|
||||
AppToaster.show({
|
||||
message: intl.get(
|
||||
'credit_note.error.you_couldn_t_delete_credit_note_that_has_associated_invoice',
|
||||
),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
}
|
||||
if (
|
||||
errors.find(
|
||||
(error) => error.type === 'CREDIT_NOTE_HAS_REFUNDS_TRANSACTIONS',
|
||||
)
|
||||
) {
|
||||
AppToaster.show({
|
||||
message: intl.get(
|
||||
'credit_note.error.you_couldn_t_delete_credit_note_that_has_associated_refund',
|
||||
),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
// @ts-nocheck
|
||||
import { connect } from 'react-redux';
|
||||
import {
|
||||
getCreditNotesTableStateFactory,
|
||||
isCreditNotesTableStateChangedFactory,
|
||||
} from '@/store/CreditNote/creditNote.selector';
|
||||
|
||||
export default (mapState) => {
|
||||
const getCreditNoteTableState = getCreditNotesTableStateFactory();
|
||||
const isCreditNoteTableChanged = isCreditNotesTableStateChangedFactory();
|
||||
|
||||
const mapStateToProps = (state, props) => {
|
||||
const mapped = {
|
||||
creditNoteTableState: getCreditNoteTableState(state, props),
|
||||
creditNoteTableStateChanged: isCreditNoteTableChanged(state, props),
|
||||
};
|
||||
return mapState ? mapState(mapped, state, props) : mapped;
|
||||
};
|
||||
return connect(mapStateToProps);
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
// @ts-nocheck
|
||||
import { connect } from 'react-redux';
|
||||
import {
|
||||
setCreditNoteTableState,
|
||||
resetCreditNoteTableState,
|
||||
} from '@/store/CreditNote/creditNote.actions';
|
||||
|
||||
const mapDipatchToProps = (dispatch) => ({
|
||||
setCreditNotesTableState: (queries) =>
|
||||
dispatch(setCreditNoteTableState(queries)),
|
||||
resetCreditNotesTableState: () => dispatch(resetCreditNoteTableState()),
|
||||
});
|
||||
|
||||
export default connect(null, mapDipatchToProps);
|
||||
Reference in New Issue
Block a user