re-structure to monorepo.

This commit is contained in:
a.bouhuolia
2023-02-03 01:02:31 +02:00
parent 8242ec64ba
commit 7a0a13f9d5
10400 changed files with 46966 additions and 17223 deletions

View File

@@ -0,0 +1,194 @@
// @ts-nocheck
import React from 'react';
import {
Intent,
Button,
ButtonGroup,
Popover,
PopoverInteractionKind,
Position,
Menu,
MenuItem,
} from '@blueprintjs/core';
import { FormattedMessage as T } from '@/components';
import { useHistory } from 'react-router-dom';
import { CLASSES } from '@/constants/classes';
import classNames from 'classnames';
import { useFormikContext } from 'formik';
import { If, Icon } from '@/components';
import { useBillFormContext } from './BillFormProvider';
/**
* Bill floating actions bar.
*/
export default function BillFloatingActions() {
const history = useHistory();
// Formik context.
const { resetForm, submitForm, isSubmitting } = useFormikContext();
// Bill form context.
const { bill, setSubmitPayload } = useBillFormContext();
// Handle submit as open button click.
const handleSubmitOpenBtnClick = (event) => {
setSubmitPayload({ redirect: true, status: true });
submitForm();
};
// Handle submit, open and anothe new button click.
const handleSubmitOpenAndNewBtnClick = (event) => {
setSubmitPayload({ redirect: false, status: true, resetForm: true });
submitForm();
};
// Handle submit as open & continue editing button click.
const handleSubmitOpenContinueEditingBtnClick = (event) => {
setSubmitPayload({ redirect: false, status: true });
submitForm();
};
// Handle submit as draft button click.
const handleSubmitDraftBtnClick = (event) => {
setSubmitPayload({ redirect: true, status: false });
submitForm();
};
// handle submit as draft & new button click.
const handleSubmitDraftAndNewBtnClick = (event) => {
setSubmitPayload({ redirect: false, status: false, resetForm: true });
submitForm();
};
// Handle submit as draft & continue editing button click.
const handleSubmitDraftContinueEditingBtnClick = (event) => {
setSubmitPayload({ redirect: false, status: 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={!bill || !bill?.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={bill && bill?.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={bill ? <T id={'reset'} /> : <T id={'clear'} />}
/>
{/* ----------- Cancel ----------- */}
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={handleCancelBtnClick}
text={<T id={'cancel'} />}
/>
</div>
);
}

View File

@@ -0,0 +1,59 @@
// @ts-nocheck
import * as Yup from 'yup';
import moment from 'moment';
import intl from 'react-intl-universal';
import { DATATYPES_LENGTH } from '@/constants/dataTypes';
import { isBlank } from '@/utils';
const BillFormSchema = Yup.object().shape({
vendor_id: Yup.number().required().label(intl.get('vendor_name_')),
bill_date: Yup.date().required().label(intl.get('bill_date_')),
due_date: Yup.date()
.min(Yup.ref('bill_date'), ({ path, min }) =>
intl.get('bill.validation.due_date', {
path,
min: moment(min).format('YYYY/MM/DD'),
}),
)
.required()
.label(intl.get('due_date_')),
bill_number: Yup.string()
.max(DATATYPES_LENGTH.STRING)
.label(intl.get('bill_number_')),
reference_no: Yup.string().nullable().min(1).max(DATATYPES_LENGTH.STRING),
note: Yup.string()
.trim()
.min(1)
.max(DATATYPES_LENGTH.TEXT)
.label(intl.get('note')),
open: Yup.boolean(),
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(),
}),
total: Yup.number().nullable(),
discount: Yup.number().nullable().min(0).max(DATATYPES_LENGTH.INT_10),
description: Yup.string().nullable().max(DATATYPES_LENGTH.TEXT),
}),
),
});
const CreateBillFormSchema = BillFormSchema;
const EditBillFormSchema = BillFormSchema;
export { CreateBillFormSchema, EditBillFormSchema };

View File

@@ -0,0 +1,138 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { Formik, Form } from 'formik';
import { Intent } from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import { isEmpty } from 'lodash';
import { CLASSES } from '@/constants/classes';
import { EditBillFormSchema, CreateBillFormSchema } from './BillForm.schema';
import BillFormHeader from './BillFormHeader';
import BillFloatingActions from './BillFloatingActions';
import BillFormFooter from './BillFormFooter';
import BillItemsEntriesEditor from './BillItemsEntriesEditor';
import BillFormTopBar from './BillFormTopBar';
import { AppToaster } from '@/components';
import { useBillFormContext } from './BillFormProvider';
import { compose, safeSumBy } from '@/utils';
import {
defaultBill,
filterNonZeroEntries,
transformToEditForm,
transformFormValuesToRequest,
handleErrors,
} from './utils';
import withCurrentOrganization from '@/containers/Organization/withCurrentOrganization';
/**
* Bill form.
*/
function BillForm({
// #withCurrentOrganization
organization: { base_currency },
}) {
const history = useHistory();
// Bill form context.
const { bill, isNewMode, submitPayload, createBillMutate, editBillMutate } =
useBillFormContext();
// Initial values in create and edit mode.
const initialValues = useMemo(
() => ({
...(!isEmpty(bill)
? {
...transformToEditForm(bill),
}
: {
...defaultBill,
currency_code: base_currency,
}),
}),
[bill, base_currency],
);
// 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.status,
};
// Handle the request success.
const onSuccess = (response) => {
AppToaster.show({
message: intl.get(
isNewMode
? 'the_bill_has_been_created_successfully'
: 'the_bill_has_been_edited_successfully',
{ number: values.bill_number },
),
intent: Intent.SUCCESS,
});
setSubmitting(false);
if (submitPayload.redirect) {
history.push('/bills');
}
if (submitPayload.resetForm) {
resetForm();
}
};
// Handle the request error.
const onError = ({
response: {
data: { errors },
},
}) => {
handleErrors(errors, { setErrors });
setSubmitting(false);
};
if (isNewMode) {
createBillMutate(form).then(onSuccess).catch(onError);
} else {
editBillMutate([bill.id, form]).then(onSuccess).catch(onError);
}
};
return (
<div
className={classNames(
CLASSES.PAGE_FORM,
CLASSES.PAGE_FORM_STRIP_STYLE,
CLASSES.PAGE_FORM_BILL,
)}
>
<Formik
validationSchema={isNewMode ? CreateBillFormSchema : EditBillFormSchema}
initialValues={initialValues}
onSubmit={handleFormSubmit}
>
<Form>
<BillFormTopBar />
<BillFormHeader />
<BillItemsEntriesEditor />
<BillFormFooter />
<BillFloatingActions />
</Form>
</Formik>
</div>
);
}
export default compose(withCurrentOrganization())(BillForm);

