feat: Credit note.

This commit is contained in:
elforjani13
2021-11-29 16:14:22 +02:00
parent 346696f673
commit 0a9798e7a7
37 changed files with 1564 additions and 2 deletions

View File

@@ -0,0 +1,109 @@
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 'common/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 } = useCreditNoteFormContext();
// Handle cancel button click.
const handleCancelBtnClick = (event) => {
history.goBack();
};
const handleClearBtnClick = (event) => {
resetForm();
};
return (
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
{/* ----------- Save And Deliver ----------- */}
<ButtonGroup>
<Button
disabled={isSubmitting}
loading={isSubmitting}
intent={Intent.PRIMARY}
text={<T id={'save_and_deliver'} />}
/>
<Popover
content={
<Menu>
<MenuItem text={<T id={'deliver_and_new'} />} />
<MenuItem text={<T id={'deliver_continue_editing'} />} />
</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'}
text={<T id={'save_as_draft'} />}
/>
<Popover
content={
<Menu>
<MenuItem text={<T id={'save_and_new'} />} />
<MenuItem text={<T id={'save_continue_editing'} />} />
</Menu>
}
minimal={true}
interactionKind={PopoverInteractionKind.CLICK}
position={Position.BOTTOM_LEFT}
>
<Button
disabled={isSubmitting}
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
/>
</Popover>
</ButtonGroup>
{/* ----------- Save and New ----------- */}
{/* ----------- Clear & Reset----------- */}
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={handleClearBtnClick}
// text={ ? <T id={'reset'} /> : <T id={'clear'} />}
/>
{/* ----------- Cancel ----------- */}
<Button
className={'ml1'}
onClick={handleCancelBtnClick}
text={<T id={'cancel'} />}
/>
</div>
);
}

View File

@@ -0,0 +1,118 @@
import React from 'react';
import { useHistory } from 'react-router-dom';
import { Formik, Form } from 'formik';
import { Intent } from '@blueprintjs/core';
import intl from 'react-intl-universal';
import { sumBy, omit, isEmpty } from 'lodash';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import {
getCreateCreditNoteFormSchema,
getEditCreditNoteFormSchema,
} from './CreditNoteForm.schema';
import CreditNoteFormHeader from './CreditNoteFormHeader';
import CreditNoteItemsEntriesEditorField from './CreditNoteItemsEntriesEditorField';
import CreditNoteFormFooter from './CreditNoteFormFooter';
import CreditNoteFloatingActions from './CreditNoteFloatingActions';
import { AppToaster } from 'components';
import { compose, orderingLinesIndexes, transactionNumber } from 'utils';
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
import { transformToEditForm, defaultCreditNote } from './utils';
import withSettings from 'containers/Settings/withSettings';
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
/**
* Credit note form.
*/
function CreditNoteForm({
// #withSettings
// #withCurrentOrganization
organization: { base_currency },
}) {
const history = useHistory();
// Credit note form context.
const { invoice } = useCreditNoteFormContext();
// Initial values.
const initialValues = React.useMemo(
() => ({
...(!isEmpty(invoice)
? { ...transformToEditForm(invoice), currency_code: base_currency }
: {
...defaultCreditNote,
entries: orderingLinesIndexes(defaultCreditNote.entries),
currency_code: base_currency,
}),
}),
[],
);
// Handle form submit.
const handleSubmit = (values, { setSubmitting, setErrors, resetForm }) => {
setSubmitting(true);
const entries = values.entries.filter(
(item) => item.item_id && item.quantity,
);
const totalQuantity = sumBy(entries, (entry) => parseInt(entry.quantity));
// Throw danger toaster in case total quantity equals zero.
if (totalQuantity === 0) {
AppToaster.show({
message: intl.get('quantity_cannot_be_zero_or_empty'),
intent: Intent.DANGER,
});
setSubmitting(false);
return;
}
// Transformes the values of the form to request.
const form = {
// ...transformValueToRequest(values),
};
// Handle the request success.
const onSuccess = () => {};
// Handle the request error.
const onError = ({
response: {
data: { errors },
},
}) => {};
};
const CreateCreditNoteFormSchema = getCreateCreditNoteFormSchema();
const EditCreditNoteFormSchema = getEditCreditNoteFormSchema();
return (
<div
className={classNames(
CLASSES.PAGE_FORM,
CLASSES.PAGE_FORM_STRIP_STYLE,
CLASSES.PAGE_FORM_CREDIT_NOTE,
)}
>
<Formik
validationSchema={
true ? CreateCreditNoteFormSchema : EditCreditNoteFormSchema
}
initialValues={initialValues}
onSubmit={handleSubmit}
>
<Form>
<CreditNoteFormHeader />
<CreditNoteItemsEntriesEditorField />
<CreditNoteFormFooter />
<CreditNoteFloatingActions />
</Form>
</Formik>
</div>
);
}
export default compose(withCurrentOrganization())(CreditNoteForm);

