fix(BS|PL): report query.

This commit is contained in:
a.bouhuolia
2022-02-09 19:50:49 +02:00
parent b759d7327e
commit c361a5852c
15 changed files with 1090 additions and 849 deletions

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect } from 'react';
import moment from 'moment'; import moment from 'moment';
import { BalanceSheetAlerts, BalanceSheetLoadingBar } from './components'; import { BalanceSheetAlerts, BalanceSheetLoadingBar } from './components';
@@ -12,6 +12,7 @@ import { BalanceSheetBody } from './BalanceSheetBody';
import withBalanceSheetActions from './withBalanceSheetActions'; import withBalanceSheetActions from './withBalanceSheetActions';
import { useBalanceSheetQuery } from './utils';
import { compose } from 'utils'; import { compose } from 'utils';
/** /**
@@ -22,26 +23,22 @@ function BalanceSheet({
// #withBalanceSheetActions // #withBalanceSheetActions
toggleBalanceSheetFilterDrawer, toggleBalanceSheetFilterDrawer,
}) { }) {
const [filter, setFilter] = useState({ // Balance sheet query.
fromDate: moment().startOf('year').format('YYYY-MM-DD'), const { query, setLocationQuery } = useBalanceSheetQuery();
toDate: moment().endOf('year').format('YYYY-MM-DD'),
basis: 'cash',
displayColumnsType: 'total',
filterByOption: 'without-zero-balance',
});
// Handle re-fetch balance sheet after filter change. // Handle re-fetch balance sheet after filter change.
const handleFilterSubmit = (filter) => { const handleFilterSubmit = (filter) => {
const _filter = { const newFilter = {
...filter, ...filter,
fromDate: moment(filter.fromDate).format('YYYY-MM-DD'), fromDate: moment(filter.fromDate).format('YYYY-MM-DD'),
toDate: moment(filter.toDate).format('YYYY-MM-DD'), toDate: moment(filter.toDate).format('YYYY-MM-DD'),
}; };
setFilter({ ..._filter }); setLocationQuery({ ...newFilter });
}; };
// Handle number format submit. // Handle number format submit.
const handleNumberFormatSubmit = (values) => { const handleNumberFormatSubmit = (values) => {
setFilter({ setLocationQuery({
...filter, ...query,
numberFormat: values, numberFormat: values,
}); });
}; };
@@ -54,9 +51,9 @@ function BalanceSheet({
); );
return ( return (
<BalanceSheetProvider filter={filter}> <BalanceSheetProvider filter={query}>
<BalanceSheetActionsBar <BalanceSheetActionsBar
numberFormat={filter.numberFormat} numberFormat={query.numberFormat}
onNumberFormatSubmit={handleNumberFormatSubmit} onNumberFormatSubmit={handleNumberFormatSubmit}
/> />
<BalanceSheetLoadingBar /> <BalanceSheetLoadingBar />
@@ -65,7 +62,7 @@ function BalanceSheet({
<DashboardPageContent> <DashboardPageContent>
<FinancialStatement> <FinancialStatement>
<BalanceSheetHeader <BalanceSheetHeader
pageFilter={filter} pageFilter={query}
onSubmitFilter={handleFilterSubmit} onSubmitFilter={handleFilterSubmit}
/> />
<BalanceSheetBody /> <BalanceSheetBody />

View File

@@ -43,7 +43,6 @@ function BalanceSheetHeader({
}, },
defaultValues, defaultValues,
); );
// Validation schema. // Validation schema.
const validationSchema = getBalanceSheetHeaderValidationSchema(); const validationSchema = getBalanceSheetHeaderValidationSchema();

View File

@@ -4,12 +4,14 @@ import { FastField, Field } from 'formik';
import { FormGroup, Checkbox } from '@blueprintjs/core'; import { FormGroup, Checkbox } from '@blueprintjs/core';
import styled from 'styled-components'; import styled from 'styled-components';
import { FormattedMessage as T } from 'components'; import { Row, Col, FieldHint, FormattedMessage as T } from 'components';
import { Row, Col, FieldHint } from '../../../components';
import { import {
handlePreviousYearCheckBoxChange, handlePreviousYearCheckBoxChange,
handlePreviousYearChangeCheckboxChange,
handlePreviousPeriodCheckBoxChange, handlePreviousPeriodCheckBoxChange,
handlePreivousPeriodPercentageCheckboxChange,
handlePreviousYearPercentageCheckboxChange,
handlePreviousPeriodChangeCheckboxChange,
} from './utils'; } from './utils';
/** /**
@@ -19,7 +21,7 @@ export default function BalanceSheetHeaderComparisonPanal() {
return ( return (
<BalanceSheetComparisonWrap> <BalanceSheetComparisonWrap>
{/**----------- Previous Year -----------*/} {/**----------- Previous Year -----------*/}
<Field name={'previous_year'} type={'checkbox'}> <Field name={'previousYear'} type={'checkbox'}>
{({ form, field }) => ( {({ form, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
@@ -33,41 +35,29 @@ export default function BalanceSheetHeaderComparisonPanal() {
</Field> </Field>
<Row> <Row>
<Col xs={3}> <Col xs={3}>
<Field name={'previous_year_amount_change'} type={'checkbox'}> <Field name={'previousYearAmountChange'} type={'checkbox'}>
{({ form: { setFieldValue }, field }) => ( {({ form, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
inline={true} inline={true}
small={true} small={true}
label={<T id={'balance_sheet.total_change'} />} label={<T id={'balance_sheet.total_change'} />}
{...field} {...field}
onChange={({ currentTarget }) => { onChange={handlePreviousYearChangeCheckboxChange(form)}
setFieldValue('previous_year', currentTarget.checked);
setFieldValue(
'previous_year_amount_change',
currentTarget.checked,
);
}}
/> />
</FormGroup> </FormGroup>
)} )}
</Field> </Field>
</Col> </Col>
<Col xs={3}> <Col xs={3}>
<FastField name={'previous_year_percentage_change'} type={'checkbox'}> <FastField name={'previousYearPercentageChange'} type={'checkbox'}>
{({ form: { setFieldValue }, field }) => ( {({ form, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
inline={true} inline={true}
label={<T id={'balance_sheet.change'} />} label={<T id={'balance_sheet.change'} />}
{...field} {...field}
onChange={({ currentTarget }) => { onChange={handlePreviousYearPercentageCheckboxChange(form)}
setFieldValue('previous_year', currentTarget.checked);
setFieldValue(
'previous_year_percentage_change',
currentTarget.checked,
);
}}
/> />
</FormGroup> </FormGroup>
)} )}
@@ -75,7 +65,7 @@ export default function BalanceSheetHeaderComparisonPanal() {
</Col> </Col>
</Row> </Row>
{/*------------ Previous Period -----------*/} {/*------------ Previous Period -----------*/}
<FastField name={'previous_period'} type={'checkbox'}> <FastField name={'previousPeriod'} type={'checkbox'}>
{({ form, field }) => ( {({ form, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
@@ -90,44 +80,29 @@ export default function BalanceSheetHeaderComparisonPanal() {
</FastField> </FastField>
<Row> <Row>
<Col xs={3}> <Col xs={3}>
<FastField name={'previous_period_amount_change'} type={'checkbox'}> <FastField name={'previousPeriodAmountChange'} type={'checkbox'}>
{({ form: { setFieldValue }, field }) => ( {({ form, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
inline={true} inline={true}
small={true} small={true}
label={<T id={'balance_sheet.total_change'} />} label={<T id={'balance_sheet.total_change'} />}
{...field} {...field}
onChange={({ currentTarget }) => { onChange={handlePreviousPeriodChangeCheckboxChange(form)}
setFieldValue('previous_period', currentTarget.checked);
setFieldValue(
'previous_period_amount_change',
currentTarget.checked,
);
}}
/> />
</FormGroup> </FormGroup>
)} )}
</FastField> </FastField>
</Col> </Col>
<Col xs={3}> <Col xs={3}>
<FastField <FastField name={'previousPeriodPercentageChange'} type={'checkbox'}>
name={'previous_period_percentage_change'} {({ form, field }) => (
type={'checkbox'}
>
{({ form: { setFieldValue }, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
inline={true} inline={true}
label={<T id={'balance_sheet.change'} />} label={<T id={'balance_sheet.change'} />}
{...field} {...field}
onChange={({ currentTarget }) => { onChange={handlePreivousPeriodPercentageCheckboxChange(form)}
setFieldValue('previous_period', currentTarget.checked);
setFieldValue(
'previous_period_percentage_change',
currentTarget.checked,
);
}}
/> />
</FormGroup> </FormGroup>
)} )}
@@ -136,7 +111,7 @@ export default function BalanceSheetHeaderComparisonPanal() {
</Row> </Row>
{/**----------- % of Column -----------*/} {/**----------- % of Column -----------*/}
<FastField name={'percentage_of_column'} type={'checkbox'}> <FastField name={'percentageOfColumn'} type={'checkbox'}>
{({ field }) => ( {({ field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
@@ -150,7 +125,7 @@ export default function BalanceSheetHeaderComparisonPanal() {
</FastField> </FastField>
{/**----------- % of Row -----------*/} {/**----------- % of Row -----------*/}
<FastField name={'percentage_of_row'} type={'checkbox'}> <FastField name={'percentageOfRow'} type={'checkbox'}>
{({ field }) => ( {({ field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox

View File

@@ -1,4 +1,5 @@
import React, { createContext, useContext } from 'react'; import React, { createContext, useContext } from 'react';
import FinancialReportPage from '../FinancialReportPage'; import FinancialReportPage from '../FinancialReportPage';
import { useBalanceSheet } from 'hooks/query'; import { useBalanceSheet } from 'hooks/query';
import { transformFilterFormToQuery } from '../common'; import { transformFilterFormToQuery } from '../common';

View File

@@ -6,8 +6,7 @@ import { FormattedMessage as T, Icon, If } from 'components';
import { useBalanceSheetContext } from './BalanceSheetProvider'; import { useBalanceSheetContext } from './BalanceSheetProvider';
import FinancialLoadingBar from '../FinancialLoadingBar'; import FinancialLoadingBar from '../FinancialLoadingBar';
import { FinancialComputeAlert } from '../FinancialReportPage'; import { FinancialComputeAlert } from '../FinancialReportPage';
import { dynamicColumns } from './dynamicColumns';
import { dynamicColumns } from './utils';
/** /**
* Balance sheet alerts. * Balance sheet alerts.

View File

@@ -0,0 +1,333 @@
import * as R from 'ramda';
import { isEmpty } from 'lodash';
import { Align } from 'common';
import { CellTextSpan } from 'components/Datatable/Cells';
import { getColumnWidth } from 'utils';
const getTableCellValueAccessor = (index) => `cells[${index}].value`;
const getReportColWidth = (data, accessor, headerText) => {
return getColumnWidth(
data,
accessor,
{ magicSpacing: 10, minWidth: 100 },
headerText,
);
};
/**
* Account name column mapper.
*/
const accountNameMapper = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
key: column.key,
Header: column.label,
accessor,
className: column.key,
textOverview: true,
width: Math.max(width, 300),
sticky: Align.Left,
};
});
/**
* Assoc columns to total column.
*/
const assocColumnsToTotalColumn = R.curry((data, column, columnAccessor) => {
const columns = totalColumnsComposer(data, column);
return R.assoc('columns', columns, columnAccessor);
});
/**
* Detarmines whether the given column has children columns.
* @returns {boolean}
*/
const isColumnHasColumns = (column) => !isEmpty(column.children);
/**
*
* @param {*} data
* @param {*} column
* @returns
*/
const dateRangeSoloColumnAttrs = (data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
return {
accessor,
width: getReportColWidth(data, accessor),
};
};
/**
* Date range columns mapper.
*/
const dateRangeMapper = R.curry((data, column) => {
const isDateColumnHasColumns = isColumnHasColumns(column);
const columnAccessor = {
Header: column.label,
key: column.key,
disableSortBy: true,
textOverview: true,
align: isDateColumnHasColumns ? Align.Center : Align.Right,
};
return R.compose(
R.when(
R.always(isDateColumnHasColumns),
assocColumnsToTotalColumn(data, column),
),
R.when(
R.always(!isDateColumnHasColumns),
R.mergeLeft(dateRangeSoloColumnAttrs(data, column)),
),
)(columnAccessor);
});
/**
* Total column mapper.
*/
const totalMapper = R.curry((data, column) => {
const hasChildren = !isEmpty(column.children);
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
const columnAccessor = {
key: column.key,
Header: column.label,
accessor,
textOverview: true,
Cell: CellTextSpan,
width,
disableSortBy: true,
align: hasChildren ? Align.Center : Align.Right,
};
return R.compose(
R.when(R.always(hasChildren), assocColumnsToTotalColumn(data, column)),
)(columnAccessor);
});
/**
* `Percentage of column` column accessor.
*/
const percentageOfColumnAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* `Percentage of row` column accessor.
*/
const percentageOfRowAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous year column accessor.
*/
const previousYearAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Pervious year change column accessor.
*/
const previousYearChangeAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous year percentage column accessor.
*/
const previousYearPercentageAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period column accessor.
*/
const previousPeriodAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period change column accessor.
*/
const previousPeriodChangeAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period percentage column accessor.
*/
const previousPeriodPercentageAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
*
* @param {*} column
* @param {*} index
* @returns
*/
const totalColumnsMapper = R.curry((data, column) => {
return R.compose(
R.when(R.pathEq(['key'], 'total'), totalMapper(data)),
// Percetage of column/row.
R.when(
R.pathEq(['key'], 'percentage_of_column'),
percentageOfColumnAccessor(data),
),
R.when(
R.pathEq(['key'], 'percentage_of_row'),
percentageOfRowAccessor(data),
),
// Previous year.
R.when(R.pathEq(['key'], 'previous_year'), previousYearAccessor(data)),
R.when(
R.pathEq(['key'], 'previous_year_change'),
previousYearChangeAccessor(data),
),
R.when(
R.pathEq(['key'], 'previous_year_percentage'),
previousYearPercentageAccessor(data),
),
// Pervious period.
R.when(R.pathEq(['key'], 'previous_period'), previousPeriodAccessor(data)),
R.when(
R.pathEq(['key'], 'previous_period_change'),
previousPeriodChangeAccessor(data),
),
R.when(
R.pathEq(['key'], 'previous_period_percentage'),
previousPeriodPercentageAccessor(data),
),
)(column);
});
/**
* Total sub-columns composer.
*/
const totalColumnsComposer = R.curry((data, column) => {
return R.map(totalColumnsMapper(data), column.children);
});
/**
* Detarmines the given string starts with `date-range` string.
*/
const isMatchesDateRange = (r) => R.match(/^date-range/g, r).length > 0;
/**
* Dynamic column mapper.
*/
const dynamicColumnMapper = R.curry((data, column) => {
const indexTotalMapper = totalMapper(data);
const indexAccountNameMapper = accountNameMapper(data);
const indexDatePeriodMapper = dateRangeMapper(data);
return R.compose(
R.when(R.pathSatisfies(isMatchesDateRange, ['key']), indexDatePeriodMapper),
R.when(R.pathEq(['key'], 'name'), indexAccountNameMapper),
R.when(R.pathEq(['key'], 'total'), indexTotalMapper),
)(column);
});
/**
* Cash flow dynamic columns.
*/
export const dynamicColumns = (columns, data) => {
return R.map(dynamicColumnMapper(data), columns);
};

View File

@@ -1,27 +1,65 @@
import * as Yup from 'yup'; import React from 'react';
import * as R from 'ramda'; import * as R from 'ramda';
import { isEmpty } from 'lodash';
import intl from 'react-intl-universal';
import moment from 'moment'; import moment from 'moment';
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import { Align } from 'common'; import { transformToForm } from 'utils';
import { CellTextSpan } from 'components/Datatable/Cells'; import { useLocationQuery, useMutateLocationQuery } from 'hooks';
import { getColumnWidth } from 'utils';
const getTableCellValueAccessor = (index) => `cells[${index}].value`; /**
* Retrieves the default balance sheet query.
* @returns {}
*/
export const getDefaultBalanceSheetQuery = () => ({
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
basis: 'cash',
displayColumnsType: 'total',
filterByOption: 'without-zero-balance',
const getReportColWidth = (data, accessor, headerText) => { previousYear: false,
return getColumnWidth( previousYearAmountChange: false,
data, previousYearPercentageChange: false,
accessor,
{ magicSpacing: 10, minWidth: 100 }, previousPeriod: false,
headerText, previousPeriodAmountChange: false,
); previousPeriodPercentageChange: false,
// Percentage columns.
percentageColumn: false,
percentageRow: false,
});
/**
* Retrieves the balance sheet query.
*/
export const useBalanceSheetQuery = () => {
// Retrieves location query.
const locationQuery = useLocationQuery();
// Mutates the location query.
const { mutate: setLocationQuery } = useMutateLocationQuery();
// Merges the default filter query with location URL query.
const query = React.useMemo(() => {
const defaultQuery = getDefaultBalanceSheetQuery();
return {
...defaultQuery,
...transformToForm(Object.fromEntries([...locationQuery]), defaultQuery),
};
}, [locationQuery]);
return {
query,
locationQuery,
setLocationQuery,
};
}; };
/** /**
* * Retrieves the balance sheet header default values.
* @returns
*/ */
export const getBalanceSheetHeaderDefaultValues = () => { export const getBalanceSheetHeaderDefaultValues = () => {
return { return {
@@ -34,8 +72,7 @@ export const getBalanceSheetHeaderDefaultValues = () => {
}; };
/** /**
* * Retrieves the balance sheet header validation schema.
* @returns
*/ */
export const getBalanceSheetHeaderValidationSchema = () => export const getBalanceSheetHeaderValidationSchema = () =>
Yup.object().shape({ Yup.object().shape({
@@ -50,330 +87,81 @@ export const getBalanceSheetHeaderValidationSchema = () =>
}); });
/** /**
* Account name column mapper. * Handles previous year checkbox change.
*/ */
const accountNameMapper = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
key: column.key,
Header: column.label,
accessor,
className: column.key,
textOverview: true,
width: Math.max(width, 300),
sticky: Align.Left,
};
});
/**
* Assoc columns to total column.
*/
const assocColumnsToTotalColumn = R.curry((data, column, columnAccessor) => {
const columns = totalColumnsComposer(data, column);
return R.assoc('columns', columns, columnAccessor);
});
/**
* Detarmines whether the given column has children columns.
* @returns {boolean}
*/
const isColumnHasColumns = (column) => !isEmpty(column.children);
/**
*
* @param {*} data
* @param {*} column
* @returns
*/
const dateRangeSoloColumnAttrs = (data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
return {
accessor,
width: getReportColWidth(data, accessor),
};
};
/**
* Date range columns mapper.
*/
const dateRangeMapper = R.curry((data, column) => {
const isDateColumnHasColumns = isColumnHasColumns(column);
const columnAccessor = {
Header: column.label,
key: column.key,
disableSortBy: true,
textOverview: true,
align: isDateColumnHasColumns ? Align.Center : Align.Right,
};
return R.compose(
R.when(
R.always(isDateColumnHasColumns),
assocColumnsToTotalColumn(data, column),
),
R.when(
R.always(!isDateColumnHasColumns),
R.mergeLeft(dateRangeSoloColumnAttrs(data, column)),
),
)(columnAccessor);
});
/**
* Total column mapper.
*/
const totalMapper = R.curry((data, column) => {
const hasChildren = !isEmpty(column.children);
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
const columnAccessor = {
key: column.key,
Header: column.label,
accessor,
textOverview: true,
Cell: CellTextSpan,
width,
disableSortBy: true,
align: hasChildren ? Align.Center : Align.Right,
};
return R.compose(
R.when(R.always(hasChildren), assocColumnsToTotalColumn(data, column)),
)(columnAccessor);
});
/**
* `Percentage of column` column accessor.
*/
const percentageOfColumnAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* `Percentage of row` column accessor.
*/
const percentageOfRowAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous year column accessor.
*/
const previousYearAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Pervious year change column accessor.
*/
const previousYearChangeAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous year percentage column accessor.
*/
const previousYearPercentageAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period column accessor.
*/
const previousPeriodAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period change column accessor.
*/
const previousPeriodChangeAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period percentage column accessor.
*/
const previousPeriodPercentageAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
*
* @param {*} column
* @param {*} index
* @returns
*/
const totalColumnsMapper = R.curry((data, column) => {
return R.compose(
R.when(R.pathEq(['key'], 'total'), totalMapper(data)),
// Percetage of column/row.
R.when(
R.pathEq(['key'], 'percentage_of_column'),
percentageOfColumnAccessor(data),
),
R.when(
R.pathEq(['key'], 'percentage_of_row'),
percentageOfRowAccessor(data),
),
// Previous year.
R.when(R.pathEq(['key'], 'previous_year'), previousYearAccessor(data)),
R.when(
R.pathEq(['key'], 'previous_year_change'),
previousYearChangeAccessor(data),
),
R.when(
R.pathEq(['key'], 'previous_year_percentage'),
previousYearPercentageAccessor(data),
),
// Pervious period.
R.when(R.pathEq(['key'], 'previous_period'), previousPeriodAccessor(data)),
R.when(
R.pathEq(['key'], 'previous_period_change'),
previousPeriodChangeAccessor(data),
),
R.when(
R.pathEq(['key'], 'previous_period_percentage'),
previousPeriodPercentageAccessor(data),
),
)(column);
});
/**
* Total sub-columns composer.
*/
const totalColumnsComposer = R.curry((data, column) => {
return R.map(totalColumnsMapper(data), column.children);
});
/**
* Detarmines the given string starts with `date-range` string.
*/
const isMatchesDateRange = (r) => R.match(/^date-range/g, r).length > 0;
/**
* Dynamic column mapper.
*/
const dynamicColumnMapper = R.curry((data, column) => {
const indexTotalMapper = totalMapper(data);
const indexAccountNameMapper = accountNameMapper(data);
const indexDatePeriodMapper = dateRangeMapper(data);
return R.compose(
R.when(R.pathSatisfies(isMatchesDateRange, ['key']), indexDatePeriodMapper),
R.when(R.pathEq(['key'], 'name'), indexAccountNameMapper),
R.when(R.pathEq(['key'], 'total'), indexTotalMapper),
)(column);
});
/**
* Cash flow dynamic columns.
*/
export const dynamicColumns = (columns, data) => {
return R.map(dynamicColumnMapper(data), columns);
};
export const handlePreviousYearCheckBoxChange = R.curry((form, event) => { export const handlePreviousYearCheckBoxChange = R.curry((form, event) => {
const isChecked = event.currentTarget.checked; const isChecked = event.currentTarget.checked;
form.setFieldValue('previous_year', isChecked); form.setFieldValue('previousYear', isChecked);
form.setFieldValue('previous_year_amount_change', isChecked);
form.setFieldValue('previous_year_percentage_change', isChecked); if (!isChecked) {
form.setFieldValue('previousYearAmountChange', isChecked);
form.setFieldValue('previousYearPercentageChange', isChecked);
}
}); });
/**
* Handles previous period checkbox change.
*/
export const handlePreviousPeriodCheckBoxChange = R.curry((form, event) => { export const handlePreviousPeriodCheckBoxChange = R.curry((form, event) => {
const isChecked = event.currentTarget.checked; const isChecked = event.currentTarget.checked;
form.setFieldValue('previous_period', isChecked); form.setFieldValue('previousPeriod', isChecked);
form.setFieldValue('previous_period_amount_change', isChecked);
form.setFieldValue('previous_period_amount_change', isChecked); if (!isChecked) {
form.setFieldValue('previousPeriodAmountChange', isChecked);
form.setFieldValue('previousPeriodPercentageChange', isChecked);
}
}); });
/**
* Handles previous year change checkbox change.
*/
export const handlePreviousYearChangeCheckboxChange = R.curry((form, event) => {
const isChecked = event.currentTarget.checked;
if (isChecked) {
form.setFieldValue('previousYear', event.currentTarget.checked);
}
form.setFieldValue('previousYearAmountChange', event.currentTarget.checked);
});
/**
* Handles preivous year percentage checkbox change.
*/
export const handlePreviousYearPercentageCheckboxChange = R.curry(
(form, event) => {
const isChecked = event.currentTarget.checked;
if (isChecked) {
form.setFieldValue('previousYear', event.currentTarget.checked);
}
form.setFieldValue('previousYearPercentageChange', isChecked);
},
);
/**
* Handles previous period percentage checkbox change.
*/
export const handlePreivousPeriodPercentageCheckboxChange = R.curry(
(form, event) => {
const isChecked = event.currentTarget.checked;
if (isChecked) {
form.setFieldValue('previousPeriod', isChecked);
}
form.setFieldValue('previousPeriodPercentageChange', isChecked);
},
);
/**
* Handle previous period change checkbox change.
*/
export const handlePreviousPeriodChangeCheckboxChange = R.curry(
(form, event) => {
const isChecked = event.currentTarget.checked;
if (isChecked) {
form.setFieldValue('previousPeriod', isChecked);
}
form.setFieldValue('previousPeriodAmountChange', isChecked);
},
);

View File

@@ -5,6 +5,10 @@ import { transformFilterFormToQuery } from '../common';
const ProfitLossSheetContext = createContext(); const ProfitLossSheetContext = createContext();
/**
* Profit/loss sheet provider.
* @returns {React.JSX}
*/
function ProfitLossSheetProvider({ query, ...props }) { function ProfitLossSheetProvider({ query, ...props }) {
const { const {
data: profitLossSheet, data: profitLossSheet,

View File

@@ -1,6 +1,6 @@
import React, { useState } from 'react'; import React from 'react';
import moment from 'moment'; import moment from 'moment';
import { compose } from 'utils'; import * as R from 'ramda';
import ProfitLossSheetHeader from './ProfitLossSheetHeader'; import ProfitLossSheetHeader from './ProfitLossSheetHeader';
import ProfitLossActionsBar from './ProfitLossActionsBar'; import ProfitLossActionsBar from './ProfitLossActionsBar';
@@ -10,37 +10,35 @@ import DashboardPageContent from 'components/Dashboard/DashboardPageContent';
import withDashboardActions from 'containers/Dashboard/withDashboardActions'; import withDashboardActions from 'containers/Dashboard/withDashboardActions';
import withProfitLossActions from './withProfitLossActions'; import withProfitLossActions from './withProfitLossActions';
import { useProfitLossSheetQuery } from './utils';
import { ProfitLossSheetProvider } from './ProfitLossProvider'; import { ProfitLossSheetProvider } from './ProfitLossProvider';
import { ProfitLossSheetLoadingBar, ProfitLossSheetAlerts } from './components'; import { ProfitLossSheetLoadingBar } from './components';
import { ProfitLossBody } from './ProfitLossBody'; import { ProfitLossBody } from './ProfitLossBody';
/** /**
* Profit/Loss financial statement sheet. * Profit/Loss financial statement sheet.
* @returns {React.JSX}
*/ */
function ProfitLossSheet({ function ProfitLossSheet({
// #withProfitLossActions // #withProfitLossActions
toggleProfitLossFilterDrawer: toggleDisplayFilterDrawer, toggleProfitLossFilterDrawer: toggleDisplayFilterDrawer,
}) { }) {
const [filter, setFilter] = useState({ // Profit/loss sheet query.
basis: 'cash', const { query, setLocationQuery } = useProfitLossSheetQuery();
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
displayColumnsType: 'total',
filterByOption: 'with-transactions',
});
// Handle submit filter. // Handle submit filter.
const handleSubmitFilter = (filter) => { const handleSubmitFilter = (filter) => {
const _filter = { const newFilter = {
...filter, ...filter,
fromDate: moment(filter.fromDate).format('YYYY-MM-DD'), fromDate: moment(filter.fromDate).format('YYYY-MM-DD'),
toDate: moment(filter.toDate).format('YYYY-MM-DD'), toDate: moment(filter.toDate).format('YYYY-MM-DD'),
}; };
setFilter(_filter); setLocationQuery(newFilter);
}; };
// Handle number format submit. // Handle number format submit.
const handleNumberFormatSubmit = (numberFormat) => { const handleNumberFormatSubmit = (numberFormat) => {
setFilter({ setLocationQuery({
...filter, ...query,
numberFormat, numberFormat,
}); });
}; };
@@ -53,9 +51,9 @@ function ProfitLossSheet({
); );
return ( return (
<ProfitLossSheetProvider query={filter}> <ProfitLossSheetProvider query={query}>
<ProfitLossActionsBar <ProfitLossActionsBar
numberFormat={filter.numberFormat} numberFormat={query.numberFormat}
onNumberFormatSubmit={handleNumberFormatSubmit} onNumberFormatSubmit={handleNumberFormatSubmit}
/> />
<ProfitLossSheetLoadingBar /> <ProfitLossSheetLoadingBar />
@@ -63,7 +61,7 @@ function ProfitLossSheet({
<DashboardPageContent> <DashboardPageContent>
<ProfitLossSheetHeader <ProfitLossSheetHeader
pageFilter={filter} pageFilter={query}
onSubmitFilter={handleSubmitFilter} onSubmitFilter={handleSubmitFilter}
/> />
<ProfitLossBody /> <ProfitLossBody />
@@ -72,7 +70,7 @@ function ProfitLossSheet({
); );
} }
export default compose( export default R.compose(
withDashboardActions, withDashboardActions,
withProfitLossActions, withProfitLossActions,
)(ProfitLossSheet); )(ProfitLossSheet);

View File

@@ -1,11 +1,10 @@
import React from 'react'; import React from 'react';
import moment from 'moment'; import moment from 'moment';
import { Formik, Form } from 'formik'; import { Formik, Form } from 'formik';
import { FormattedMessage as T } from 'components'; import * as R from 'ramda';
import intl from 'react-intl-universal';
import * as Yup from 'yup';
import { Tabs, Tab, Button, Intent } from '@blueprintjs/core'; import { Tabs, Tab, Button, Intent } from '@blueprintjs/core';
import { FormattedMessage as T } from 'components';
import FinancialStatementHeader from 'containers/FinancialStatements/FinancialStatementHeader'; import FinancialStatementHeader from 'containers/FinancialStatements/FinancialStatementHeader';
import ProfitLossSheetHeaderGeneralPane from './ProfitLossSheetHeaderGeneralPane'; import ProfitLossSheetHeaderGeneralPane from './ProfitLossSheetHeaderGeneralPane';
import ProfitLossSheetHeaderComparisonPanel from './ProfitLossSheetHeaderComparisonPanel'; import ProfitLossSheetHeaderComparisonPanel from './ProfitLossSheetHeaderComparisonPanel';
@@ -13,8 +12,12 @@ import ProfitLossSheetHeaderComparisonPanel from './ProfitLossSheetHeaderCompari
import withProfitLoss from './withProfitLoss'; import withProfitLoss from './withProfitLoss';
import withProfitLossActions from './withProfitLossActions'; import withProfitLossActions from './withProfitLossActions';
import { compose } from 'utils'; import { useProfitLossHeaderValidationSchema } from './utils';
/**
* Profit/loss header.
* @returns {React.JSX}
*/
function ProfitLossHeader({ function ProfitLossHeader({
// #ownProps // #ownProps
pageFilter, pageFilter,
@@ -27,15 +30,7 @@ function ProfitLossHeader({
toggleProfitLossFilterDrawer: toggleFilterDrawer, toggleProfitLossFilterDrawer: toggleFilterDrawer,
}) { }) {
// Validation schema. // Validation schema.
const validationSchema = Yup.object().shape({ const validationSchema = useProfitLossHeaderValidationSchema();
fromDate: Yup.date().required().label(intl.get('from_date')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('to_date')),
filterByOption: Yup.string(),
displayColumnsType: Yup.string(),
});
// Initial values. // Initial values.
const initialValues = { const initialValues = {
@@ -43,13 +38,11 @@ function ProfitLossHeader({
fromDate: moment(pageFilter.fromDate).toDate(), fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(), toDate: moment(pageFilter.toDate).toDate(),
}; };
// Handle form submit. // Handle form submit.
const handleSubmit = (values, actions) => { const handleSubmit = (values, actions) => {
onSubmitFilter(values); onSubmitFilter(values);
toggleFilterDrawer(false); toggleFilterDrawer(false);
}; };
// Handles the cancel button click. // Handles the cancel button click.
const handleCancelClick = () => { const handleCancelClick = () => {
toggleFilterDrawer(false); toggleFilterDrawer(false);
@@ -97,7 +90,7 @@ function ProfitLossHeader({
); );
} }
export default compose( export default R.compose(
withProfitLoss(({ profitLossDrawerFilter }) => ({ withProfitLoss(({ profitLossDrawerFilter }) => ({
profitLossDrawerFilter, profitLossDrawerFilter,
})), })),

View File

@@ -9,6 +9,10 @@ import { Row, Col, FieldHint } from '../../../components';
import { import {
handlePreviousYearCheckBoxChange, handlePreviousYearCheckBoxChange,
handlePreviousPeriodCheckBoxChange, handlePreviousPeriodCheckBoxChange,
handlePreviousYearChangeCheckboxChange,
handlePreviousYearPercentageCheckboxChange,
handlePreviousPeriodChangeCheckboxChange,
handlePreviousPeriodPercentageCheckboxChange,
} from './utils'; } from './utils';
/** /**
@@ -18,7 +22,7 @@ export default function ProfitLossSheetHeaderComparisonPanel() {
return ( return (
<ProfitLossSheetComparisonWrap> <ProfitLossSheetComparisonWrap>
{/**----------- Previous Year -----------*/} {/**----------- Previous Year -----------*/}
<FastField name={'previous_year'} type={'checkbox'}> <FastField name={'previousYear'} type={'checkbox'}>
{({ form, field }) => ( {({ form, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
@@ -33,42 +37,30 @@ export default function ProfitLossSheetHeaderComparisonPanel() {
</FastField> </FastField>
<Row> <Row>
<Col xs={3}> <Col xs={3}>
<FastField name={'previous_year_amount_change'} type={'checkbox'}> <FastField name={'previousYearAmountChange'} type={'checkbox'}>
{({ form: { setFieldValue }, field }) => ( {({ form, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
inline={true} inline={true}
small={true} small={true}
label={<T id={'profit_loss_sheet.total_change'} />} label={<T id={'profit_loss_sheet.total_change'} />}
{...field} {...field}
onChange={({ currentTarget }) => { onChange={handlePreviousYearChangeCheckboxChange(form)}
setFieldValue('previous_year', currentTarget.checked);
setFieldValue(
'previous_year_amount_change',
currentTarget.checked,
);
}}
/> />
</FormGroup> </FormGroup>
)} )}
</FastField> </FastField>
</Col> </Col>
<Col xs={3}> <Col xs={3}>
<FastField name={'previous_year_percentage_change'} type={'checkbox'}> <FastField name={'previousYearPercentageChange'} type={'checkbox'}>
{({ form: { setFieldValue }, field }) => ( {({ form, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
inline={true} inline={true}
small={true} small={true}
label={<T id={'profit_loss_sheet.perentage_change'} />} label={<T id={'profit_loss_sheet.perentage_change'} />}
{...field} {...field}
onChange={({ currentTarget }) => { onChange={handlePreviousYearPercentageCheckboxChange(form)}
setFieldValue('previous_year', currentTarget.checked);
setFieldValue(
'previous_year_percentage_change',
currentTarget.checked,
);
}}
/> />
</FormGroup> </FormGroup>
)} )}
@@ -76,7 +68,7 @@ export default function ProfitLossSheetHeaderComparisonPanel() {
</Col> </Col>
</Row> </Row>
{/**----------- Previous Period (PP) -----------*/} {/**----------- Previous Period (PP) -----------*/}
<FastField name={'previous_period'} type={'checkbox'}> <FastField name={'previousPeriod'} type={'checkbox'}>
{({ form, field }) => ( {({ form, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
@@ -91,45 +83,30 @@ export default function ProfitLossSheetHeaderComparisonPanel() {
</FastField> </FastField>
<Row> <Row>
<Col xs={3}> <Col xs={3}>
<FastField name={'previous_period_amount_change'} type={'checkbox'}> <FastField name={'previousPeriodAmountChange'} type={'checkbox'}>
{({ form: { setFieldValue }, field }) => ( {({ form, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
inline={true} inline={true}
small={true} small={true}
label={<T id={'profit_loss_sheet.total_change'} />} label={<T id={'profit_loss_sheet.total_change'} />}
{...field} {...field}
onChange={({ currentTarget }) => { onChange={handlePreviousPeriodChangeCheckboxChange(form)}
setFieldValue('previous_period', currentTarget.checked);
setFieldValue(
'previous_period_amount_change',
currentTarget.checked,
);
}}
/> />
</FormGroup> </FormGroup>
)} )}
</FastField> </FastField>
</Col> </Col>
<Col xs={3}> <Col xs={3}>
<FastField <FastField name={'previousPeriodPercentageChange'} type={'checkbox'}>
name={'previous_period_percentage_change'} {({ form, field }) => (
type={'checkbox'}
>
{({ form: { setFieldValue }, field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
inline={true} inline={true}
small={true} small={true}
label={<T id={'profit_loss_sheet.perentage_change'} />} label={<T id={'profit_loss_sheet.perentage_change'} />}
{...field} {...field}
onChange={({ currentTarget }) => { onChange={handlePreviousPeriodPercentageCheckboxChange(form)}
setFieldValue('previous_period', currentTarget.checked);
setFieldValue(
'previous_period_percentage_change',
currentTarget.checked,
);
}}
/> />
</FormGroup> </FormGroup>
)} )}
@@ -137,7 +114,7 @@ export default function ProfitLossSheetHeaderComparisonPanel() {
</Col> </Col>
</Row> </Row>
{/**----------- % of Column -----------*/} {/**----------- % of Column -----------*/}
<FastField name={'percentage_column'} type={'checkbox'}> <FastField name={'percentageColumn'} type={'checkbox'}>
{({ field }) => ( {({ field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
@@ -150,7 +127,7 @@ export default function ProfitLossSheetHeaderComparisonPanel() {
)} )}
</FastField> </FastField>
{/**----------- % of Row -----------*/} {/**----------- % of Row -----------*/}
<FastField name={'percentage_row'} type={'checkbox'}> <FastField name={'percentageRow'} type={'checkbox'}>
{({ field }) => ( {({ field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
@@ -163,7 +140,7 @@ export default function ProfitLossSheetHeaderComparisonPanel() {
)} )}
</FastField> </FastField>
{/**----------- % of Expense -----------*/} {/**----------- % of Expense -----------*/}
<FastField name={'percentage_expense'} type={'checkbox'}> <FastField name={'percentageExpense'} type={'checkbox'}>
{({ field }) => ( {({ field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox
@@ -176,7 +153,7 @@ export default function ProfitLossSheetHeaderComparisonPanel() {
)} )}
</FastField> </FastField>
{/**----------- % of Income -----------*/} {/**----------- % of Income -----------*/}
<FastField name={'percentage_income'} type={'checkbox'}> <FastField name={'percentageIncome'} type={'checkbox'}>
{({ field }) => ( {({ field }) => (
<FormGroup labelInfo={<FieldHint />}> <FormGroup labelInfo={<FieldHint />}>
<Checkbox <Checkbox

View File

@@ -0,0 +1,383 @@
import * as R from 'ramda';
import { isEmpty } from 'lodash';
import { Align } from 'common';
import { CellTextSpan } from 'components/Datatable/Cells';
import { getColumnWidth } from 'utils';
const getTableCellValueAccessor = (index) => `cells[${index}].value`;
const getReportColWidth = (data, accessor, labelText) => {
return getColumnWidth(
data,
accessor,
{ magicSpacing: 10, minWidth: 100 },
labelText,
);
};
const isNodeHasChildren = (node) => !isEmpty(node.children);
/**
* `Percentage of income` column accessor.
*/
const percentageOfIncomeAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* `Percentage of expense` column accessor.
*/
const percentageOfExpenseAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* `Percentage of column` column accessor.
*/
const percentageOfColumnAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* `Percentage of row` column accessor.
*/
const percentageOfRowAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous year column accessor.
*/
const previousYearAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Pervious year change column accessor.
*/
const previousYearChangeAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous year percentage column accessor.
*/
const previousYearPercentageAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period column accessor.
*/
const previousPeriodAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period change column accessor.
*/
const previousPeriodChangeAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period percentage column accessor.
*/
const previousPeriodPercentageAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
*
* @param {*} column
* @param {*} index
* @returns
*/
const totalColumnsMapper = R.curry((data, column) => {
return R.compose(
R.when(R.pathEq(['key'], 'total'), totalColumn(data)),
// Percetage of column/row.
R.when(
R.pathEq(['key'], 'percentage_column'),
percentageOfColumnAccessor(data),
),
R.when(R.pathEq(['key'], 'percentage_row'), percentageOfRowAccessor(data)),
R.when(
R.pathEq(['key'], 'percentage_income'),
percentageOfIncomeAccessor(data),
),
R.when(
R.pathEq(['key'], 'percentage_expenses'),
percentageOfExpenseAccessor(data),
),
// Previous year.
R.when(R.pathEq(['key'], 'previous_year'), previousYearAccessor(data)),
R.when(
R.pathEq(['key'], 'previous_year_change'),
previousYearChangeAccessor(data),
),
R.when(
R.pathEq(['key'], 'previous_year_percentage'),
previousYearPercentageAccessor(data),
),
// Pervious period.
R.when(R.pathEq(['key'], 'previous_period'), previousPeriodAccessor(data)),
R.when(
R.pathEq(['key'], 'previous_period_change'),
previousPeriodChangeAccessor(data),
),
R.when(
R.pathEq(['key'], 'previous_period_percentage'),
previousPeriodPercentageAccessor(data),
),
)(column);
});
/**
* Total sub-columns composer.
*/
const totalColumnsComposer = R.curry((data, column) => {
return R.map(totalColumnsMapper(data), column.children);
});
/**
* Assoc columns to total column.
*/
const assocColumnsToTotalColumn = R.curry((data, column, columnAccessor) => {
const columns = totalColumnsComposer(data, column);
return R.assoc('columns', columns, columnAccessor);
});
/**
* Retrieves the total column.
*/
const totalColumn = R.curry((data, column) => {
const hasChildren = isNodeHasChildren(column);
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
key: column.key,
Header: column.label,
accessor,
textOverview: true,
Cell: CellTextSpan,
width,
disableSortBy: true,
align: hasChildren ? Align.Center : Align.Right,
};
});
/**
*
*/
const totalColumnCompose = R.curry((data, column) => {
const hasChildren = isNodeHasChildren(column);
return R.compose(
R.when(R.always(hasChildren), assocColumnsToTotalColumn(data, column)),
totalColumn(data),
)(column);
});
/**
* Account name column mapper.
*/
const accountNameColumn = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
key: column.key,
Header: column.label,
accessor,
className: column.key,
textOverview: true,
width: Math.max(width, 300),
sticky: Align.Left,
};
});
/**
*
* @param {*} data
* @param {*} column
* @returns
*/
const dateRangeSoloColumnAttrs = (data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
return {
accessor,
width: getReportColWidth(data, accessor),
};
};
/**
* Retrieves date range column.
*/
const dateRangeColumn = R.curry((data, column) => {
const isDateColumnHasColumns = isNodeHasChildren(column);
const columnAccessor = {
Header: column.label,
key: column.key,
disableSortBy: true,
textOverview: true,
align: isDateColumnHasColumns ? Align.Center : Align.Right,
};
return R.compose(
R.when(
R.always(isDateColumnHasColumns),
assocColumnsToTotalColumn(data, column),
),
R.when(
R.always(!isDateColumnHasColumns),
R.mergeLeft(dateRangeSoloColumnAttrs(data, column)),
),
)(columnAccessor);
});
/**
* Detarmines the given string starts with `date-range` string.
*/
const isMatchesDateRange = (r) => R.match(/^date-range/g, r).length > 0;
/**
*
* @param {} data
* @param {} column
*/
const dynamicColumnMapper = R.curry((data, column) => {
const indexTotalColumn = totalColumnCompose(data);
const indexAccountNameColumn = accountNameColumn(data);
const indexDatePeriodMapper = dateRangeColumn(data);
return R.compose(
R.when(R.pathSatisfies(isMatchesDateRange, ['key']), indexDatePeriodMapper),
R.when(R.pathEq(['key'], 'name'), indexAccountNameColumn),
R.when(R.pathEq(['key'], 'total'), indexTotalColumn),
)(column);
});
/**
*
* @param {*} columns
* @param {*} data
* @returns
*/
export const dynamicColumns = (columns, data) => {
return R.map(dynamicColumnMapper(data), columns);
};

View File

@@ -1,7 +1,12 @@
import React from 'react'; import React from 'react';
import { dynamicColumns } from './utils';
import { dynamicColumns } from './dynamicColumns';
import { useProfitLossSheetContext } from './ProfitLossProvider'; import { useProfitLossSheetContext } from './ProfitLossProvider';
/**
* Retrieves the profit/loss table columns.
* @returns
*/
export const useProfitLossSheetColumns = () => { export const useProfitLossSheetColumns = () => {
const { const {
profitLossSheet: { table }, profitLossSheet: { table },

View File

@@ -1,397 +1,159 @@
import React from 'react';
import * as R from 'ramda'; import * as R from 'ramda';
import { isEmpty } from 'lodash'; import moment from 'moment';
import intl from 'react-intl-universal';
import * as Yup from 'yup';
import { Align } from 'common'; import { useMutateLocationQuery, useLocationQuery } from 'hooks';
import { CellTextSpan } from 'components/Datatable/Cells'; import { transformToForm } from 'utils';
import { getColumnWidth } from 'utils';
const getTableCellValueAccessor = (index) => `cells[${index}].value`;
const getReportColWidth = (data, accessor, labelText) => {
return getColumnWidth(
data,
accessor,
{ magicSpacing: 10, minWidth: 100 },
labelText,
);
};
const isNodeHasChildren = (node) => !isEmpty(node.children);
/** /**
* `Percentage of income` column accessor. * Retrieves the default profit/loss sheet query.
*/
const percentageOfIncomeAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* `Percentage of expense` column accessor.
*/
const percentageOfExpenseAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* `Percentage of column` column accessor.
*/
const percentageOfColumnAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* `Percentage of row` column accessor.
*/
const percentageOfRowAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous year column accessor.
*/
const previousYearAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Pervious year change column accessor.
*/
const previousYearChangeAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous year percentage column accessor.
*/
const previousYearPercentageAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period column accessor.
*/
const previousPeriodAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period change column accessor.
*/
const previousPeriodChangeAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
* Previous period percentage column accessor.
*/
const previousPeriodPercentageAccessor = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
Header: column.label,
key: column.key,
accessor,
width,
align: Align.Right,
disableSortBy: true,
textOverview: true,
};
});
/**
*
* @param {*} column
* @param {*} index
* @returns * @returns
*/ */
const totalColumnsMapper = R.curry((data, column) => { export const getDefaultProfitLossQuery = () => ({
return R.compose( basis: 'cash',
R.when(R.pathEq(['key'], 'total'), totalColumn(data)), fromDate: moment().startOf('year').format('YYYY-MM-DD'),
// Percetage of column/row. toDate: moment().endOf('year').format('YYYY-MM-DD'),
R.when( displayColumnsType: 'total',
R.pathEq(['key'], 'percentage_column'), filterByOption: 'with-transactions',
percentageOfColumnAccessor(data),
), previousYear: false,
R.when(R.pathEq(['key'], 'percentage_row'), percentageOfRowAccessor(data)), previousYearAmountChange: false,
R.when( previousYearPercentageChange: false,
R.pathEq(['key'], 'percentage_income'),
percentageOfIncomeAccessor(data), previousPeriod: false,
), previousPeriodAmountChange: false,
R.when( previousPeriodPercentageChange: false,
R.pathEq(['key'], 'percentage_expenses'),
percentageOfExpenseAccessor(data), // Percentage columns.
), percentageColumn: false,
// Previous year. percentageRow: false,
R.when(R.pathEq(['key'], 'previous_year'), previousYearAccessor(data)), percentageIncome: false,
R.when( percentageExpense: false,
R.pathEq(['key'], 'previous_year_change'),
previousYearChangeAccessor(data),
),
R.when(
R.pathEq(['key'], 'previous_year_percentage'),
previousYearPercentageAccessor(data),
),
// Pervious period.
R.when(R.pathEq(['key'], 'previous_period'), previousPeriodAccessor(data)),
R.when(
R.pathEq(['key'], 'previous_period_change'),
previousPeriodChangeAccessor(data),
),
R.when(
R.pathEq(['key'], 'previous_period_percentage'),
previousPeriodPercentageAccessor(data),
),
)(column);
}); });
/** /**
* Total sub-columns composer. * Retrieves the balance sheet query API.
*/ */
const totalColumnsComposer = R.curry((data, column) => { export const useProfitLossSheetQuery = () => {
return R.map(totalColumnsMapper(data), column.children); // Retrieves location query.
}); const locationQuery = useLocationQuery();
/** // Mutate the location query.
* Assoc columns to total column. const { mutate: setLocationQuery } = useMutateLocationQuery();
*/
const assocColumnsToTotalColumn = R.curry((data, column, columnAccessor) => {
const columns = totalColumnsComposer(data, column);
return R.assoc('columns', columns, columnAccessor); // Merges the default query with location query.
}); const query = React.useMemo(() => {
const defaultQuery = getDefaultProfitLossQuery();
/** return {
* Retrieves the total column. ...defaultQuery,
*/ ...transformToForm(Object.fromEntries([...locationQuery]), defaultQuery),
const totalColumn = R.curry((data, column) => { };
const hasChildren = isNodeHasChildren(column); }, [locationQuery]);
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return { return {
key: column.key, query,
Header: column.label, locationQuery,
accessor, setLocationQuery,
textOverview: true,
Cell: CellTextSpan,
width,
disableSortBy: true,
align: hasChildren ? Align.Center : Align.Right,
};
});
/**
*
*/
const totalColumnCompose = R.curry((data, column) => {
const hasChildren = isNodeHasChildren(column);
return R.compose(
R.when(R.always(hasChildren), assocColumnsToTotalColumn(data, column)),
totalColumn(data),
)(column);
});
/**
* Account name column mapper.
*/
const accountNameColumn = R.curry((data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
const width = getReportColWidth(data, accessor, column.label);
return {
key: column.key,
Header: column.label,
accessor,
className: column.key,
textOverview: true,
width: Math.max(width, 300),
sticky: Align.Left,
};
});
/**
*
* @param {*} data
* @param {*} column
* @returns
*/
const dateRangeSoloColumnAttrs = (data, column) => {
const accessor = getTableCellValueAccessor(column.cell_index);
return {
accessor,
width: getReportColWidth(data, accessor),
}; };
}; };
/** /**
* Retrieves date range column. * Retrieves the profit/loss header validation schema.
*/
const dateRangeColumn = R.curry((data, column) => {
const isDateColumnHasColumns = isNodeHasChildren(column);
const columnAccessor = {
Header: column.label,
key: column.key,
disableSortBy: true,
textOverview: true,
align: isDateColumnHasColumns ? Align.Center : Align.Right,
};
return R.compose(
R.when(
R.always(isDateColumnHasColumns),
assocColumnsToTotalColumn(data, column),
),
R.when(
R.always(!isDateColumnHasColumns),
R.mergeLeft(dateRangeSoloColumnAttrs(data, column)),
),
)(columnAccessor);
});
/**
* Detarmines the given string starts with `date-range` string.
*/
const isMatchesDateRange = (r) => R.match(/^date-range/g, r).length > 0;
/**
*
* @param {} data
* @param {} column
*/
const dynamicColumnMapper = R.curry((data, column) => {
const indexTotalColumn = totalColumnCompose(data);
const indexAccountNameColumn = accountNameColumn(data);
const indexDatePeriodMapper = dateRangeColumn(data);
return R.compose(
R.when(R.pathSatisfies(isMatchesDateRange, ['key']), indexDatePeriodMapper),
R.when(R.pathEq(['key'], 'name'), indexAccountNameColumn),
R.when(R.pathEq(['key'], 'total'), indexTotalColumn),
)(column);
});
/**
*
* @param {*} columns
* @param {*} data
* @returns * @returns
*/ */
export const dynamicColumns = (columns, data) => { export const useProfitLossHeaderValidationSchema = () => {
return R.map(dynamicColumnMapper(data), columns); return Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('from_date')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('to_date')),
filterByOption: Yup.string(),
displayColumnsType: Yup.string(),
});
}; };
/**
* Handles the previous year checkbox change.
*/
export const handlePreviousYearCheckBoxChange = R.curry((form, event) => { export const handlePreviousYearCheckBoxChange = R.curry((form, event) => {
const isChecked = event.currentTarget.checked; const isChecked = event.currentTarget.checked;
form.setFieldValue('previous_year', isChecked);
form.setFieldValue('previous_year_amount_change', isChecked); form.setFieldValue('previousYear', isChecked);
form.setFieldValue('previous_year_percentage_change', isChecked);
if (!isChecked) {
form.setFieldValue('previousYearAmountChange', isChecked);
form.setFieldValue('previousYearPercentageChange', isChecked);
}
}); });
/**
* Handles the preivous period checkbox change.
*/
export const handlePreviousPeriodCheckBoxChange = R.curry((form, event) => { export const handlePreviousPeriodCheckBoxChange = R.curry((form, event) => {
const isChecked = event.currentTarget.checked; const isChecked = event.currentTarget.checked;
form.setFieldValue('previous_period', isChecked);
form.setFieldValue('previous_period_amount_change', isChecked); form.setFieldValue('previousPeriod', isChecked);
form.setFieldValue('previous_period_amount_change', isChecked);
if (!isChecked) {
form.setFieldValue('previousPeriodAmountChange', isChecked);
form.setFieldValue('previousPeriodPercentageChange', isChecked);
}
}); });
/**
* Handles previous year change amount checkbox change.
*/
export const handlePreviousYearChangeCheckboxChange = R.curry((form, event) => {
const isChecked = event.currentTarget.checked;
if (isChecked) {
form.setFieldValue('previousYear', isChecked);
}
form.setFieldValue('previousYearAmountChange', isChecked);
});
/**
* Handle previous year percentage checkbox change.
*/
export const handlePreviousYearPercentageCheckboxChange = R.curry(
(form, event) => {
const isChecked = event.currentTarget.checked;
if (isChecked) {
form.setFieldValue('previousYear', isChecked);
}
form.setFieldValue('previousYearPercentageChange', isChecked);
},
);
/**
* Handles previous period change amout checkbox change.
*/
export const handlePreviousPeriodChangeCheckboxChange = R.curry(
(form, event) => {
const isChecked = event.currentTarget.checked;
if (isChecked) {
form.setFieldValue('previousPeriod', isChecked);
}
form.setFieldValue('previousPeriodAmountChange', isChecked);
},
);
/**
* Handles previous period percentage checkbox change.
*/
export const handlePreviousPeriodPercentageCheckboxChange = R.curry(
(form, event) => {
const isChecked = event.currentTarget.checked;
if (isChecked) {
form.setFieldValue('previousPeriod', isChecked);
}
form.setFieldValue('previousPeriodPercentageChange', isChecked);
},
);

View File

@@ -1,4 +1,5 @@
import { useRef, useEffect, useMemo } from 'react'; import { useRef, useEffect, useMemo } from 'react';
import { useLocation, useHistory } from 'react-router';
import useAutofocus from './useAutofocus'; import useAutofocus from './useAutofocus';
import { useLocalStorage } from './utils/useLocalStorage'; import { useLocalStorage } from './utils/useLocalStorage';
@@ -53,3 +54,29 @@ export function useMemorizedColumnsWidths(tableName) {
}; };
return [get, save, handleColumnResizing]; return [get, save, handleColumnResizing];
} }
/**
* Retrieve the URL location search params.
*/
export const useLocationQuery = () => {
const { search } = useLocation();
return useMemo(() => {
return new URLSearchParams(search);
}, [search]);
};
/**
* Mutates the URL location params.
*/
export const useMutateLocationQuery = () => {
const location = useLocation();
const history = useHistory();
return {
mutate: (query) => {
const params = new URLSearchParams(query).toString();
history.push({ pathname: location.pathname, search: params.toString() });
},
};
};