View File

@@ -0,0 +1,22 @@
// @ts-nocheck
import React from 'react';
import { BaseCurrency, BaseCurrencyRoot } from '@/components';
import { useBillFormContext } from './BillFormProvider';
/**
* Bill form currnecy tag.
* @returns
*/
export default function BillFormCurrencyTag() {
const { isForeignVendor, selectVendor } = useBillFormContext();
if (!isForeignVendor) {
return null;
}
return (
<BaseCurrencyRoot>
<BaseCurrency currency={selectVendor?.currency_code} />
</BaseCurrencyRoot>
);
}

View File

@@ -0,0 +1,32 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import styled from 'styled-components';
import { CLASSES } from '@/constants/classes';
import { Paper, Row, Col } from '@/components';
import { BillFormFooterLeft } from './BillFormFooterLeft';
import { BillFormFooterRight } from './BillFormFooterRight';
// Bill form floating actions.
export default function BillFormFooter() {
return (
<div class={classNames(CLASSES.PAGE_FORM_FOOTER)}>
<BillFooterPaper>
<Row>
<Col md={8}>
<BillFormFooterLeft />
</Col>
<Col md={4}>
<BillFormFooterRight />
</Col>
</Row>
</BillFooterPaper>
</div>
);
}
const BillFooterPaper = styled(Paper)`
padding: 20px;
`;

View File

@@ -0,0 +1,34 @@
// @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 BillFormFooterLeft() {
return (
<React.Fragment>
{/* --------- note --------- */}
<TermsConditsFormGroup
label={<T id={'bill_form.label.note'} />}
name={'note'}
>
<FEditableText
name={'note'}
placeholder={intl.get('bill_form.label.note.placeholder')}
/>
</TermsConditsFormGroup>
</React.Fragment>
);
}
const TermsConditsFormGroup = styled(FFormGroup)`
&.bp3-form-group {
.bp3-label {
font-size: 12px;
margin-bottom: 12px;
}
.bp3-form-content {
margin-left: 10px;
}
}
`;

View File

@@ -0,0 +1,52 @@
// @ts-nocheck
import React from 'react';
import styled from 'styled-components';
import {
T,
TotalLines,
TotalLine,
TotalLineBorderStyle,
TotalLineTextStyle,
} from '@/components';
import { useBillTotals } from './utils';
export function BillFormFooterRight() {
const {
formattedSubtotal,
formattedTotal,
formattedDueTotal,
formattedPaymentTotal,
} = useBillTotals();
return (
<BillTotalLines labelColWidth={'180px'} amountColWidth={'180px'}>
<TotalLine
title={<T id={'bill_form.label.subtotal'} />}
value={formattedSubtotal}
borderStyle={TotalLineBorderStyle.None}
/>
<TotalLine
title={<T id={'bill_form.label.total'} />}
value={formattedTotal}
borderStyle={TotalLineBorderStyle.SingleDark}
textStyle={TotalLineTextStyle.Bold}
/>
<TotalLine
title={<T id={'bill_form.label.total'} />}
value={formattedPaymentTotal}
borderStyle={TotalLineBorderStyle.None}
/>
<TotalLine
title={<T id={'bill_form.label.total'} />}
value={formattedDueTotal}
textStyle={TotalLineTextStyle.Bold}
/>
</BillTotalLines>
);
}
const BillTotalLines = styled(TotalLines)`
width: 100%;
color: #555555;
`;

View File

@@ -0,0 +1,34 @@
// @ts-nocheck
import React, { useMemo } from 'react';
import intl from 'react-intl-universal';
import classNames from 'classnames';
import { sumBy } from 'lodash';
import { useFormikContext } from 'formik';
import { CLASSES } from '@/constants/classes';
import { PageFormBigNumber } from '@/components';
import BillFormHeaderFields from './BillFormHeaderFields';
/**
* Fill form header.
*/
function BillFormHeader() {
const {
values: { currency_code, entries },
} = useFormikContext();
// Calculate the total due amount of bill entries.
const totalDueAmount = useMemo(() => sumBy(entries, 'amount'), [entries]);
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER)}>
<BillFormHeaderFields />
<PageFormBigNumber
label={intl.get('due_amount')}
amount={totalDueAmount}
currencyCode={currency_code}
/>
</div>
);
}
export default BillFormHeader;

View File