View File

@@ -0,0 +1,51 @@
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import { DATATYPES_LENGTH } from 'common/dataTypes';
import { isBlank } from 'utils';
const getSchema = () => Yup.object().shape({
customer_id: Yup.string()
.label(intl.get('customer_name_'))
.required(),
invoice_date: Yup.date()
.required()
.label(intl.get('invoice_date_')),
invoice_no: Yup.string()
.max(DATATYPES_LENGTH.STRING)
.label(intl.get('invoice_no_')),
reference_no: Yup.string().min(1).max(DATATYPES_LENGTH.STRING),
delivered: Yup.boolean(),
invoice_message: Yup.string()
.trim()
.min(1)
.max(DATATYPES_LENGTH.TEXT)
.label(intl.get('note')),
terms_conditions: Yup.string()
.trim()
.min(1)
.max(DATATYPES_LENGTH.TEXT)
.label(intl.get('note')),
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 getCreateCreditNoteFormSchema = getSchema;
export const getEditCreditNoteFormSchema = getSchema;

View File

@@ -0,0 +1,51 @@
import React from 'react';
import { FastField } from 'formik';
import { FormGroup, TextArea } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import { CLASSES } from 'common/classes';
import { Row, Col, Postbox } from 'components';
import { inputIntent } from 'utils';
import classNames from 'classnames';
/**
* Credit note form footer.
*/
export default function CreditNoteFormFooter() {
return (
<div className={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<Postbox
title={<T id={'credit_note.label_credit_note_details'} />}
defaultOpen={false}
>
<Row>
<Col md={8}>
{/* --------- Customer notes --------- */}
<FastField name={'invoice_message'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'credit_note.label_customer_note'} />}
className={'form-group--customer_notes'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup>
)}
</FastField>
{/* --------- Terms and conditions --------- */}
<FastField name={'terms_conditions'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'terms_conditions'} />}
className={'form-group--terms_conditions'}
intent={inputIntent({ error, touched })}
>
<TextArea growVertically={true} {...field} />
</FormGroup>
)}
</FastField>
</Col>
</Row>
</Postbox>
</div>
);
}

View File

@@ -0,0 +1,42 @@
import React from 'react';
import { useFormikContext } from 'formik';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { CLASSES } from 'common/classes';
import CreditNoteFormHeaderFields from './CreditNoteFormHeaderFields';
import { getEntriesTotal } from 'containers/Entries/utils';
import { PageFormBigNumber } from 'components';
import withCurrentOrganization from 'containers/Organization/withCurrentOrganization';
import { compose } from 'utils';
/**
* Credit note header.
*/
function CreditNoteFormHeader({
// #withCurrentOrganization
organization: { base_currency },
}) {
const { values } = useFormikContext();
// Calculate the total amount.
const totalAmount = React.useMemo(
() => getEntriesTotal(values.entries),
[values.entries],
);
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<CreditNoteFormHeaderFields />
<PageFormBigNumber
label={intl.get('due_amount')}
amount={totalAmount}
currencyCode={base_currency}
/>
</div>
);
}
export default compose(withCurrentOrganization())(CreditNoteFormHeader);

View File

@@ -0,0 +1,125 @@
import React from 'react';
import { FormGroup, InputGroup, Position } from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import { FastField, Field, ErrorMessage } from 'formik';
import { CLASSES } from 'common/classes';
import classNames from 'classnames';
import {
ContactSelecetList,
FieldRequiredHint,
Icon,
FormattedMessage as T,
} from 'components';
import { customerNameFieldShouldUpdate } from './utils';
import { useCreditNoteFormContext } from './CreditNoteFormProvider';
import withSettings from 'containers/Settings/withSettings';
import withDialogActions from 'containers/Dialog/withDialogActions';
import {
momentFormatter,
compose,
tansformDateValue,
inputIntent,
handleDateChange,
} from 'utils';
/**
* Credit note form header fields.
*/
function CreditNoteFormHeaderFields() {
// Credit note form context.
const { customers } = useCreditNoteFormContext();
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'} />}
>
<ContactSelecetList
contactsList={customers}
selectedContactId={value}
defaultSelectText={<T id={'select_customer_account'} />}
onContactSelected={(customer) => {
form.setFieldValue('customer_id', customer.id);
}}
popoverFill={true}
/>
</FormGroup>
)}
</FastField>
{/* ----------- Credit note date ----------- */}
<FastField name={'invoice_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="invoice_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('invoice_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM_LEFT, minimal: true }}
inputProps={{
leftIcon: <Icon icon={'date-range'} />,
}}
/>
</FormGroup>
)}
</FastField>
{/* ----------- Credit note # ----------- */}
<Field name={'invoice_no'}>
{({ form, field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'credit_note.label_credit_note'} />}
labelInfo={<FieldRequiredHint />}
inline={true}
className={classNames('form-group--invoice-no', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="invoice_no" />}
>
<InputGroup minimal={true} {...field} />
</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 CreditNoteFormHeaderFields;

View File

@@ -0,0 +1,21 @@
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>
);
}

View File

@@ -0,0 +1,74 @@
import React from 'react';
import { useLocation } from 'react-router-dom';
import { isEmpty, pick } from 'lodash';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import { transformToEditForm } from './utils';
import { useInvoice, useItems, useCustomers } from 'hooks/query';
const CreditNoteFormContext = React.createContext();
/**
* Credit note data provider.
*/
function CreditNoteFormProvider({ creditNoteId, ...props }) {
const { state } = useLocation();
const invoiceId = state?.action;
// Fetches the invoice by the given id.
const { data: invoice, isLoading: isInvoiceLoading } = useInvoice(invoiceId, {
enabled: !!invoiceId,
});
// 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,
});
// const newCreditNote =
// Create and edit credit note mutations.
// Form submit payload.
const [submitPayload, setSubmitPayload] = React.useState();
// Determines whether the form in new mode.
const isNewMode = !creditNoteId;
// Provider payload.
const provider = {
invoice,
items,
customers,
invoiceId,
submitPayload,
isItemsLoading,
isCustomersLoading,
setSubmitPayload,
isNewMode,
};
return (
<DashboardInsider
loading={isInvoiceLoading || isItemsLoading || isCustomersLoading}
name={'credit-note-form'}
>
<CreditNoteFormContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const useCreditNoteFormContext = () => React.useContext(CreditNoteFormContext);
export { CreditNoteFormProvider, useCreditNoteFormContext };

View File

@@ -0,0 +1,41 @@
import React from 'react';
import { FastField } from 'formik';
import classNames from 'classnames';
import { CLASSES } from 'common/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>
);
}

View File