@@ -0,0 +1,198 @@
// @ts-nocheck
import React from 'react';
import styled from 'styled-components';
import classNames from 'classnames';
import { FormGroup, InputGroup, Classes, Position } from '@blueprintjs/core';
import { FastField, ErrorMessage } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import { FeatureCan, FormattedMessage as T } from '@/components';
import { CLASSES } from '@/constants/classes';
import {
FFormGroup,
VendorSelectField,
FieldRequiredHint,
Icon,
VendorDrawerLink,
} from '@/components';
import { useBillFormContext } from './BillFormProvider';
import { vendorsFieldShouldUpdate } from './utils';
import {
BillExchangeRateInputField,
BillProjectSelectButton,
} from './components';
import { ProjectsSelect } from '@/containers/Projects/components';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import {
momentFormatter,
compose,
tansformDateValue,
handleDateChange,
inputIntent,
} from '@/utils';
import { Features } from '@/constants';
/**
* Fill form header.
*/
function BillFormHeader() {
// Bill form context.
const { vendors, projects } = useBillFormContext();
return (
<div className={classNames(CLASSES.PAGE_FORM_HEADER_FIELDS)}>
{/* ------- Vendor name ------ */}
<FastField
name={'vendor_id'}
vendors={vendors}
shouldUpdate={vendorsFieldShouldUpdate}
>
{({ form, field: { value }, meta: { error, touched } }) => (
<FFormGroup
name={'vendor_id'}
label={<T id={'vendor_name'} />}
inline={true}
className={classNames(
'form-group--vendor-name',
'form-group--select-list',
CLASSES.FILL,
)}
labelInfo={<FieldRequiredHint />}
>
<VendorSelectField
contacts={vendors}
selectedContactId={value}
defaultSelectText={<T id={'select_vender_account'} />}
onContactSelected={(contact) => {
form.setFieldValue('vendor_id', contact.id);
form.setFieldValue('currency_code', contact?.currency_code);
}}
popoverFill={true}
allowCreate={true}
/>
{value && (
<VendorButtonLink vendorId={value}>
<T id={'view_vendor_details'} />
</VendorButtonLink>
)}
</FFormGroup>
)}
</FastField>
{/* ----------- Exchange rate ----------- */}
<BillExchangeRateInputField
name={'exchange_rate'}
formGroupProps={{ label: ' ', inline: true }}
/>
{/* ------- Bill date ------- */}
<FastField name={'bill_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'bill_date'} />}
inline={true}
labelInfo={<FieldRequiredHint />}
className={classNames(CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="bill_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('bill_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
inputProps={{ leftIcon: <Icon icon={'date-range'} /> }}
/>
</FormGroup>
)}
</FastField>
{/* ------- Due date ------- */}
<FastField name={'due_date'}>
{({ form, field: { value }, meta: { error, touched } }) => (
<FormGroup
label={<T id={'due_date'} />}
inline={true}
className={classNames(
'form-group--due-date',
'form-group--select-list',
CLASSES.FILL,
)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="due_date" />}
>
<DateInput
{...momentFormatter('YYYY/MM/DD')}
value={tansformDateValue(value)}
onChange={handleDateChange((formattedDate) => {
form.setFieldValue('due_date', formattedDate);
})}
popoverProps={{ position: Position.BOTTOM, minimal: true }}
inputProps={{
leftIcon: <Icon icon={'date-range'} />,
}}
/>
</FormGroup>
)}
</FastField>
{/* ------- Bill number ------- */}
<FastField name={'bill_number'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'bill_number'} />}
inline={true}
className={('form-group--bill_number', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="bill_number" />}
>
<InputGroup minimal={true} {...field} />
</FormGroup>
)}
</FastField>
{/* ------- Reference ------- */}
<FastField name={'reference_no'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'reference'} />}
inline={true}
className={classNames('form-group--reference', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="reference" />}
>
<InputGroup minimal={true} {...field} />
</FormGroup>
)}
</FastField>
{/*------------ Project name -----------*/}
<FeatureCan feature={Features.Projects}>
<FFormGroup
name={'project_id'}
label={<T id={'bill.project_name.label'} />}
inline={true}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ProjectsSelect
name={'project_id'}
projects={projects}
input={BillProjectSelectButton}
popoverFill={true}
/>
</FFormGroup>
</FeatureCan>
</div>
);
}
export default compose(withDialogActions)(BillFormHeader);
const VendorButtonLink = styled(VendorDrawerLink)`
font-size: 11px;
margin-top: 6px;
`;

View File

@@ -0,0 +1,19 @@
// @ts-nocheck
import React from 'react';
import { useParams } from 'react-router-dom';
import BillForm from './BillForm';
import { BillFormProvider } from './BillFormProvider';
import '@/style/pages/Bills/PageForm.scss';
export default function BillFormPage() {
const { id } = useParams();
const billId = parseInt(id, 10);
return (
<BillFormProvider billId={billId}>
<BillForm />
</BillFormProvider>
);
}

View File