@@ -0,0 +1,88 @@
import React from 'react';
import moment from 'moment';
import intl from 'react-intl-universal';
import { useFormikContext } from 'formik';
import { Intent } from '@blueprintjs/core';
import { omit } from 'lodash';
import {
compose,
transformToForm,
repeatValue,
transactionNumber,
defaultFastFieldShouldUpdate,
} from 'utils';
import { AppToaster } from 'components';
import {
updateItemsEntriesTotal,
ensureEntriesHaveEmptyLine,
} from 'containers/Entries/utils';
export const MIN_LINES_NUMBER = 4;
// Default entry object.
export const defaultCreditNoteEntry = {
index: 0,
item_id: '',
rate: '',
discount: '',
quantity: '',
description: '',
amount: '',
};
// Default credit note object.
export const defaultCreditNote = {
customer_id: '',
invoice_date: moment(new Date()).format('YYYY-MM-DD'),
invoice_no: '',
invoice_no_manually: false,
reference_no: '',
invoice_message: '',
terms_conditions: '',
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 = compose(
ensureEntriesHaveEmptyLine(defaultCreditNoteEntry),
updateItemsEntriesTotal,
)(initialEntries);
return {
...transformToForm(creditNote, defaultCreditNote),
entries,
};
}
/**
* 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)
);
};

View File

@@ -0,0 +1,15 @@
import React from 'react';
const CreditNoteDeleteAlert = React.lazy(() =>
import('../../Alerts/CreditNotes/CreditNoteDeleteAlert'),
);
/**
* Sales Credit notes alerts.
*/
export default [
{
name: 'credit-note-delete',
component: CreditNoteDeleteAlert,
},
];

View File

@@ -0,0 +1,117 @@
import React from 'react';
import {
Button,
Classes,
NavbarDivider,
NavbarGroup,
Intent,
Alignment,
} from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import {
Icon,
FormattedMessage as T,
DashboardActionViewsList,
AdvancedFilterPopover,
DashboardFilterButton,
DashboardRowsHeightButton,
} from 'components';
import DashboardActionsBar from '../../../../components/Dashboard/DashboardActionsBar';
import withCreditNotes from './withCreditNotes';
import withCreditNotesActions from './withCreditNotesActions';
import withSettings from '../../../Settings/withSettings';
import withSettingsActions from '../../../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.
// credit note refresh action.
// Handle view tab change.
const handleTabChange = (view) => {
setCreditNotesTableState({ viewSlug: view ? view.slug : null });
};
// Handle click a refresh credit note.
const handleRefreshBtnClick = () => {};
// Handle table row size change.
const handleTableRowSizeChange = (size) => {
addSetting('salesCreditNote', 'tableSize', size);
};
return (
<DashboardActionsBar>
<NavbarGroup>
<DashboardActionViewsList
allMenuItem={true}
resourceName={'credit_note'}
views={[]}
onChange={handleTabChange}
/>
<NavbarDivider />
<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);

View File