@@ -0,0 +1,147 @@
// @ts-nocheck
import React, { createContext, useState } from 'react';
import { Features } from '@/constants';
import { useFeatureCan } from '@/hooks/state';
import { DashboardInsider } from '@/components/Dashboard';
import { useProjects } from '@/containers/Projects/hooks';
import {
useAccounts,
useVendors,
useItems,
useBill,
useWarehouses,
useBranches,
useSettings,
useCreateBill,
useEditBill,
} from '@/hooks/query';
const BillFormContext = createContext();
// Filter all purchasable items only.
const stringifiedFilterRoles = JSON.stringify([
{
index: 1,
fieldKey: 'purchasable',
value: true,
condition: '&&',
comparator: 'equals',
},
{
index: 2,
fieldKey: 'active',
value: true,
condition: '&&',
comparator: 'equals',
},
]);
/**
* Bill form provider.
*/
function BillFormProvider({ billId, ...props }) {
// Features guard.
const { featureCan } = useFeatureCan();
const isWarehouseFeatureCan = featureCan(Features.Warehouses);
const isBranchFeatureCan = featureCan(Features.Branches);
const isProjectsFeatureCan = featureCan(Features.Projects);
// Handle fetch accounts.
const { data: accounts, isLoading: isAccountsLoading } = useAccounts();
// Handle fetch vendors data table
const {
data: { vendors },
isLoading: isVendorsLoading,
} = useVendors({ page_size: 10000 });
// Handle fetch Items data table or list
const {
data: { items },
isLoading: isItemsLoading,
} = useItems({
page_size: 10000,
stringified_filter_roles: stringifiedFilterRoles,
});
// Handle fetch bill details.
const { data: bill, isLoading: isBillLoading } = useBill(billId, {
enabled: !!billId,
});
// 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 });
// Fetches the projects list.
const {
data: { projects },
isLoading: isProjectsLoading,
} = useProjects({}, { enabled: !!isProjectsFeatureCan });
// Handle fetching bill settings.
const { isFetching: isSettingLoading } = useSettings();
// Form submit payload.
const [submitPayload, setSubmitPayload] = useState({});
// Create and edit bills mutations.
const { mutateAsync: createBillMutate } = useCreateBill();
const { mutateAsync: editBillMutate } = useEditBill();
const isNewMode = !billId;
// Determines whether the warehouse and branches are loading.
const isFeatureLoading =
isWarehouesLoading || isBranchesLoading || isProjectsLoading;
const provider = {
accounts,
vendors,
items,
bill,
warehouses,
branches,
projects,
submitPayload,
isNewMode,
isSettingLoading,
isBillLoading,
isAccountsLoading,
isItemsLoading,
isVendorsLoading,
isFeatureLoading,
isBranchesSuccess,
isWarehousesSuccess,
createBillMutate,
editBillMutate,
setSubmitPayload,
};
return (
<DashboardInsider
loading={
isVendorsLoading || isItemsLoading || isAccountsLoading || isBillLoading
}
name={'bill-form'}
>
<BillFormContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const useBillFormContext = () => React.useContext(BillFormContext);
export { BillFormProvider, useBillFormContext };

View File

@@ -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 { useFeatureCan } from '@/hooks/state';
import {
Icon,
BranchSelect,
FeatureCan,
WarehouseSelect,
FormTopbar,
DetailsBarSkeletonBase,
} from '@/components';
import { useBillFormContext } from './BillFormProvider';
import { Features } from '@/constants';
/**
* Bill form topbar .
* @returns {JSX.Element}
*/
export default function BillFormTopBar() {
// 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}>
<BillFormSelectBranch />
</FeatureCan>
{featureCan(Features.Warehouses) && featureCan(Features.Branches) && (
<NavbarDivider />
)}
<FeatureCan feature={Features.Warehouses}>
<BillFormSelectWarehouse />
</FeatureCan>
</NavbarGroup>
</FormTopbar>
);
}
function BillFormSelectBranch() {
// Bill form context.
const { branches, isBranchesLoading } = useBillFormContext();
return isBranchesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<BranchSelect
name={'branch_id'}
branches={branches}
input={BillBranchSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function BillFormSelectWarehouse() {
// Bill form context.
const { warehouses, isWarehouesLoading } = useBillFormContext();
return isWarehouesLoading ? (
<DetailsBarSkeletonBase className={Classes.SKELETON} />
) : (
<WarehouseSelect
name={'warehouse_id'}
warehouses={warehouses}
input={BillWarehouseSelectButton}
popoverProps={{ minimal: true }}
/>
);
}
function BillWarehouseSelectButton({ label }) {
return (
<Button
text={intl.get('bill.warehouse_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'warehouse-16'} iconSize={16} />}
/>
);
}
function BillBranchSelectButton({ label }) {
return (
<Button
text={intl.get('bill.branch_button.label', { label })}
minimal={true}
small={true}
icon={<Icon icon={'branch-16'} iconSize={16} />}
/>
);
}

View File

@@ -0,0 +1,45 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import ItemsEntriesTable from '@/containers/Entries/ItemsEntriesTable';
import { FastField } from 'formik';
import { CLASSES } from '@/constants/classes';
import { useBillFormContext } from './BillFormProvider';
import { entriesFieldShouldUpdate } from './utils';
import { ITEM_TYPE } from '@/containers/Entries/utils';
/**
* Bill form body.
*/
export default function BillFormBody({ defaultBill }) {
const { items } = useBillFormContext();
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}
itemType={ITEM_TYPE.PURCHASABLE}
landedCost={true}
/>
)}
</FastField>
</div>
);
}

View File

@@ -0,0 +1,39 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import { Button } from '@blueprintjs/core';
import { useFormikContext } from 'formik';
import { ExchangeRateInputGroup } from '@/components';
import { useCurrentOrganization } from '@/hooks/state';
import { useBillIsForeignCustomer } from './utils';
/**
* bill exchange rate input field.
* @returns {JSX.Element}
*/
export function BillExchangeRateInputField({ ...props }) {
const currentOrganization = useCurrentOrganization();
const { values } = useFormikContext();
const isForeignCustomer = useBillIsForeignCustomer();
// Can't continue if the customer is not foreign.
if (!isForeignCustomer) {
return null;
}
return (
<ExchangeRateInputGroup
fromCurrency={values.currency_code}
toCurrency={currentOrganization.base_currency}
{...props}
/>
);
}
/**
* bill project select.
* @returns {JSX.Element}
*/
export function BillProjectSelectButton({ label }) {
return <Button text={label ?? intl.get('select_project')} />;
}

View File

@@ -0,0 +1,287 @@
// @ts-nocheck
import React from 'react';
import moment from 'moment';
import intl from 'react-intl-universal';
import * as R from 'ramda';
import { first } from 'lodash';
import { Intent } from '@blueprintjs/core';
import { useFormikContext } from 'formik';
import { AppToaster } from '@/components';
import {
defaultFastFieldShouldUpdate,
transformToForm,
repeatValue,
orderingLinesIndexes,
formattedAmount,
} from '@/utils';
import {
updateItemsEntriesTotal,
ensureEntriesHaveEmptyLine,
} from '@/containers/Entries/utils';
import { useCurrentOrganization } from '@/hooks/state';
import { isLandedCostDisabled, getEntriesTotal } from '@/containers/Entries/utils';
import { useBillFormContext } from './BillFormProvider';
export const MIN_LINES_NUMBER = 1;
// Default bill entry.
export const defaultBillEntry = {
index: 0,
item_id: '',
rate: '',
discount: '',
quantity: '',
description: '',
amount: '',
landed_cost: false,
};
// Default bill.
export const defaultBill = {
vendor_id: '',
bill_number: '',
bill_date: moment(new Date()).format('YYYY-MM-DD'),
due_date: moment(new Date()).format('YYYY-MM-DD'),
reference_no: '',
note: '',
open: '',
branch_id: '',
warehouse_id: '',
exchange_rate: 1,
currency_code: '',
entries: [...repeatValue(defaultBillEntry, MIN_LINES_NUMBER)],
};
export const ERRORS = {
// Bills
BILL_NUMBER_EXISTS: 'BILL.NUMBER.EXISTS',
ENTRIES_ALLOCATED_COST_COULD_NOT_DELETED:
'ENTRIES_ALLOCATED_COST_COULD_NOT_DELETED',
};
/**
* Transformes the bill to initial values of edit form.
*/
export const transformToEditForm = (bill) => {
const initialEntries = [
...bill.entries.map((entry) => ({
...transformToForm(entry, defaultBillEntry),
landed_cost_disabled: isLandedCostDisabled(entry.item),
})),
...repeatValue(
defaultBillEntry,
Math.max(MIN_LINES_NUMBER - bill.entries.length, 0),
),
];
const entries = R.compose(
ensureEntriesHaveEmptyLine(defaultBillEntry),
updateItemsEntriesTotal,
)(initialEntries);
return {
...transformToForm(bill, defaultBill),
entries,
};
};
/**
* Transformes bill entries to submit request.
*/
export const transformEntriesToSubmit = (entries) => {
const transformBillEntry = R.compose(
R.omit(['amount']),
R.curry(transformToForm)(R.__, defaultBillEntry),
);
return R.compose(orderingLinesIndexes, R.map(transformBillEntry))(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,
};
};
/**
* Handle delete errors.
*/
export const handleDeleteErrors = (errors) => {
if (
errors.find((error) => error.type === 'BILL_HAS_ASSOCIATED_PAYMENT_ENTRIES')
) {
AppToaster.show({
message: intl.get('cannot_delete_bill_that_has_payment_transactions'),
intent: Intent.DANGER,
});
}
if (
errors.find((error) => error.type === 'BILL_HAS_ASSOCIATED_LANDED_COSTS')
) {
AppToaster.show({
message: intl.get(
'cannot_delete_bill_that_has_associated_landed_cost_transactions',
),
intent: Intent.DANGER,
});
}
if (
errors.find((error) => error.type === 'BILL_HAS_APPLIED_TO_VENDOR_CREDIT')
) {
AppToaster.show({
message: intl.get(
'bills.error.you_couldn_t_delete_bill_has_reconciled_with_vendor_credit',
),
intent: Intent.DANGER,
});
}
};
/**
* Detarmines vendors fast field should update
*/
export const vendorsFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.vendors !== oldProps.vendors ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
/**
* Detarmines entries fast field should update.
*/
export const entriesFieldShouldUpdate = (newProps, oldProps) => {
return (
newProps.items !== oldProps.items ||
defaultFastFieldShouldUpdate(newProps, oldProps)
);
};
// Transform response error to fields.
export const handleErrors = (errors, { setErrors }) => {
if (errors.some((e) => e.type === ERRORS.BILL_NUMBER_EXISTS)) {
setErrors({
bill_number: intl.get('bill_number_exists'),
});
}
if (
errors.some(
(e) => e.type === ERRORS.ENTRIES_ALLOCATED_COST_COULD_NOT_DELETED,
)
) {
setErrors(
AppToaster.show({
intent: Intent.DANGER,
message: 'ENTRIES_ALLOCATED_COST_COULD_NOT_DELETED',
}),
);
}
};
export const useSetPrimaryBranchToForm = () => {
const { setFieldValue } = useFormikContext();
const { branches, isBranchesSuccess } = useBillFormContext();
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 } = useBillFormContext();
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 bill totals.
*/
export const useBillTotals = () => {
const {
values: { entries, currency_code: currencyCode },
} = useFormikContext();
// Retrieves the bili 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],
);
// Retrieves the payment total.
const paymentTotal = React.useMemo(() => 0, []);
// Retireves the formatted payment total.
const formattedPaymentTotal = React.useMemo(
() => formattedAmount(paymentTotal, currencyCode),
[paymentTotal, currencyCode],
);
// Retrieves the formatted due total.
const dueTotal = React.useMemo(
() => total - paymentTotal,
[total, paymentTotal],
);
// Retrieves the formatted due total.
const formattedDueTotal = React.useMemo(
() => formattedAmount(dueTotal, currencyCode),
[dueTotal, currencyCode],
);
return {
total,
paymentTotal,
dueTotal,
formattedTotal,
formattedSubtotal,
formattedPaymentTotal,
formattedDueTotal,
};
};
/**
* Detarmines whether the bill has foreign customer.
* @returns {boolean}
*/
export const useBillIsForeignCustomer = () => {
const { values } = useFormikContext();
const currentOrganization = useCurrentOrganization();
const isForeignCustomer = React.useMemo(
() => values.currency_code !== currentOrganization.base_currency,
[values.currency_code, currentOrganization.base_currency],
);
return isForeignCustomer;
};

View File

@@ -0,0 +1,125 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import { MenuItem } from '@blueprintjs/core';
import { formattedAmount } from '@/utils';
import { T, Icon, Choose, If } from '@/components';
import { RESOURCES_TYPES } from '@/constants/resourcesTypes';
import { AbilitySubject, BillAction } from '@/constants/abilityOption';
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
/**
* Universal search bill item select action.
*/
function BillUniversalSearchSelectComponent({
// #ownProps
resourceType,
resourceId,
onAction,
// #withDrawerActions
openDrawer,
}) {
if (resourceType === RESOURCES_TYPES.BILL) {
openDrawer('bill-drawer', { billId: resourceId });
onAction && onAction();
}
return null;
}
export const BillUniversalSearchSelect = withDrawerActions(
BillUniversalSearchSelectComponent,
);
/**
* Status accessor.
*/
export function BillStatus({ bill }) {
return (
<Choose>
<Choose.When condition={bill.is_fully_paid && bill.is_open}>
<span class="fully-paid-text">
<T id={'paid'} />
</span>
</Choose.When>
<Choose.When condition={bill.is_open}>
<Choose>
<Choose.When condition={bill.is_overdue}>
<span className={'overdue-status'}>
{intl.get('overdue_by', { overdue: bill.overdue_days })}
</span>
</Choose.When>
<Choose.Otherwise>
<span className={'due-status'}>
{intl.get('due_in', { due: bill.remaining_days })}
</span>
</Choose.Otherwise>
</Choose>
<If condition={bill.is_partially_paid}>
<span className="partial-paid">
{intl.get('day_partially_paid', {
due: formattedAmount(bill.due_amount, bill.currency_code),
})}
</span>
</If>
</Choose.When>
<Choose.Otherwise>
<span class="draft">
<T id={'draft'} />
</span>
</Choose.Otherwise>
</Choose>
);
}
/**
* Bill universal search item.
*/
export function BillUniversalSearchItem(
item,
{ handleClick, modifiers, query },
) {
return (
<MenuItem
active={modifiers.active}
text={
<div>
<div>{item.text}</div>
<span class="bp3-text-muted">
{item.reference.bill_number}{' '}
<Icon icon={'caret-right-16'} iconSize={16} />
{item.reference.formatted_bill_date}
</span>
</div>
}
label={
<>
<div class="amount">{item.reference.formatted_amount}</div>
<BillStatus bill={item.reference} />
</>
}
onClick={handleClick}
className={'universal-search__item--bill'}
/>
);
}
const billsToSearch = (bill) => ({
id: bill.id,
text: bill.vendor.display_name,
reference: bill,
});
export const universalSearchBillBind = () => ({
resourceType: RESOURCES_TYPES.BILL,
optionItemLabel: intl.get('bills'),
selectItemAction: BillUniversalSearchSelect,
itemRenderer: BillUniversalSearchItem,
itemSelect: billsToSearch,
permission: {
ability: BillAction.View,
subject: AbilitySubject.Bill,
},
});

View File