@@ -0,0 +1,104 @@
import React from 'react';
import { useHistory } from 'react-router-dom';
import CreditNoteEmptyStatus from './CreditNotesEmptyStatus';
import { DataTable, DashboardContentTable } from 'components';
import { TABLES } from 'common/tables';
import { useMemorizedColumnsWidths } from 'hooks';
import TableSkeletonRows from 'components/Datatable/TableSkeletonRows';
import TableSkeletonHeader from 'components/Datatable/TableHeaderSkeleton';
import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withCreditNotesActions from './withCreditNotesActions';
import withSettings from '../../../Settings/withSettings';
import withAlertsActions from 'containers/Alert/withAlertActions';
import { useCreditNoteTableColumns } from './components';
import { useCreditNoteListContext } from './CreditNotesListProvider';
import { compose } from 'utils';
/**
* Credit note data table.
*/
function CreditNotesDataTable({
// #withCreditNotesActions
setCreditNotesTableState,
// #withAlertsActions
openAlert,
// #withSettings
creditNoteTableSize,
}) {
const history = useHistory();
// Credit note list context.
// Credit note table columns.
const columns = useCreditNoteTableColumns();
// Local storage memorizing columns widths.
const [initialColumnsWidths, , handleColumnResizing] =
useMemorizedColumnsWidths(TABLES.CREDIT_NOTE);
// Handles fetch data once the table state change.
const handleDataTableFetchData = React.useCallback(
({ pageSize, pageIndex, sortBy }) => {
setCreditNotesTableState({
pageSize,
pageIndex,
sortBy,
});
},
[setCreditNotesTableState],
);
// Handle delete credit note.
const handleDeleteCreditNote = ({ id }) => {
openAlert('sale-credit-note-delete', { creditNoteId: id });
};
// Handle edit credit note.
const hanldeEditCreditNote = (creditNote) => {
history.push(`/credit-notes/${creditNote.id}/edit`);
};
return (
<DashboardContentTable>
<DataTable
columns={columns}
data={[]}
// loading={}
// headerLoading={}
// progressBarLoading={}
onFetchData={handleDataTableFetchData}
manualSortBy={true}
selectionColumn={true}
noInitialFetch={true}
sticky={true}
autoResetSortBy={false}
autoResetPage={false}
TableLoadingRenderer={TableSkeletonRows}
TableHeaderSkeletonRenderer={TableSkeletonHeader}
initialColumnsWidths={initialColumnsWidths}
onColumnResizing={handleColumnResizing}
size={creditNoteTableSize}
payload={{
onDelete: handleDeleteCreditNote,
onEdit: hanldeEditCreditNote,
}}
/>
</DashboardContentTable>
);
}
export default compose(
withDashboardActions,
withCreditNotesActions,
withAlertsActions,
withSettings(({ creditNoteSettings }) => ({
creditNoteTableSize: creditNoteSettings?.tableSize,
})),
)(CreditNotesDataTable);

View File

@@ -0,0 +1,29 @@
import React from 'react';
import { Button, Intent } from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import { EmptyStatus } from 'components';
import { FormattedMessage as T } from 'components';
export default function CreditNotesEmptyStatus() {
return (
<EmptyStatus
title={<T id={'the_organization_doesn_t_receive_money_yet'} />}
description={
<p>
<T id={'credit_note.empty_status_description'} />
</p>
}
action={
<>
<Button intent={Intent.PRIMARY} large={true}>
<T id={'credit_note.new_credit_note'} />
</Button>
<Button intent={Intent.NONE} large={true}>
<T id={'learn_more'} />
</Button>
</>
}
/>
);
}

View File

@@ -0,0 +1,51 @@
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);

View File