@@ -0,0 +1,167 @@
// @ts-nocheck
import React, { useState } from 'react';
import {
Button,
Classes,
NavbarDivider,
NavbarGroup,
Intent,
Alignment,
} from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import {
If,
Can,
Icon,
FormattedMessage as T,
DashboardActionViewsList,
DashboardFilterButton,
AdvancedFilterPopover,
DashboardRowsHeightButton,
DashboardActionsBar,
} from '@/components';
import { BillAction, AbilitySubject } from '@/constants/abilityOption';
import withBills from './withBills';
import withBillsActions from './withBillsActions';
import withSettings from '@/containers/Settings/withSettings';
import withSettingsActions from '@/containers/Settings/withSettingsActions';
import { useBillsListContext } from './BillsListProvider';
import { useRefreshBills } from '@/hooks/query/bills';
import { compose } from '@/utils';
/**
* Bills actions bar.
*/
function BillActionsBar({
// #withBillActions
setBillsTableState,
// #withBills
billsConditionsRoles,
// #withSettings
billsTableSize,
// #withSettingsActions
addSetting,
}) {
const history = useHistory();
// Bills refresh action.
const { refresh } = useRefreshBills();
// Bills list context.
const { billsViews, fields } = useBillsListContext();
// Handle click a new bill.
const handleClickNewBill = () => {
history.push('/bills/new');
};
// Handle tab change.
const handleTabChange = (view) => {
setBillsTableState({
viewSlug: view ? view.slug : null,
});
};
// Handle click a refresh bills
const handleRefreshBtnClick = () => {
refresh();
};
// Handle table row size change.
const handleTableRowSizeChange = (size) => {
addSetting('bills', 'tableSize', size);
};
return (
<DashboardActionsBar>
<NavbarGroup>
<DashboardActionViewsList
resourceName={'bills'}
views={billsViews}
allMenuItem={true}
allMenuItemText={<T id={'all'} />}
onChange={handleTabChange}
/>
<NavbarDivider />
<Can I={BillAction.Create} a={AbilitySubject.Bill}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'plus'} />}
text={<T id={'new_bill'} />}
onClick={handleClickNewBill}
/>
</Can>
<AdvancedFilterPopover
advancedFilterProps={{
conditions: billsConditionsRoles,
defaultFieldKey: 'bill_number',
fields: fields,
onFilterChange: (filterConditions) => {
setBillsTableState({ filterRoles: filterConditions });
},
}}
>
<DashboardFilterButton
conditionsCount={billsConditionsRoles.length}
/>
</AdvancedFilterPopover>
<If condition={false}>
<Button
className={Classes.MINIMAL}
icon={<Icon icon={'trash-16'} iconSize={16} />}
text={<T id={'delete'} />}
intent={Intent.DANGER}
// onClick={handleBulkDelete}
/>
</If>
<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={billsTableSize}
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(
withBillsActions,
withSettingsActions,
withBills(({ billsTableState }) => ({
billsConditionsRoles: billsTableState.filterRoles,
})),
withSettings(({ billsettings }) => ({
billsTableSize: billsettings?.tableSize,
})),
)(BillActionsBar);

View File

@@ -0,0 +1,22 @@
// @ts-nocheck
import React from 'react';
const BillOpenAlert = React.lazy(
() => import('@/containers/Alerts/Bills/BillOpenAlert'),
);
const BillDeleteAlert = React.lazy(
() => import('@/containers/Alerts/Bills/BillDeleteAlert'),
);
const BillLocatedLandedCostDeleteAlert = React.lazy(
() => import('@/containers/Alerts/Bills/BillLocatedLandedCostDeleteAlert'),
);
export default [
{ name: 'bill-delete', component: BillDeleteAlert },
{ name: 'bill-open', component: BillOpenAlert },
{
name: 'bill-located-cost-delete',
component: BillLocatedLandedCostDeleteAlert,
},
];

View File

@@ -0,0 +1,41 @@
// @ts-nocheck
import React from 'react';
import { Button, Intent } from '@blueprintjs/core';
import { useHistory } from 'react-router-dom';
import { EmptyStatus } from '@/components';
import { Can, FormattedMessage as T } from '@/components';
import { BillAction, AbilitySubject } from '@/constants/abilityOption';
export default function BillsEmptyStatus() {
const history = useHistory();
return (
<EmptyStatus
title={<T id={'manage_the_organization_s_services_and_products'} />}
description={
<p>
<T id="bill_empty_status_description" />
</p>
}
action={
<>
<Can I={BillAction.Create} a={AbilitySubject.Bill}>
<Button
intent={Intent.PRIMARY}
large={true}
onClick={() => {
history.push('/bills/new');
}}
>
<T id={'new_bill'} />
</Button>
<Button intent={Intent.NONE} large={true}>
<T id={'learn_more'} />
</Button>
</Can>
</>
}
/>
);
}

View File

@@ -0,0 +1,58 @@
// @ts-nocheck
import React, { useEffect } from 'react';
import { DashboardPageContent } from '@/components';
import '@/style/pages/Bills/List.scss';
import { BillsListProvider } from './BillsListProvider';
import BillsActionsBar from './BillsActionsBar';
import BillsViewsTabs from './BillsViewsTabs';
import BillsTable from './BillsTable';
import withBills from './withBills';
import withBillsActions from './withBillsActions';
import { transformTableStateToQuery, compose } from '@/utils';
/**
* Bills list.
*/
function BillsList({
// #withBills
billsTableState,
billsTableStateChanged,
// #withBillsActions
resetBillsTableState,
}) {
// Resets the accounts table state once the page unmount.
useEffect(
() => () => {
resetBillsTableState();
},
[resetBillsTableState],
);
return (
<BillsListProvider
query={transformTableStateToQuery(billsTableState)}
tableStateChanged={billsTableStateChanged}
>
<BillsActionsBar />
<DashboardPageContent>
<BillsViewsTabs />
<BillsTable />
</DashboardPageContent>
</BillsListProvider>
);
}
export default compose(
withBills(({ billsTableState, billsTableStateChanged }) => ({
billsTableState,
billsTableStateChanged,
})),
withBillsActions,
)(BillsList);

View File

@@ -0,0 +1,66 @@
// @ts-nocheck
import React, { createContext } from 'react';
import { isEmpty } from 'lodash';
import { DashboardInsider } from '@/components/Dashboard';
import { useResourceViews, useResourceMeta, useBills } from '@/hooks/query';
import { getFieldsFromResourceMeta } from '@/utils';
const BillsListContext = createContext();
/**
* Accounts chart data provider.
*/
function BillsListProvider({ query, tableStateChanged, ...props }) {
// Fetch accounts resource views and fields.
const { data: billsViews, isLoading: isViewsLoading } =
useResourceViews('bills');
// Fetch the accounts resource fields.
const {
data: resourceMeta,
isLoading: isResourceLoading,
isFetching: isResourceFetching,
} = useResourceMeta('bills');
// Fetch accounts list according to the given custom view id.
const {
data: { bills, pagination, filterMeta },
isLoading: isBillsLoading,
isFetching: isBillsFetching,
} = useBills(query, { keepPreviousData: true });
// Detarmines the datatable empty status.
const isEmptyStatus = isEmpty(bills) && !isBillsLoading && !tableStateChanged;
// Provider payload.
const provider = {
bills,
pagination,
billsViews,
resourceMeta,
fields: getFieldsFromResourceMeta(resourceMeta.fields),
isResourceLoading,
isResourceFetching,
isBillsLoading,
isBillsFetching,
isViewsLoading,
isEmptyStatus,
};
return (
<DashboardInsider
loading={isViewsLoading || isResourceLoading}
name={'bills'}
>
<BillsListContext.Provider value={provider} {...props} />
</DashboardInsider>
);
}
const useBillsListContext = () => React.useContext(BillsListContext);
export { BillsListProvider, useBillsListContext };

View File