@@ -0,0 +1,28 @@
import React from 'react';
import { isEmpty } from 'lodash';
import DashboardInsider from 'components/Dashboard/DashboardInsider';
import { getFieldsFromResourceMeta } from 'utils';
const CreditNoteListContext = React.createContext();
/**
* Credit note data provider.
*/
function CreditNotesListProvider({ query, tableStateChanged, ...props }) {
// Provider payload.
const provider = {};
return (
<DashboardInsider
// loading={}
name={'credit-note-list'}
>
<CreditNoteListContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const useCreditNoteListContext = () => React.useContext(CreditNoteListContext);
export { CreditNotesListProvider , useCreditNoteListContext };

View File

@@ -0,0 +1,46 @@
import React from 'react';
import { Alignment, Navbar, NavbarGroup } from '@blueprintjs/core';
import { DashboardViewsTabs } from 'components';
import withCreditNotes from './withCreditNotes';
import withCreditNotesActions from './withCreditNotesActions';
import { compose, transfromViewsToTabs } from 'utils';
import { useCreditNoteListContext } from './CreditNotesListProvider';
/**
* Credit Note views tabs.
*/
function CreditNotesViewTabs({
// #withCreditNotes
creditNoteCurrentView,
// #withCreditNotesActions
setCreditNotesTableState,
}) {
// Credit note list context.
// Handle click a new view tab.
const handleClickNewView = () => {};
// const tabs = transfromViewsToTabs(creditNoteCurrentView);
// Handle tab change.
const handleTabsChange = (viewSlug) => {
setCreditNotesTableState({ viewSlug });
};
return (
<Navbar className={'navbar--dashboard-views'}>
<NavbarGroup align={Alignment.LEFT}></NavbarGroup>
</Navbar>
);
}
export default compose(
withCreditNotesActions,
withCreditNotes(({ creditNoteTableState }) => ({
creditNoteCurrentView: creditNoteTableState.viewSlug,
})),
)(CreditNotesViewTabs);

View File

@@ -0,0 +1,122 @@
import React from 'react';
import {
Intent,
Tag,
Menu,
MenuItem,
MenuDivider,
ProgressBar,
} from '@blueprintjs/core';
import intl from 'react-intl-universal';
import clsx from 'classnames';
import { CLASSES } from '../../../../common/classes';
import {
FormatDateCell,
FormattedMessage as T,
AppToaster,
Choose,
If,
Icon,
} from 'components';
import { formattedAmount, safeCallback, calculateStatus } from 'utils';
export function ActionsMenu({
payload: {
onEdit,
onDeliver,
onDelete,
onDrawer,
onQuick,
onViewDetails,
onPrint,
},
row: { original },
}) {
return (
<Menu>
<MenuItem
icon={<Icon icon="reader-18" />}
text={intl.get('view_details')}
/>
<MenuDivider />
<MenuItem
icon={<Icon icon="pen-18" />}
text={intl.get('credit_note.label_edit_credit_note')}
onClick={safeCallback(onEdit, original)}
/>
<MenuItem
text={intl.get('credit_note.label_delete_credit_note')}
intent={Intent.DANGER}
onClick={safeCallback(onDelete, original)}
icon={<Icon icon="trash-16" iconSize={16} />}
/>
</Menu>
);
}
/**
* Retrieve credit note table columns.
*/
export function useCreditNoteTableColumns() {
return React.useMemo(
() => [
{
id: 'date',
Header: intl.get('date'),
accessor: 'date',
Cell: FormatDateCell,
width: 110,
className: 'date',
clickable: true,
textOverview: true,
},
{
id: 'customer',
Header: intl.get('customer_name'),
accessor: 'customer.display_name',
width: 180,
className: 'customer_id',
clickable: true,
textOverview: true,
},
{
id: 'credit_note',
Header: intl.get('credit_note.label_credit_note_no'),
accessor: 'credit_note',
width: 100,
className: 'credit_note',
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: 'status',
Header: intl.get('status'),
// accessor:
width: 120, // 160
className: 'status',
clickable: true,
},
{
id: 'reference_no',
Header: intl.get('reference_no'),
accessor: 'reference_no',
width: 90,
className: 'reference_no',
clickable: true,
textOverview: true,
},
],
[],
);
}

View File

@@ -0,0 +1,19 @@
import { connect } from 'react-redux';
import {
getCreditNoteTableStateFactory,
isCreditNoteTableStateChangedFactory,
} from '../../../../store/CreditNotes/creditNotes.selector';
export default (mapState) => {
const getCreditNoteTableState = getCreditNoteTableStateFactory();
const isCreditNoteTableChanged = isCreditNoteTableStateChangedFactory();
const mapStateToProps = (state, props) => {
const mapped = {
creditNoteTableState: getCreditNoteTableState(state, props),
creditNoteTableStateChanged: isCreditNoteTableChanged(state, props),
};
return mapState ? mapState(mapped, state, props) : mapped;
};
return connect(mapStateToProps);
};

View File

@@ -0,0 +1,12 @@
import { connect } from 'react-redux';
import {
setCreditNotesTableState,
resetCreditNotesTableState,
} from '../../../../store/CreditNotes/creditNotes.actions';
const mapDispatchToProps = (dispatch) => ({
setCreditNoteTableState: (state) => dispatch(setCreditNotesTableState(state)),
resetCreditNoteTableState: () => dispatch(resetCreditNotesTableState()),
});
export default connect(null, mapDispatchToProps);