@@ -0,0 +1,163 @@
// @ts-nocheck
import React, { useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import { TABLES } from '@/constants/tables';
import {
DataTable,
DashboardContentTable,
TableSkeletonRows,
TableSkeletonHeader,
} from '@/components';
import BillsEmptyStatus from './BillsEmptyStatus';
import withBills from './withBills';
import withBillActions from './withBillsActions';
import withAlertsActions from '@/containers/Alert/withAlertActions';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
import withSettings from '@/containers/Settings/withSettings';
import { useBillsTableColumns, ActionsMenu } from './components';
import { useBillsListContext } from './BillsListProvider';
import { useMemorizedColumnsWidths } from '@/hooks';
import { compose } from '@/utils';
/**
* Bills transactions datatable.
*/
function BillsDataTable({
// #withBillsActions
setBillsTableState,
// #withBills
billsTableState,
// #withAlerts
openAlert,
// #withDialogActions
openDialog,
// #withDrawerActions
openDrawer,
// #withSettings
billsTableSize,
}) {
// Bills list context.
const { bills, pagination, isBillsLoading, isBillsFetching, isEmptyStatus } =
useBillsListContext();
const history = useHistory();
// Bills table columns.
const columns = useBillsTableColumns();
const handleFetchData = useCallback(
({ pageIndex, pageSize, sortBy }) => {
setBillsTableState({
pageIndex,
pageSize,
sortBy,
});
},
[setBillsTableState],
);
// Handle bill edit action.
const handleEditBill = (bill) => {
history.push(`/bills/${bill.id}/edit`);
};
// Handle convert to vendor credit.
const handleConvertToVendorCredit = ({ id }) => {
history.push(`/vendor-credits/new?from_bill_id=${id}`, { billId: id });
};
// Handle bill delete action.
const handleDeleteBill = (bill) => {
openAlert('bill-delete', { billId: bill.id });
};
// Handle bill open action.
const handleOpenBill = (bill) => {
openAlert('bill-open', { billId: bill.id });
};
// Handle quick payment made action.
const handleQuickPaymentMade = ({ id }) => {
openDialog('quick-payment-made', { billId: id });
};
// handle allocate landed cost.
const handleAllocateLandedCost = ({ id }) => {
openDialog('allocate-landed-cost', { billId: id });
};
// Handle view detail bill.
const handleViewDetailBill = ({ id }) => {
openDrawer('bill-drawer', { billId: id });
};
// Handle cell click.
const handleCellClick = (cell, event) => {
openDrawer('bill-drawer', { billId: cell.row.original.id });
};
// Local storage memorizing columns widths.
const [initialColumnsWidths, , handleColumnResizing] =
useMemorizedColumnsWidths(TABLES.BILLS);
if (isEmptyStatus) {
return <BillsEmptyStatus />;
}
return (
<DashboardContentTable>
<DataTable
columns={columns}
data={bills}
loading={isBillsLoading}
headerLoading={isBillsLoading}
progressBarLoading={isBillsFetching}
onFetchData={handleFetchData}
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={billsTableSize}
payload={{
onDelete: handleDeleteBill,
onEdit: handleEditBill,
onOpen: handleOpenBill,
onQuick: handleQuickPaymentMade,
onAllocateLandedCost: handleAllocateLandedCost,
onViewDetails: handleViewDetailBill,
onConvert: handleConvertToVendorCredit,
}}
/>
</DashboardContentTable>
);
}
export default compose(
withBills(({ billsTableState }) => ({ billsTableState })),
withBillActions,
withAlertsActions,
withDrawerActions,
withDialogActions,
withSettings(({ billsettings }) => ({
billsTableSize: billsettings?.tableSize,
})),
)(BillsDataTable);

View File

@@ -0,0 +1,54 @@
// @ts-nocheck
import React from 'react';
import { Alignment, Navbar, NavbarGroup } from '@blueprintjs/core';
import { DashboardViewsTabs } from '@/components';
import { useBillsListContext } from './BillsListProvider';
import withBills from './withBills';
import withBillActions from './withBillsActions';
import { compose, transfromViewsToTabs } from '@/utils';
/**
* Bills view tabs.
*/
function BillViewTabs({
// #withBillActions
setBillsTableState,
// #withBills
billsCurrentView,
}) {
// Bills list context.
const { billsViews } = useBillsListContext();
// Handle tab chaging.
const handleTabsChange = (viewSlug) => {
setBillsTableState({
viewSlug: viewSlug || null,
});
};
const tabs = transfromViewsToTabs(billsViews);
return (
<Navbar className={'navbar--dashboard-views'}>
<NavbarGroup align={Alignment.LEFT}>
<DashboardViewsTabs
currentViewSlug={billsCurrentView}
resourceName={'bills'}
tabs={tabs}
onChange={handleTabsChange}
/>
</NavbarGroup>
</Navbar>
);
}
export default compose(
withBillActions,
withBills(({ billsTableState }) => ({
billsCurrentView: billsTableState.viewSlug,
})),
)(BillViewTabs);

View File

@@ -0,0 +1,235 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import {
Intent,
Menu,
MenuItem,
MenuDivider,
Tag,
ProgressBar,
} from '@blueprintjs/core';
import {
FormatDateCell,
FormattedMessage as T,
Icon,
If,
Choose,
Money,
Can,
} from '@/components';
import {
formattedAmount,
safeCallback,
isBlank,
calculateStatus,
} from '@/utils';
import {
BillAction,
PaymentMadeAction,
AbilitySubject,
} from '@/constants/abilityOption';
/**
* Actions menu.
*/
export function ActionsMenu({
payload: {
onEdit,
onOpen,
onDelete,
onQuick,
onConvert,
onViewDetails,
onAllocateLandedCost,
},
row: { original },
}) {
return (
<Menu>
<MenuItem
icon={<Icon icon="reader-18" />}
text={intl.get('view_details')}
onClick={safeCallback(onViewDetails, original)}
/>
<Can I={BillAction.Edit} a={AbilitySubject.Bill}>
<MenuDivider />
<MenuItem
icon={<Icon icon="pen-18" />}
text={intl.get('edit_bill')}
onClick={safeCallback(onEdit, original)}
/>
<MenuItem
icon={<Icon icon="convert_to" />}
text={intl.get('bill.convert_to_credit_note')}
onClick={safeCallback(onConvert, original)}
/>
<If condition={!original.is_open}>
<MenuItem
icon={<Icon icon={'check'} iconSize={18} />}
text={intl.get('mark_as_open')}
onClick={safeCallback(onOpen, original)}
/>
</If>
</Can>
<Can I={PaymentMadeAction.Create} a={AbilitySubject.PaymentMade}>
<If condition={original.is_open && !original.is_fully_paid}>
<MenuItem
icon={<Icon icon="quick-payment-16" iconSize={16} />}
text={intl.get('add_payment')}
onClick={safeCallback(onQuick, original)}
/>
</If>
</Can>
<MenuItem
icon={<Icon icon="receipt-24" iconSize={16} />}
text={intl.get('allocate_landed_coast')}
onClick={safeCallback(onAllocateLandedCost, original)}
/>
<Can I={BillAction.Delete} a={AbilitySubject.Bill}>
<MenuDivider />
<MenuItem
text={intl.get('delete_bill')}
intent={Intent.DANGER}
onClick={safeCallback(onDelete, original)}
icon={<Icon icon="trash-16" iconSize={16} />}
/>
</Can>
</Menu>
);
}
/**
* Amount accessor.
*/
export function AmountAccessor(bill) {
return !isBlank(bill.amount) ? (
<Money amount={bill.amount} currency={bill.currency_code} />
) : (
''
);
}
/**
* Status accessor.
*/
export function StatusAccessor(bill) {
return (
<div className={'status-accessor'}>
<Choose>
<Choose.When condition={bill.is_fully_paid && bill.is_open}>
<span className={'fully-paid-icon'}>
<Icon icon="small-tick" iconSize={18} />
</span>
<span class="fully-paid-text">
<T id={'paid'} />
</span>
</Choose.When>
<Choose.When condition={bill.is_open}>
<Choose>
<Choose.When condition={bill.is_overdue}>
<span className={'overdue-status'}>
{intl.get('overdue_by', { overdue: bill.overdue_days })}
</span>
</Choose.When>
<Choose.Otherwise>
<span className={'due-status'}>
{intl.get('due_in', { due: bill.remaining_days })}
</span>
</Choose.Otherwise>
</Choose>
<If condition={bill.is_partially_paid}>
<span className="partial-paid">
{intl.get('day_partially_paid', {
due: formattedAmount(bill.due_amount, bill.currency_code),
})}
</span>
<ProgressBar
animate={false}
stripes={false}
intent={Intent.PRIMARY}
value={calculateStatus(bill.balance, bill.amount)}
/>
</If>
</Choose.When>
<Choose.Otherwise>
<Tag minimal={true} round={true}>
<T id={'draft'} />
</Tag>
</Choose.Otherwise>
</Choose>
</div>
);
}
/**
* Retrieve bills table columns.
*/
export function useBillsTableColumns() {
return React.useMemo(
() => [
{
id: 'bill_date',
Header: intl.get('bill_date'),
accessor: 'bill_date',
Cell: FormatDateCell,
width: 110,
className: 'bill_date',
clickable: true,
},
{
id: 'vendor',
Header: intl.get('vendor_name'),
accessor: 'vendor.display_name',
width: 180,
className: 'vendor',
clickable: true,
},
{
id: 'bill_number',
Header: intl.get('bill_number'),
accessor: (row) => (row.bill_number ? `${row.bill_number}` : null),
width: 100,
className: 'bill_number',
clickable: true,
},
{
id: 'amount',
Header: intl.get('amount'),
accessor: AmountAccessor,
width: 120,
className: 'amount',
align: 'right',
clickable: true,
},
{
id: 'status',
Header: intl.get('status'),
accessor: StatusAccessor,
width: 160,
className: 'status',
clickable: true,
},
{
id: 'due_date',
Header: intl.get('due_date'),
accessor: 'due_date',
Cell: FormatDateCell,
width: 110,
className: 'due_date',
clickable: true,
},
{
id: 'reference_no',
Header: intl.get('reference_no'),
accessor: 'reference_no',
width: 90,
className: 'reference_no',
clickable: true,
},
],
[],
);
}

View File

@@ -0,0 +1,20 @@
// @ts-nocheck
import { connect } from 'react-redux';
import {
getBillsTableStateFactory,
billsTableStateChangedFactory,
} from '@/store/Bills/bills.selectors';
export default (mapState) => {
const getBillsTableState = getBillsTableStateFactory();
const billsTableStateChanged = billsTableStateChangedFactory();
const mapStateToProps = (state, props) => {
const mapped = {
billsTableState: getBillsTableState(state, props),
billsTableStateChanged: billsTableStateChanged(state, props),
};
return mapState ? mapState(mapped, state, props) : mapped;
};
return connect(mapStateToProps);
};

View File

@@ -0,0 +1,13 @@
// @ts-nocheck
import { connect } from 'react-redux';
import {
setBillsTableState,
resetBillsTableState,
} from '@/store/Bills/bills.actions';
const mapDispatchToProps = (dispatch) => ({
setBillsTableState: (queries) => dispatch(setBillsTableState(queries)),
resetBillsTableState: () => dispatch(resetBillsTableState()),
});
export default connect(null, mapDispatchToProps);